Esempio n. 1
0
    def put(self):
        # Update an existing response for the logged-in user.
        req_parser = reqparse.RequestParser()
        req_parser.add_argument('id', type=int, required=True)
        req_parser.add_argument('is_submitted', type=bool, required=True)
        req_parser.add_argument('application_form_id', type=int, required=True)
        req_parser.add_argument('answers', type=list, required=True, location='json')
        args = req_parser.parse_args()

        user_id = g.current_user['id']
        try: 
            old_response = db.session.query(Response).filter(Response.id == args['id']).first()
            if not old_response:
                LOGGER.error("Response not found for id {}".format(args['id']))
                return errors.RESPONSE_NOT_FOUND
            if old_response.user_id != user_id:
                LOGGER.error("Old user id {} does not match user id {}".format(old_response.user_id, user_id))
                return errors.UNAUTHORIZED
            if old_response.application_form_id != args['application_form_id']:
                LOGGER.error("Update conflict for {}".format(args['application_form_id']))
                return errors.UPDATE_CONFLICT

            old_response.is_submitted = args['is_submitted']
            if args['is_submitted']:
                old_response.submitted_timestamp = datetime.datetime.now()
                old_response.is_withdrawn = False
                old_response.withdrawn_timestamp = None

            for answer_args in args['answers']:
                old_answer = db.session.query(Answer).filter(Answer.response_id == old_response.id, Answer.question_id == answer_args['question_id']).first()
                if old_answer:  # Update the existing answer
                    old_answer.value = answer_args['value']
                else:
                    answer = Answer(old_response.id, answer_args['question_id'], answer_args['value'])
                    db.session.add(answer)
            db.session.commit()
            db.session.flush()

            try:
                if old_response.is_submitted:
                    LOGGER.info('Sending confirmation email for response with ID : {id}'.format(id=old_response.id))
                    user = db.session.query(AppUser).filter(AppUser.id==g.current_user['id']).first()
                    self.send_confirmation(user, old_response)
            except:                
                LOGGER.warn('Failed to send confirmation email for response with ID : {id}, but the response was submitted succesfully'.format(id=old_response.id))
            finally:
                return old_response, 200

        except SQLAlchemyError as e:
            LOGGER.error("Database error encountered: {}".format(e))            
            return errors.DB_NOT_AVAILABLE
        except: 
            LOGGER.error("Encountered unknown error: {}".format(traceback.format_exc()))
            return errors.DB_NOT_AVAILABLE
Esempio n. 2
0
    def post(self):
        args = self.post_req_parser.parse_args()
        user_id = g.current_user['id']
        is_submitted = args['is_submitted']
        application_form_id = args['application_form_id']
        language = args['language']
        if len(language) != 2:
            language = 'en'  # Fallback to English if language doesn't look like an ISO 639-1 code

        application_form = application_form_repository.get_by_id(
            application_form_id)
        if application_form is None:
            return errors.FORM_NOT_FOUND_BY_ID

        user = user_repository.get_by_id(user_id)
        responses = response_repository.get_all_for_user_application(
            user_id, application_form_id)

        if not application_form.nominations and len(responses) > 0:
            return errors.RESPONSE_ALREADY_SUBMITTED

        response = Response(application_form_id, user_id, language)
        if is_submitted:
            response.submit()

        response_repository.save(response)

        answers = []
        for answer_args in args['answers']:
            answer = Answer(response.id, answer_args['question_id'],
                            answer_args['value'])
            answers.append(answer)
        response_repository.save_answers(answers)

        try:
            if response.is_submitted:
                LOGGER.info(
                    'Sending confirmation email for response with ID : {id}'.
                    format(id=response.id))
                user = user_repository.get_by_id(user_id)
                response = response_repository.get_by_id_and_user_id(
                    response.id, user_id)
                self.send_confirmation(user, response)
        except:
            LOGGER.warn(
                'Failed to send confirmation email for response with ID : {id}, but the response was submitted succesfully'
                .format(id=response.id))
        finally:
            return response, 201
Esempio n. 3
0
    def post(self):
        # Save a new response for the logged-in user.
        req_parser = reqparse.RequestParser()
        req_parser.add_argument('is_submitted', type=bool, required=True)
        req_parser.add_argument('application_form_id', type=int, required=True)
        req_parser.add_argument('answers',
                                type=list,
                                required=True,
                                location='json')
        args = req_parser.parse_args()

        user_id = g.current_user['id']
        try:
            response = Response(args['application_form_id'], user_id)
            response.is_submitted = args['is_submitted']
            if args['is_submitted']:
                response.submitted_timestamp = datetime.datetime.now()
            db.session.add(response)
            db.session.commit()

            for answer_args in args['answers']:
                answer = Answer(response.id, answer_args['question_id'],
                                answer_args['value'])
                db.session.add(answer)
            db.session.commit()

            try:
                if response.is_submitted:
                    LOGGER.info(
                        'Sending confirmation email for response with ID : {id}'
                        .format(id=response.id))
                    user = db.session.query(AppUser).filter(
                        AppUser.id == g.current_user['id']).first()
                    self.send_confirmation(user, response)
            except:
                LOGGER.warn(
                    'Failed to send confirmation email for response with ID : {id}, but the response was submitted succesfully'
                    .format(id=response.id))
            finally:
                return response, 201  # 201 is 'CREATED' status code

        except SQLAlchemyError as e:
            LOGGER.error("Database error encountered: {}".format(e))
            return errors.DB_NOT_AVAILABLE
        except:
            LOGGER.error("Encountered unknown error: {}".format(
                traceback.format_exc()))
            return errors.DB_NOT_AVAILABLE
Esempio n. 4
0
    def put(self):
        args = self.put_req_parser.parse_args()
        user_id = g.current_user['id']
        is_submitted = args['is_submitted']
        language = args['language']

        response = response_repository.get_by_id(args['id'])
        if not response:
            return errors.RESPONSE_NOT_FOUND
        if response.user_id != user_id:
            return errors.UNAUTHORIZED
        if response.application_form_id != args['application_form_id']:
            return errors.UPDATE_CONFLICT

        response.is_submitted = is_submitted
        response.language = language
        if is_submitted:
            response.submit()
        response_repository.save(response)

        answers = []
        for answer_args in args['answers']:
            answer = response_repository.get_answer_by_question_id_and_response_id(
                answer_args['question_id'], response.id)
            if answer:
                answer.update(answer_args['value'])
            else:
                answer = Answer(response.id, answer_args['question_id'],
                                answer_args['value'])
            answers.append(answer)
        response_repository.save_answers(answers)

        try:
            if response.is_submitted:
                LOGGER.info(
                    'Sending confirmation email for response with ID : {id}'.
                    format(id=response.id))
                user = user_repository.get_by_id(user_id)
                response = response_repository.get_by_id_and_user_id(
                    response.id, user_id)
                self.send_confirmation(user, response)
        except:
            LOGGER.warn(
                'Failed to send confirmation email for response with ID : {id}, but the response was submitted succesfully'
                .format(id=response.id))
        finally:
            return response, 200
Esempio n. 5
0
    def _seed_data(self):
        # Add a user
        test_country = Country('Indaba Land')
        _add_object_to_db(test_country)

        test_category = UserCategory('Category1')
        _add_object_to_db(test_category)

        other_user_data = self.user_data_dict.copy()
        other_user_data['email'] = '*****@*****.**'
        response = self.app.post('/api/v1/user', data=other_user_data)
        self.other_user_data = json.loads(response.data)

        response = self.app.post('/api/v1/user', data=self.user_data_dict)
        self.user_data = json.loads(response.data)

        # Add application form data
        self.test_event = Event('Test Event', 'Event Description', date(
            2019, 2, 24), date(2019, 3, 24))
        _add_object_to_db(self.test_event)
        self.test_form = ApplicationForm(
            self.test_event.id, True, date(2019, 3, 24))
        _add_object_to_db(self.test_form)
        test_section = Section(
            self.test_form.id, 'Test Section', 'Test Description', 1)
        _add_object_to_db(test_section)
        self.test_question = Question(self.test_form.id, test_section.id,
                                      'Test Question Description', 'Test question placeholder', 1, 'Test Type', None)
        _add_object_to_db(self.test_question)
        self.test_question2 = Question(
            self.test_form.id, test_section.id, 'Test Question 2', 'Enter something', 2, 'short-text', None)
        _add_object_to_db(self.test_question2)

        self.test_response = Response(
            self.test_form.id, self.other_user_data['id'])
        _add_object_to_db(self.test_response)

        self.test_answer1 = Answer(
            self.test_response.id, self.test_question.id, 'My Answer')
        _add_object_to_db(self.test_answer1)

        db.session.flush()
Esempio n. 6
0
    def _seed_data(self):
        organisation = self.add_organisation(
            'Deep Learning Indaba', 'Baobab', 'blah.png', 'blah_big.png',
            'deeplearningindba', 'https://www.deeplearningindaba.com',
            '*****@*****.**')

        email_templates = [
            EmailTemplate('withdrawal', None, ''),
            EmailTemplate('confirmation-response', None,
                          '{question_answer_summary}')
        ]
        db.session.add_all(email_templates)
        db.session.commit()

        # Add a user
        test_country = Country('Indaba Land')
        _add_object_to_db(test_country)

        test_category = UserCategory('Category1')
        _add_object_to_db(test_category)

        other_user_data = self.user_data_dict.copy()
        other_user_data['email'] = '*****@*****.**'
        response = self.app.post('/api/v1/user', data=other_user_data)
        self.other_user_data = json.loads(response.data)

        response = self.app.post('/api/v1/user', data=self.user_data_dict)
        self.user_data = json.loads(response.data)

        # Add application form data
        self.test_event = Event('Test Event', 'Event Description',
                                date(2019, 2, 24), date(2019, 3, 24),
                                'NAGSOLVER', 1, '*****@*****.**',
                                'indaba.deeplearning', datetime.now(),
                                datetime.now(), datetime.now(), datetime.now(),
                                datetime.now(), datetime.now(), datetime.now(),
                                datetime.now(), datetime.now(), datetime.now())
        _add_object_to_db(self.test_event)
        self.test_form = ApplicationForm(self.test_event.id, True,
                                         date(2019, 3, 24))
        _add_object_to_db(self.test_form)
        test_section = Section(self.test_form.id, 'Test Section',
                               'Test Description', 1)
        _add_object_to_db(test_section)
        self.test_question = Question(self.test_form.id, test_section.id,
                                      'Test Question Description',
                                      'Test question placeholder', 1,
                                      'Test Type', None)
        _add_object_to_db(self.test_question)
        self.test_question2 = Question(self.test_form.id, test_section.id,
                                       'Test Question 2', 'Enter something', 2,
                                       'short-text', None)
        _add_object_to_db(self.test_question2)

        self.test_response = Response(self.test_form.id,
                                      self.other_user_data['id'])
        _add_object_to_db(self.test_response)

        self.test_answer1 = Answer(self.test_response.id,
                                   self.test_question.id, 'My Answer')
        _add_object_to_db(self.test_answer1)

        db.session.flush()
Esempio n. 7
0
 def add_answer(self, response_id, question_id, answer_value):
     answer = Answer(response_id, question_id, answer_value)
     db.session.add(answer)
     db.session.commit()
     return answer
Esempio n. 8
0
    def _seed_data(self):
        """Create dummy data for testing"""
        organisation = self.add_organisation(
            'Deep Learning Indaba', 'Baobab', 'blah.png', 'blah_big.png',
            'deeplearningindba', 'https://www.deeplearningindaba.com',
            '*****@*****.**')

        email_templates = [
            EmailTemplate('withdrawal', None, ''),
            EmailTemplate('confirmation-response', None,
                          '{question_answer_summary}')
        ]
        db.session.add_all(email_templates)
        db.session.commit()

        # Add country
        test_country = Country('Indaba Land')
        self.add_to_db(test_country)

        # Add category
        test_category = UserCategory('Category1')
        self.add_to_db(test_category)

        # Add users to database
        other_user_data = self.user_data_dict.copy()
        other_user_data['email'] = self.other_user_email
        response = self.app.post('/api/v1/user', data=other_user_data)
        self.other_user_data = json.loads(response.data)

        response = self.app.post('/api/v1/user', data=self.user_data_dict)
        self.user_data = json.loads(response.data)

        self.add_n_users(self.num_dummy_users)

        # Add application form data
        self.test_event = self.add_event('Test Event', 'Event Description',
                                         date(2019, 2, 24), date(2019, 3, 24),
                                         'NAGSOLVER')
        self.test_form = self.create_application_form(self.test_event.id, True)
        self.test_section = Section(self.test_form.id, 'Test Section',
                                    'Test Description', 1)
        self.test_section.key = 'test_section'
        self.add_to_db(self.test_section)
        self.test_question = Question(self.test_form.id, self.test_section.id,
                                      'Test Question Description',
                                      'Test question placeholder', 1,
                                      'Test Type', None)
        self.add_to_db(self.test_question)
        self.test_question2 = Question(self.test_form.id, self.test_section.id,
                                       'Test Question 2', 'Enter something', 2,
                                       'short-text', None)
        self.add_to_db(self.test_question2)

        # responses
        self.test_response = Response(self.test_form.id,
                                      self.other_user_data['id'])
        self.add_to_db(self.test_response)

        self.test_answer1 = Answer(self.test_response.id,
                                   self.test_question.id, 'My Answer')
        self.add_to_db(self.test_answer1)

        self.responses = []
        for user in self.test_users:
            response = Response(self.test_form.id, user.id)
            self.add_to_db(response)
            answer1 = Answer(
                response.id, self.test_question.id,
                "{}'s Answer for question 1".format(user.firstname))
            answer2 = Answer(
                response.id, self.test_question2.id,
                "{}'s Answer for question 2".format(user.firstname))
            self.add_to_db(answer1)
            self.add_to_db(answer2)
            self.responses.append(response)

        # add nomination application form
        self.test_nomination_form = self.create_application_form(
            self.test_event.id, True, True)
        self.test_nomination_response = Response(self.test_nomination_form.id,
                                                 self.other_user_data['id'])
        self.add_to_db(self.test_nomination_response)

        db.session.flush()
Esempio n. 9
0
    def _seed_data(self):
        self.add_organisation('Deep Learning Indaba', 'blah.png',
                              'blah_big.png')
        self.first_user_data = self.add_user('*****@*****.**', 'First',
                                             'User', 'Mx')
        self.other_user_data = self.add_user('*****@*****.**')

        test_event = self.add_event()
        test_event.add_event_role('admin', 1)
        self.test_event_data = copy.deepcopy(test_event.__dict__)
        self.add_to_db(test_event)

        nomination_event = self.add_event(key="AWARD_NOMINATIONS_ONLY")
        nomination_event.add_event_role('admin', 1)
        self.test_nomination_event_data = copy.deepcopy(
            nomination_event.__dict__)
        self.add_to_db(nomination_event)

        self.test_form = self.create_application_form(test_event.id, True,
                                                      False)
        self.add_to_db(self.test_form)

        self.test_nomination_form = self.create_application_form(
            nomination_event.id, True, True)

        sections = [
            Section(test_event.id, 'Nomination Capacity', 'Nomination Details',
                    1),
            Section(nomination_event.id, 'Nominee Information',
                    'Details of person being nominated', 1)
        ]
        sections[1].key = 'nominee_section'
        db.session.add_all(sections)
        db.session.commit()

        questions = [
            Question(test_event.id, sections[0].id, 'Nomination Capacity',
                     'Enter 50 to 150 words', 1, 'long_text', ''),
            Question(test_event.id, sections[0].id, 'some details',
                     'Enter 50 to 150 words', 2, 'long_text', ''),
            Question(nomination_event.id, sections[1].id, 'title',
                     'Enter 50 to 150 words', 1, 'long_text', ''),
            Question(nomination_event.id, sections[1].id, 'firstname',
                     'Enter 50 to 150 words', 2, 'long_text', ''),
            Question(nomination_event.id, sections[1].id, 'lastname',
                     'Enter 50 to 150 words', 3, 'long_text', ''),
            Question(nomination_event.id, sections[1].id, 'email',
                     'Enter 50 to 150 words', 4, 'long_text', ''),
        ]
        questions[0].key = 'nominating_capacity'
        questions[2].key = 'nomination_title'
        questions[3].key = 'nomination_firstname'
        questions[4].key = 'nomination_lastname'
        questions[5].key = 'nomination_email'
        db.session.add_all(questions)
        db.session.commit()

        self.test_response1 = Response(  # Self nomination
            self.test_form.id, self.first_user_data.id)

        self.add_to_db(self.test_response1)
        answers = [
            Answer(self.test_response1.id, questions[0].id, 'self'),
            Answer(self.test_response1.id, questions[1].id, 'Blah')
        ]
        db.session.add_all(answers)
        db.session.commit()

        self.test_response2 = Response(  # Nominating other
            self.test_form.id, self.other_user_data.id)

        self.add_to_db(self.test_response2)
        answers = [
            Answer(self.test_response2.id, questions[0].id, 'other'),
            Answer(self.test_response2.id, questions[1].id, 'Blah'),
            Answer(self.test_response2.id, questions[2].id, 'Mx'),
            Answer(self.test_response2.id, questions[3].id, 'Skittles'),
            Answer(self.test_response2.id, questions[4].id, 'Cat'),
            Answer(self.test_response2.id, questions[5].id,
                   '*****@*****.**'),
        ]
        db.session.add_all(answers)
        db.session.commit()

        self.first_headers = self.get_auth_header_for("*****@*****.**")
        self.other_headers = self.get_auth_header_for("*****@*****.**")

        db.session.flush()