Beispiel #1
0
    def post(self):
        # get the user details from the request sent by the client
        user_details = user_parser.parse_args()
        # check if the user exists before registering them
        user_db_row = User.get_user_by_email(user_details['email'])
        if user_db_row:
            err_msg = f"{user_details['email']} already exists"
            response_msg = helper.make_rest_fail_response(err_msg)
            return make_response(response_msg, 409)

        # check if user phone number exists
        phone_number = UserProfile.get_profile_by_phone_number(
            user_details["phone"])
        if phone_number:
            err_msg = f"{user_details['phone']} already exists"
            response_msg = helper.make_rest_fail_response(err_msg)
            return make_response(response_msg, 409)

        # save the user authentication details and profile details
        # in their respective database tables
        user_uuid = uuid.uuid4()
        new_user_authentication = User(user_uuid, user_details['email'],
                                       user_details['password'])
        new_user_authentication.save()

        new_user_profile = UserProfile(new_user_authentication.id,
                                       user_details['first_name'],
                                       user_details['last_name'],
                                       user_details['phone'])
        new_user_profile.save()

        new_user_role = UserRolePlacement(
            new_user_authentication.id,
            Role.fetch_role_by_name(user_details['role']))
        new_user_role.save()

        # Account confirmation email generation
        # Save extra user details depending on their role
        role = user_details["role"]
        self.onboard_client(role, new_user_authentication.id, user_details)

        #   Send a confirmation link to the user for account confirmation
        confirmation_code = token_handler.user_account_confirmation_token(
            new_user_authentication.id)
        email_template = helper.generate_confirmation_template(
            application.config['CONFIRMATION_ENDPOINT'], confirmation_code)
        subject = "Your account is inactive, please confirm account or check with your administrator"
        email_text = f"Use this link {application.config['CONFIRMATION_ENDPOINT']}/{confirmation_code}" \
                     f" to confirm your account"

        helper.send_email(user_details['email'], subject, email_template,
                          email_text)

        response_msg = helper.make_rest_success_response(
            "Registration successful, kindly"
            " check your email for confirmation link")
        return make_response(response_msg, 200)
Beispiel #2
0
    def post(self):
        # this is the POST request resource to handle user signin

        user_details = user_parser.parse_args()
        # check whether the user exists before confirming
        user_db_row = User.get_user_by_email(user_details['email'])

        if not user_db_row:
            response_msg = helper.make_rest_fail_response(
                "User email does not exist")
            return make_response(response_msg, 404)

        # good, let's go ahead and authenticate the user now
        # we also need to check whether the user account is verified or not
        # we don't want inactive accounts accessing our system
        if user_db_row.check_password_hash(user_details['password']):
            if user_db_row.is_active:
                # generate an access and refresh tokens for the user, for obvious reasons
                # also return the user role as a token claim, we'll need that for subsequent
                # requests from the client
                role = self.get_user_role(user_db_row.id)
                if role in ("IASTF", "BRSTF", "TASTF"):
                    # if the user is a staff,
                    # we need to make sure that the account has not been deactivated
                    # by their respective administrator
                    if staff_handler.check_account_status(
                            role, user_db_row.id) == False:
                        msg = "Your account has been blocked by your administrator"
                        return make_response(
                            helper.make_rest_fail_response(msg), 400)

                auth_tokens = token_handler.create_user_token(
                    user_db_row.id, role)
                response_dict = {
                    "authentication": auth_tokens,
                    "role": role,
                    "is_complete": user_db_row.is_complete
                }
                if role in ("BRSTF", "TASTF", "IASTF"):
                    # if the authenticated user is a staff member,
                    # get the corresponding permissions
                    response_dict[
                        'permission'] = UserPermissions.get_permission_by_user_id(
                            user_db_row.id)

                response_msg = helper.make_rest_success_response(
                    "Welcome", response_dict)
                return make_response(response_msg, 200)
            else:
                response_msg = helper.make_rest_fail_response(
                    "Please confirm your account before signing in.")
                return make_response(response_msg, 400)
        else:
            # wrong credentials passed, return the appropriate message
            response_msg = helper.make_rest_fail_response(
                "Wrong credentials passed, please try again")
            return make_response(response_msg, 400)
Beispiel #3
0
    def post(self):
        """
        send the user an email containing a link to set a new password
        :arg email {string} user email whose account we intend to recover
        :return:
        """
        user_details = user_parser.parse_args()
        user_row = User.get_user_by_email(user_details['email'])
        if user_row:
            profile_details = UserProfile.get_profile_by_user_id(user_row.id)
            account_token = token_handler.user_account_confirmation_token(
                user_row.id)
            email_text = f"To reset your account password, please follow this link " \
                         f"{application.config['ACCOUNT_RESET_ENDPOINT']}/{account_token}"
            email_template = helper.generate_account_recovery_template(
                application.config['ACCOUNT_RESET_ENDPOINT'], account_token,
                profile_details.first_name)
            subject = "Account Password Recovery"
            helper.send_email(user_details['email'], subject, email_template,
                              email_text)
            response_msg = helper.make_rest_success_response(
                "Successfully sent account recovery steps, check your"
                " email")
            return make_response(response_msg, 200)

        response_msg = helper.make_rest_fail_response(
            "There is not account associated with this email")
        return make_response(response_msg, 404)
    def get_customer_details(self, user_id):
        # use the user id to determine the customer's role, whether IND or ORG
        role_id = UserRolePlacement.fetch_role_by_user_id(user_id)
        # get role name using role_id
        role = Role.fetch_role_by_id(role_id)
        if role == 'IND':
            customer_no = IndividualCustomer.get_customer_number(user_id)
            if customer_no:
                user_profile = UserProfile.get_profile_by_user_id(user_id)
                data = {
                    "customer_number": customer_no,
                    "first_name": user_profile.first_name,
                    "last_name": user_profile.last_name,
                    "phone_number": user_profile.phone,
                    "kra_pin": user_profile.kra_pin,
                    "id_passport": user_profile.id_passport,
                }
                return data
            else:
                response_msg = helper.make_rest_fail_response(
                    "Customer does not exist")
                return make_response(response_msg, 404)

        elif role == 'ORG':
            # When the customer is an organization, their details are stored directly in the organization model
            # (not linked with the user profile)
            customer = OrganizationCustomer.get_customer_by_contact(user_id)
            if customer:
                # get customer details
                data = {}
                # TODO: Confirm from Tony whether to fetch organization details or contact person
                pass
Beispiel #5
0
    def get(self):
        data = OrganizationTypes.get_organization_customer_types()
        if data:
            message = "Request successful"
            response = helper.make_rest_success_response(message, data)
            return make_response(response, 200)

        message = "No data was found"
        response = helper.make_rest_fail_response(message)
        return make_response(response, 404)
Beispiel #6
0
    def get(self, object_name):
        bucket_name = app.config['S3_BUCKET']
        client_method = "put_object"
        s3_handler = S3FileHandler(bucket_name, object_name)
        response = s3_handler.generate_pre_signed_url(client_method)
        if response:
            return make_response(
                helper.make_rest_success_response("Success", response), 200)

        return make_response(helper.make_rest_fail_response("Failed"), 500)
Beispiel #7
0
    def get(self):
        """
        Get all loadings
        """
        loadings = Loadings.get_all_loadings()
        if loadings:
            response_msg = helper.make_rest_success_response(
                "Loadings", loadings)
            return make_response(response_msg, 200)

        return make_response(
            helper.make_rest_fail_response("No data was found"), 404)
Beispiel #8
0
    def get(self):
        """
        Get all extensions
        """
        extensions = Extension.get_all_extensions()
        if extensions:
            response = helper.make_rest_success_response(
                "Extensions", extensions)
            return make_response(response, 200)

        return make_response(
            helper.make_rest_fail_response("No data was found"), 404)
Beispiel #9
0
    def get(self):
        """
        Get all benefits
        """
        benefits = Benefit.get_all_benefits()
        if benefits:
            response_msg = helper.make_rest_success_response(
                "Benefits", benefits)
            return make_response(response_msg, 200)

        return make_response(
            helper.make_rest_fail_response("No data was found"), 404)
Beispiel #10
0
    def get(self):
        """
        Get all cars classified under a particular car make
        """
        # get car makes
        cars = CarMake.get_all_car_makes()
        if cars:
            response = helper.make_rest_success_response(
                "Success", {"cars": cars})
            return make_response(response, 200)

        return make_response(
            helper.make_rest_fail_response("No data was found"), 404)
Beispiel #11
0
    def get(self, object_name):
        """
        get the presigned url to fetch file from s3 resource
        :param object_name {String} the name of object to be uploaded
        """
        bucket_name = app.config['S3_BUCKET']
        s3_handler = S3FileHandler(bucket_name, object_name)
        response = s3_handler.generate_pre_signed_url()
        if response:
            return make_response(
                helper.make_rest_success_response("Success", response), 200)

        return make_response(helper.make_rest_fail_response("Failed"), 500)
Beispiel #12
0
    def get(self, master_id):
        """
        get the master policy and associated child policies
        :return:
        """
        result = MasterController.fetch_master_policy(master_id)
        if result:
            return make_response(
                helper.make_rest_success_response("Successfully fetched",
                                                  result), 200)

        return make_response(
            helper.make_rest_fail_response("Policy was not found"), 404)
    def put(self):
        """
        update staff details
        may be user permissions or to block staff member account
        """
        staff_details = user_parser.parse_args()
        staff = User.get_user_by_email(staff_details['email'])

        if staff_details['email'] and not staff:
            response_msg = helper.make_rest_fail_response(
                "User does not exist")
            return make_response(response_msg, 404)

        if staff_details['permissions']:
            if user_update.update_staff_permissions(
                    staff.id, staff_details['permissions']):
                response_msg = helper.make_rest_success_response(
                    "Update successful!")
                return make_response(response_msg, 200)
            else:
                response_msg = helper.make_rest_success_response(
                    "Failed to update staff permissions")
                return make_response(response_msg, 500)

        if type(staff_details['is_active']) == bool:
            # de/activate staff account
            claims = get_jwt_claims()
            role = claims['role']
            if staff_handler.update_account_status(role,
                                                   staff_details['staff_id'],
                                                   staff_details['is_active']):
                return make_response(
                    helper.make_rest_success_response("Update successful"),
                    200)
            else:
                return make_response(
                    helper.make_rest_fail_response(staff_details['is_active']),
                    500)
Beispiel #14
0
    def get(self, customer_number):
        """
        get the customer active child policies
        this is needed for the payments module where user's active policy payments will be tracked
        :return:
        """
        customers = ChildPolicy.get_child_policies(customer_number)
        if customers:
            return make_response(
                helper.make_rest_success_response("success", customers), 200)

        return make_response(
            helper.make_rest_fail_response("No customer policies were found"),
            404)
Beispiel #15
0
    def get(self):
        """
        get user profile details
        """
        user_id = get_jwt_identity()
        claims = get_jwt_claims()
        role = claims['role']
        profile_data = self.fetch_profile_data(role, user_id)
        if profile_data is None:
            response = helper.make_rest_fail_response("No user was found")
            return make_response(response, 404)

        response = helper.make_rest_success_response(None, profile_data)
        return make_response(response, 200)
    def post(self):
        """
        make a new policy payment to the database
        """
        payment_details = payments_parser.parse_args()
        new_installment = PolicyPayments(
            payment_details['transaction_type'], payment_details['amount'],
            payment_details['customer_no'], payment_details['child_policy_id'],
            payment_details['next_date'], payment_details['amount_due'],
            payment_details['transaction_code'])
        if new_installment.add():
            response_message = "Successfully made new installment"
            return make_response(
                helper.make_rest_success_response(response_message), 200)

        response_message = "Failed to make new payment installmnet"
        return make_response(helper.make_rest_fail_response(response_message),
                             500)
Beispiel #17
0
    def get(self, child_id):
        """
        Process request to get all unselected benefits and extensions
        of a policy holder, and the rest of the policy details
        :param policy_id:
        :return:
        """
        child = ChildPolicy.get_child_by_id(child_id).serialize()
        result = ChildController.get_unselected_benefits_extensions(child_id)
        if child:
            if result:
                child.update({"unselected_benefits": result})

            return make_response(
                helper.make_rest_success_response("Success", child), 200)

        else:
            return make_response(
                helper.make_rest_fail_response("Policy does not exist"), 404)
Beispiel #18
0
    def put(self):
        """
        when the user resets the password, 
        we will update the same here
        :return:
        """
        user_id = get_jwt_identity()
        user_details = user_parser.parse_args()
        user = User.get_user_by_id(user_id)
        if user:
            updateController.update_user_password(user_details['new_password'],
                                                  user_id)
            response_msg = helper.make_rest_success_response(
                "Successfully recovered user account")
            return make_response(response_msg, 200)

        response_msg = helper.make_rest_fail_response(
            "Sorry, user does not exist in this database")
        return make_response(response_msg, 404)
Beispiel #19
0
    def get(self):
        """
        get agent specific customers
        :return:
        """
        current_user = get_jwt_identity()
        current_user_claims = get_jwt_claims()
        current_user_role = current_user_claims['role']
        agency_id = customer.get_agent_id(current_user_role, current_user)
        agency_customers = customer.get_customer_details(
            current_user_role, agency_id)

        if agency_customers:
            return make_response(
                helper.make_rest_success_response("Success", agency_customers),
                200)
        else:
            return make_response(
                helper.make_rest_fail_response(
                    "No customers, better get to work!"), 404)
Beispiel #20
0
    def put(self):
        """
        authentication token is sent here for confirmation
        token must be valid for account to be activated
        """
        # the user id is needed to needed to know the user whose account we are activating
        user_id = get_jwt_identity()
        user_row = User.get_user_by_id(user_id)
        if user_row:
            if user_row.is_active:
                response = helper.make_rest_success_response(
                    "Your account is already active, please login")
                return make_response(response, 200)
            data = {'is_active': True}
            user_row.update(data)
            response = helper.make_rest_success_response(
                "Your account has been activated, you can now log in")
            return make_response(response, 200)

        # the user has not been found in the database
        response = helper.make_rest_fail_response("User does not exist")
        return make_response(response, 404)
Beispiel #21
0
    def get(self, user_id):
        """
        If the jwt token has expired
        a user can request for another token here simple by passing in the user_id
        """
        user_row = User.get_user_by_id(user_id)
        if user_row:
            # awesome, user account exists, let's go ahead and resend the activation email to the user
            confirmation_code = token_handler.user_account_confirmation_token(
                user_id)
            email_template = helper.generate_confirmation_template(
                application.config['CONFIRMATION_ENDPOINT'], confirmation_code)
            subject = "Please confirm your account"
            email_text = f"Use this link {application.config['CONFIRMATION_ENDPOINT']}/{confirmation_code}" \
                         f" to confirm your account"
            helper.send_email(user_row.email, subject, email_template,
                              email_text)
            response = helper.make_rest_success_response(
                "Please check your email to confirm your account")
            return make_response(response, 200)

        response = helper.make_rest_fail_response(
            "User was not found, please try again or register a new account")
        return make_response(response, 404)
    def post(self):
        # get the staff details from the request sent by the client
        user_details = user_parser.parse_args()
        # check if the staff exists before registering them
        user_db_row = User.get_user_by_email(user_details['email'])
        if user_db_row:
            err_msg = f"{user_details['first_name']} {user_details['last_name']} already exists"
            response_msg = helper.make_rest_fail_response(err_msg)
            return make_response(response_msg, 409)

        # create user account
        user_uuid = uuid.uuid4()
        # Create temporary seven digit password
        temporary_pass = helper.create_user_password()
        new_user = User(user_uuid, user_details['email'], temporary_pass)
        new_user.save()

        # create user profile
        new_user_profile = UserProfile(new_user.id, user_details['first_name'],
                                       user_details['last_name'],
                                       user_details['phone'])
        new_user_profile.save()

        # get organization details from JWT, such as the role of the client enrolling the staff, and their UID
        uid = get_jwt_identity()

        # get user role
        claims = get_jwt_claims()
        role = claims['role']

        # role = 'BR'

        # get agency_id
        agency_id = staff_handler.get_agency_id(role, uid)

        # Add staff to the appropriate table: i.e BRStaff, TRStaff, IAStaff
        # We also assign the staff roles at this stage,
        # depending on the entities they operate under, i.e BRSTF, IASTF, TASTF
        self.add_staff(role, agency_id, new_user.id)

        # store staff permissions
        self.set_permissions(user_details['permissions'], new_user.id)

        # send email to with the activation details for the staff
        # Temporary password email
        email_template = helper.generate_temporary_password_template(
            application.config['LOGIN_ENDPOINT'], temporary_pass)
        subject = "Nexure Temporary Password"
        email_text = f"Follow {application.config['LOGIN_ENDPOINT']} to login and use {temporary_pass} as your temporary password"
        helper.send_email(user_details['email'], subject, email_template,
                          email_text)

        #  Generate a user account activation email
        confirmation_code = token_handler.user_account_confirmation_token(
            new_user.id)
        email_template = helper.generate_confirmation_template(
            application.config['CONFIRMATION_ENDPOINT'], confirmation_code)
        subject = "Please confirm your account"
        email_text = f"Use this link {application.config['CONFIRMATION_ENDPOINT']}/{confirmation_code}" \
                     f" to confirm your account"
        helper.send_email(user_details['email'], subject, email_template,
                          email_text)
        response = helper.make_rest_success_response(
            "Registration successful. Please check the staff email to activate your account."
        )
        return make_response(response, 200)
Beispiel #23
0
    def post(self):
        customer_details = customer_parser.parse_args()
        # we need to check for all the unique values to a user to ensure there is no duplicate
        customer = UserProfile.check_account_duplicate(
            customer_details['phone'], customer_details['id_passport'],
            customer_details['kra_pin'])
        customer_number = None
        if not customer:
            # Create temporary seven digit password
            temporary_pass = helper.create_user_password()
            # create a new user account if not existing
            user_id = uuid.uuid4()
            # create new user
            customer = User(user_id, customer_details['email'], temporary_pass)
            customer.save()

            # if on boarding an individual customer
            if customer_details['type'] == 'Individual':
                customer = User.get_user_by_email(customer_details['email'])
                customer_id = customer.id
                # create individual customer's profile
                new_individual_profile = UserProfile(
                    customer_id, customer_details["first_name"],
                    customer_details["last_name"], customer_details["phone"],
                    customer_details["gender"], customer_details["avatar_url"],
                    customer_details["occupation"],
                    customer_details["id_passport"],
                    customer_details["kra_pin"],
                    customer_details["birth_date"],
                    customer_details['physical_address'],
                    customer_details['postal_address'],
                    customer_details['postal_code'],
                    customer_details['postal_town'],
                    customer_details['country'], customer_details['county'],
                    customer_details['constituency'], customer_details['ward'],
                    customer_details['facebook'],
                    customer_details['instagram'], customer_details['twitter'])
                new_individual_profile.save()

                #  create a new individual customer detail
                customer_number = self.create_customer_number(
                    "IN", customer_id, customer_details['country'])
                self.create_individual_customer(customer_id, customer_number,
                                                customer_details['salutation'])
                self.role_placement(customer_id, "IND")

                # send activation email
                self.send_activation_email(customer_details['email'],
                                           customer_id, temporary_pass)

            # if on boarding an organization
            elif customer_details['type'] == "Organization":
                customer_id = customer.id
                customer_number = self.create_customer_number(
                    customer_details['org_type'], customer_id,
                    customer_details['country'])
                # Add contact person details
                contact_person = UserProfile(customer_id,
                                             customer_details['first_name'],
                                             customer_details['last_name'],
                                             customer_details["phone"])
                contact_person.save()

                new_org_customer = OrganizationCustomer(
                    customer_details['org_type'], customer_details["org_name"],
                    customer_details['org_phone'],
                    customer_details['org_email'],
                    customer_details['reg_number'],
                    customer_details['physical_address'],
                    customer_details['postal_address'],
                    customer_details['postal_code'],
                    customer_details['postal_town'],
                    customer_details['county'],
                    customer_details['constituency'], customer_details['ward'],
                    customer_details['facebook'],
                    customer_details['instagram'], customer_details['twitter'],
                    customer_id, customer_number)
                new_org_customer.save()
                self.role_placement(customer_id, "ORG")

                # send activation email
                self.send_activation_email(customer_details['email'],
                                           customer_id, temporary_pass)

        # create a new affiliation between the customer and broker/agent
        # each affiliation must only exist once in the db
        # we need to fetch the role of the agent/broker and associate it into the affiliation

        uid = get_jwt_identity()
        # we need to check whether the current user is a staff member or an agent/broker
        role_name = self.get_role_name(uid)
        agent_broker = self.check_staff(uid, role_name)

        if agent_broker:
            # the current user is not a staff member
            # we also need to ensure the affiliation created is not a duplicate one
            if customer_number is None:
                customer_number = self.fetch_customer_number(
                    role_name, customer.id, agent_broker)

            if self.is_affiliation_duplicate(role_name, agent_broker,
                                             customer_number):
                response_msg = helper.make_rest_fail_response(
                    "Customer already exists")
                return make_response(response_msg, 409)

            self.register_customer(role_name, customer_number, agent_broker,
                                   uid)
        else:
            broker_agent_id = self.get_broker_agent_id(uid, role_name)
            if customer_number is None:
                customer_number = self.fetch_customer_number(
                    role_name, customer.id, broker_agent_id, agent_broker)
            if self.is_affiliation_duplicate(role_name, broker_agent_id,
                                             customer_number):

                response_msg = helper.make_rest_fail_response(
                    "Customer already exists")
                return make_response(response_msg, 409)

            self.register_customer(role_name, customer_number, broker_agent_id)

        response_msg = helper.make_rest_success_response(
            "Customer has been on-boarded successfully",
            {"customer_number": customer_number})
        return make_response(response_msg, 200)
    def post(self):
        # get the current agency details
        uid = get_jwt_identity()

        # get user role so that you can use it to get the agency_id,
        claims = get_jwt_claims()
        role = claims['role']

        # get company_id
        company_id = self.get_agency_id(role, uid)
        policy_details = underwriting_parser.parse_args()
        # get the transaction type i.e could be a new policy, renewal or endorsement or extension
        if policy_details:
            transaction_type = policy_details['transaction_type']
            # if it's a new transaction (customer had not been enrolled into this kind of policy before)
            if transaction_type == 'NET':
                # Create master policy, first generate master policy number
                index = MasterPolicy.query.all()
                new_policy = PolicyNoGenerator('MS', len(index))
                # Get class details after receiving the class id from the front end e.g if name is Motor Private
                class_details = InsuranceClass.get_class_by_id(
                    policy_details['class_id'])
                # generate master policy number using the acronym from the class details
                new_policy.set_mpi(class_details.acronym)
                ms_policy_number = new_policy.generate_policy_no()

                master_policy = MasterController.create_master_policy(
                    ms_policy_number,
                    policy_details['customer_number'],
                    policy_details['date_expiry'],
                    policy_details['insurance_company']
                )
                # create child policy number
                child_policy_no = self.create_child_policy_number(
                    policy_details)
                # Create child policy with details
                child_policy_id = self.create_child(
                    policy_details, child_policy_no, company_id, master_policy)
                # Send response if successfully onboarded with the onboarded data
                # data = self.get_cover_data(child_policy_id)
                response = helper.make_rest_success_response(
                    "Congratulations! The customer was enrolled successfully. Cover will be"
                    " activated after payment is made", child_policy_id)
                return make_response(response, 200)

            # if it's an endorsement i.e the customer wants to add an item under the master policy
            elif transaction_type == 'END':
                # In this case, you could be endorsing the child policy or master policy
                # get the master policy by master policy id
                if policy_details["master_policy_id"]:
                    endorsed_policy = MasterPolicy.get_policy_by_id(
                        policy_details["master_policy_id"])

                    # check whether the policy has expired.
                    time_difference = (
                        endorsed_policy.date_expiry - datetime.now()).days
                    if time_difference > 1:
                        # create child policy number
                        child_policy_no = self.create_child_policy_number(
                            policy_details)
                        # Then endorse it with the child policy details:
                        child_policy_id = self.create_child(
                            policy_details, child_policy_no, company_id, endorsed_policy)
                        # endorsement successful
                        response = helper.make_rest_success_response(
                            "Endorsement successful", child_policy_id)
                        return make_response(response, 200)

                    else:
                        response = helper.make_rest_fail_response(
                            "Failed! Policy expired. Kindly renew it then endorse.")
                        return make_response(response, 500)

                if policy_details["child_policy_id"]:

                    # In this case we add a benefit to the child policy
                    endorsed_policy = ChildPolicy.get_child_by_id(
                        policy_details["child_policy_id"])

                    # Check whether the policy has expired.
                    time_difference = (
                        endorsed_policy.date_expiry - datetime.now()).days
                    if time_difference > 1:
                        # revise the child policy with the a new premium amount
                        revised_policy = self.revise_child_policy(
                            "END", endorsed_policy, policy_details, "benefit")

                        # append the new benefit to revised policy
                        child_controller = ChildController()
                        child_controller.add_benefits(
                            policy_details['benefits'], revised_policy)

                        # endorsement successful
                        response = helper.make_rest_success_response(
                            "Endorsement successful", revised_policy)
                        return make_response(response, 200)

                    else:
                        response = helper.make_rest_fail_response(
                            "Failed! Policy expired. Kindly renew it then endorse.")
                        return make_response(response, 500)

            elif transaction_type == 'RET':
                #   renew the transaction
                if MasterController.renew_transaction(policy_details['master_policy_id'],
                                                      policy_details['expiry_date'],
                                                      transaction_type):
                    return make_response(helper.make_rest_success_response("Policy renewed successfully"),
                                         200)
                else:
                    return make_response(helper.make_rest_success_response("Failed to renew Policy"))
                # if the customer want's to extend the cover to cater for extra losses
            elif transaction_type == 'EXT':
                # get child policy
                extended_policy = ChildPolicy.get_child_by_id(
                    policy_details['child_policy_id'])
                # check whether policy is less than one year old (365) days
                time_difference = (
                    datetime.now() - extended_policy.date_activated).days
                if time_difference < 365:
                    # revise the child policy with the a new premium amount
                    revised_policy = self.revise_child_policy(
                        "EXT", extended_policy, policy_details)

                    # append the new extension to revised policy
                    child_controller = ChildController()
                    child_controller.add_extensions(policy_details["extensions"],
                                                    revised_policy)

                    return make_response(helper.make_rest_success_response("Policy extended successfully", revised_policy),
                                         200)
                else:
                    return make_response(helper.make_rest_success_response("Failed to extend policy"))

            elif transaction_type == 'REF':
                refund_type = policy_details["refund_type"]
                # fetch the child policy to be refunded or updated
                child_policy = ChildPolicy.get_child_by_id(
                    policy_details['child_policy_id'], True)

                # get premium amount
                premium_amount = child_policy.premium_amount
                refund_amount = None

                # TODO: create model that stores transactions, the amount paid below is dummy data
                amount_paid = 800
                if refund_type == "sold":
                    # deactivate the previous child policy so that we can create a new one
                    child_policy.deactivate()

                    # initialize child controller
                    child_controller = ChildController()
                    child_controller.create_child_policy(
                        child_policy.cp_number,
                        child_policy.customer_number,
                        child_policy.rate,
                        child_policy.date_expiry,
                        # Zero premium amount
                        0,
                        "REF",
                        child_policy.agency_id,
                        child_policy.company,
                        child_policy.pricing_model,
                        child_policy.master_policy,
                        child_policy.subclass,
                        child_policy.vehicle,
                        "sold"
                    )

                    # if the policy has lasted for less than thirty days refund full amount paid
                    period_lasted = (datetime.now() -
                                     child_policy.date_activated).days
                    if period_lasted <= 30:
                        refund_amount = amount_paid

                    # if more than 30 days, deduct the cost incured for the period the cover has run
                    else:
                        cost_incurred = (premium_amount / 365) * period_lasted
                        if amount_paid >= cost_incurred:
                            refund_amount = amount_paid - cost_incurred
                        # TODO: Create a clause for handling amount paid

                elif refund_type == "benefit":
                    # deactivate previous policy
                    child_policy.deactivate()

                    # create new transaction with the same child policy number and vehicle details
                    revised_policy = self.revise_child_policy(
                        "REF", child_policy, policy_details, "benefit_removed")

                    # Append any remaining benefits
                    # first get the id of the cancelled benefit
                    cancelled_benefit = policy_details["benefit_id"]
                    # get remaining
                    remaining_benefits = [
                        i.serialize() for i in child_policy.benefits if i.id != cancelled_benefit]

                    # append them to the revised policy
                    ChildController.add_benefits(
                        remaining_benefits, revised_policy)

                    # get refund amount based on the new recalculated premium amount
                    new_premium_amount = policy_details["premium_amount"]
                    previous_premium = child_policy.premium_amount

                    # difference
                    premium_change = previous_premium - new_premium_amount

                    # If the policy has run for 30 days, refund full difference
                    period_lasted = (datetime.now() -
                                     child_policy.date_activated).days
                    amount_to_revise = (period_lasted / 365) * premium_change
                    refund_amount = amount_paid

                    # TODO: Revise transaction table and update date due using the amount to revise

                elif refund_type == "sum_insured":
                    # create new child policy based on new details after downward revision of sum insured
                    # deactivate previous policy
                    child_policy.deactivate()

                    # create transaction with new details
                    new_child = self.create_child(
                        policy_details, child_policy.cp_number, company_id, child_policy.master_policy)

                    # TODO: update with new dates
                    new_child.activate()

                    # get refund amount based on the new recalculated premium amount
                    new_premium_amount = policy_details["premium_amount"]
                    previous_premium = child_policy.premium_amount

                    # difference
                    premium_change = previous_premium - new_premium_amount

                    # If the policy has run for 30 days, refund full difference
                    period_lasted = (datetime.now() -
                                     child_policy.date_activated).days
                    amount_to_revise = (period_lasted / 365) * premium_change
                    refund_amount = amount_to_revise

                    # TODO: Revise transaction table and update date due using the amount to revise

                return make_response(helper.make_rest_success_response("Refund successful", refund_amount),
                                     200)

            elif transaction_type == 'CNC':
                # To cancel a transaction
                child_controller = ChildController()
                child_controller.cancel(policy_details['child_policy_id'])
                return make_response(helper.make_rest_success_response("Policy cancelled successfully"),
                                     200)

        else:
            response = helper.make_rest_fail_response("Failed")
            return make_response(response, 500)
Beispiel #25
0
    def put(self):
        """
        registration completion of a user and profile update
        :return:
        """
        # get user id
        user_id = get_jwt_identity()
        # get the user details from the request sent by the client
        user_details = user_parser.parse_args()
        customer_details = customer_parser.parse_args()
        if user_details['customer_id']:
            user_id = user_details['customer_id']
        # check if the user exists
        user = User.get_user_by_id(user_id)

        # if the user is an agent and is updating
        # details on behalf of a customer
        # we can check whether the customer exists or not

        # if user exists, then update their details
        if user:
            # get their role
            claims = get_jwt_claims()
            role = claims['role']
            if user_details['customer_id']:
                user = User.get_user_by_id(user_details['customer_id'])
                role = 'IND'
            if user_details['update_type'] == "password":
                updateController.update_user_password(
                    user_details['new_password'], user_id)

            elif user_details['update_type'] == "personal":
                user_details.update({
                    'birth_date':
                    UserRegister.format_birth_date(
                        str(user_details['birth_date']))
                })
                updateController.update_personal_details(user_details, user_id)

            elif user_details['update_type'] == "location":
                updateController.update_location_details(
                    user_details, role, user_id)

            elif user_details['update_type'] == "agency":
                updateController.update_agency_details(user_details, role,
                                                       user_id)

            elif user_details['update_type'] == "complete_profile":
                user_details['birth_date'] = UserRegister.format_birth_date(
                    user_details['birth_date'])
                updateController.complete_user_profile(user_details, user_id,
                                                       role)

            elif user_details['update_type'] == "social":
                updateController.update_social_profile(user_details, user_id,
                                                       role)

            elif user_details['update_type'] == "image":
                updateController.update_avatar_name(user_details['avatar_url'],
                                                    user_id, role)

            elif user_details['update_type'] == "extra_info":
                updateController.update_extra_info(role, user_id,
                                                   customer_details)

        else:
            # if user does not exist
            response_msg = helper.make_rest_fail_response(
                "User does not exist")
            return make_response(response_msg, 404)

        # update was successful
        response_msg = helper.make_rest_success_response(f"Update successful.")
        return make_response(response_msg, 200)