Ejemplo n.º 1
0
def _serialize_review_form(review_form, language):
    review_questions = []
    for question in review_form.review_questions:
        translation = question.get_translation(language)
        if translation is None:
            LOGGER.warn(
                'Missing {} translation for review question id {}'.format(
                    language, question.id))
            translation = question.get_translation('en')
        review_questions.append({
            'id': question.id,
            'question_id': question.question_id,
            'description': translation.description,
            'headline': translation.headline,
            'type': question.type,
            'placeholder': translation.placeholder,
            'options': translation.options,
            'is_required': question.is_required,
            'order': question.order,
            'validation_regex': translation.validation_regex,
            'validation_text': translation.validation_text,
            'weight': question.weight
        })

    form = {
        'id': review_form.id,
        'application_form_id': review_form.application_form_id,
        'is_open': review_form.is_open,
        'deadline': review_form.deadline.isoformat(),
        'review_questions': review_questions
    }

    return form
Ejemplo n.º 2
0
    def get(self):
        args = self.req_parser.parse_args()

        try:
            event = db.session.query(Event).filter(Event.id == args['event_id']).first()
            if not event:
                LOGGER.warn("Event not found for event_id: {}".format(args['event_id']))
                return errors.EVENT_NOT_FOUND

            form = db.session.query(ApplicationForm).filter(ApplicationForm.event_id == args['event_id']).first()     
            if not form:
                LOGGER.warn("Form not found for event_id: {}".format(args['event_id']))
                return errors.FORM_NOT_FOUND
            
            # Get the latest response (note there may be older withdrawn responses)
            response = db.session.query(Response).filter(
                Response.application_form_id == form.id, Response.user_id == g.current_user['id']
                ).order_by(Response.started_timestamp.desc()).first()
            if not response:
                LOGGER.debug("Response not found for event_id: {}".format(args['event_id']))
                return errors.RESPONSE_NOT_FOUND
            
            answers = db.session.query(Answer).filter(Answer.response_id == response.id).all()
            response.answers = list(answers)

            return response

        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
Ejemplo n.º 3
0
    def send_confirmation(self, user, questions, answers, confirmed, event_name):
        if answers is None:
            LOGGER.warn(
                'Found no answers associated with response with id {response_id}'.format(response_id=user.id))
        if questions is None:
            LOGGER.warn(
                'Found no questions associated with application form with id {form_id}'.format(form_id=user.id))
        try:
            # Building the summary, where the summary is a dictionary whose key is the question headline, and the value
            # is the relevant answer
            summary = ""
            for answer in answers:
                for question in questions:
                    if answer.registration_question_id == question.id:
                        summary += "Question heading :" + question.headline + "\nQuestion Description :" + \
                            question.description + "\nAnswer :" + _get_answer_value(
                                answer, question) + "\n"

            subject = event_name + ' Registration'
            greeting = strings.build_response_email_greeting(
                user.user_title, user.firstname, user.lastname)
            if len(summary) <= 0:
                summary = '\nNo valid questions were answered'
            body_text = greeting + '\n\n' + REGISTRATION_MESSAGE + \
                self.get_confirmed_message(
                    confirmed) + '\n\nHere is a copy of your responses:\n\n' + summary

            emailer.send_mail(user.email, subject, body_text=body_text)

        except Exception as e:
            LOGGER.error('Could not send confirmation email for response with id : {response_id}'.format(
                response_id=user.id))
Ejemplo n.º 4
0
    def send_confirmation(self, user, questions, answers, confirmed, event):
        if answers is None:
            LOGGER.warn(
                'Found no answers associated with response with id {response_id}'
                .format(response_id=user.id))
        if questions is None:
            LOGGER.warn(
                'Found no questions associated with application form with id {form_id}'
                .format(form_id=user.id))
        try:
            # Building the summary, where the summary is a dictionary whose key is the question headline, and the value
            # is the relevant answer
            summary = ""
            for answer in answers:
                for question in questions:
                    if answer.registration_question_id == question.id:
                        summary += "Question:" + question.headline + "\nAnswer:" + _get_answer_value(
                            answer, question) + "\n"

            emailer.email_user('registration-with-confirmation' if confirmed
                               else 'registration-pending-confirmation',
                               template_parameters=dict(summary=summary),
                               event=event,
                               user=user)

        except Exception as e:
            LOGGER.error(
                'Could not send confirmation email for response with id : {response_id}'
                .format(response_id=user.id))
Ejemplo n.º 5
0
    def get(self):
        LOGGER.debug('Received get request for camera')
        args = self.req_parser.parse_args()
        LOGGER.debug('Parsed Args for site_id: {}'.format(args))

        try:
            site = db.session.query(Site).filter(
                Site.id == args['site_id']).first()
            if (not site):
                LOGGER.warn('Site not found for site_id: {}'.format(
                    args['site_id']))
                return SITE_NOT_FOUND

            cameras = db.session.query(Camera).filter(
                Camera.site_id == site.id).all()  #All cameras at our site
            if (not cameras):
                LOGGER.warn(
                    'No cameras found for site with site_id: {}'.format(
                        args['site_id']))
                return CAMERA_NOT_FOUND

            for camera in cameras:
                cv2.VideoCapture(camera.ip_address).read()

        except SQLAlchemyError as e:
            LOGGER.error("Database error encountered: {}".format(e))
            return DB_NOT_AVAILABLE
        except:
            LOGGER.error("Encountered unknown error: {}".format(
                traceback.format_exc()))
            return DB_NOT_AVAILABLE
Ejemplo n.º 6
0
def _serialize_tag(tag, language):
    tag_translation = tag.get_translation(language)
    if not tag_translation:
        LOGGER.warn('Could not find {} translation for tag id {}'.format(
            language, tag.id))
        tag_translation = tag.get_translation('en')
    return {'id': tag.id, 'name': tag_translation.name}
Ejemplo n.º 7
0
    def send_confirmation(self, user, questions, answers, event_name):
        if answers is None:
            LOGGER.warn(
                'Found no answers associated with response with id {response_id}'
                .format(response_id=user.id))
        if questions is None:
            LOGGER.warn(
                'Found no questions associated with application form with id {form_id}'
                .format(form_id=user.id))
        try:
            # Building the summary, where the summary is a dictionary whose key is the question headline, and the value
            # is the relevant answer
            summary = ""
            for answer in answers:
                for question in questions:
                    if answer.registration_question_id == question.id:
                        summary += "Question heading :" + question.headline + "\nQuestion Description :" + \
                                   question.description + "\nAnswer :" + _get_answer_value(
                            answer, question) + "\n"

            subject = event_name + ' Registration'
            greeting = strings.build_response_email_greeting(
                user.user_title, user.firstname, user.lastname)
            if len(summary) <= 0:
                summary = '\nNo valid questions were answered'
            body_text = greeting + '\n\n' + 'Thank you for completing your guest registration. Please find a copy of your answers below for future reference.' + '\n\n' + summary + '\n\nKind Regards, The Deep Learning Indaba Team'

            emailer.send_mail(user.email, subject, body_text=body_text)
            return True

        except Exception as e:
            LOGGER.error(
                'Could not send confirmation email for response with id : {response_id}'
                .format(response_id=user.id))
            return False
Ejemplo n.º 8
0
def _serialize_tag(tag, language):
    """Serialize a tag in a specific language."""
    translation = tag.get_translation(language)
    if translation is None:
        LOGGER.warn(
            'Could not find translation for language {} for tag id {}'.format(
                language, tag.id))
        translation = tag.get_translation('en')
    return {'id': tag.id, 'event_id': tag.event_id, 'name': translation.name}
Ejemplo n.º 9
0
def _serialize_question(question, language):
    translation = question.get_translation(language)
    if not translation:
        LOGGER.warn('Could not find {} translation for question id {}'.format(
            language, question.id))
        translation = question.get_translation('en')
    return dict(question_id=question.id,
                headline=translation.headline,
                type=question.type)
Ejemplo n.º 10
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
Ejemplo n.º 11
0
 def _serialize_answer(answer, language):
     translation = answer.question.get_translation(language)
     if not translation:
         translation = answer.question.get_translation('en')
         LOGGER.warn(
             'Could not find {} translation for question id {}'.format(
                 language, answer.question.id))
     return {
         'headline': translation.headline,
         'value': answer.value_display
     }
Ejemplo n.º 12
0
    def _serialise_identifier(answer, language):
        question_translation = answer.question.get_translation(language)
        if question_translation is None:
            question_translation = answer.question.get_translation('en')
            LOGGER.warn(
                'Could not find {} translation for question id {}'.format(
                    language, answer.question.id))

        return {
            'headline': question_translation.headline,
            'value': answer.value_display
        }
Ejemplo n.º 13
0
    def get(self):
        args = self.req_parser.parse_args()
        event_id = args['event_id']
        try:
            registration_form = db.session.query(RegistrationForm).filter(
                RegistrationForm.event_id == event_id).first()

            if not registration_form:
                return errors.REGISTRATION_FORM_NOT_FOUND

            sections = (db.session.query(RegistrationSection).filter(
                RegistrationSection.registration_form_id ==
                registration_form.id).filter(
                    RegistrationSection.show_for_travel_award == None).filter(
                        RegistrationSection.show_for_accommodation_award ==
                        None).filter(RegistrationSection.
                                     show_for_payment_required == None).all())

            if not sections:
                LOGGER.warn('Sections not found for event_id: {}'.format(
                    args['event_id']))
                return errors.SECTION_NOT_FOUND

            registration_form.registration_sections = sections

            questions = db.session.query(RegistrationQuestion).filter(
                RegistrationQuestion.registration_form_id ==
                registration_form.id).all()

            if not questions:
                LOGGER.warn('Questions not found for  event_id: {}'.format(
                    args['event_id']))
                return errors.QUESTION_NOT_FOUND

            for s in registration_form.registration_sections:
                s.registration_questions = []
                for q in questions:
                    if q.section_id == s.id:
                        s.registration_questions.append(q)

            return marshal(registration_form,
                           self.registration_form_fields), 201

        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
Ejemplo n.º 14
0
def _serialize_answer(answer, language):
    question = answer.question
    translation = question.get_translation(language)
    if translation is None:
        LOGGER.warn('No {} translation found for question id {}'.format(language, question.id))
        translation = question.get_translation('en')

    return {
        'question_id': answer.question_id,
        'value': answer.value,
        'type': answer.question.type,
        'options': translation.options,
        'headline': translation.headline
    }
Ejemplo n.º 15
0
    def send_confirmation(self, user, response):
        try:
            answers = db.session.query(Answer).filter(Answer.response_id == response.id).all()
            if answers is None:
                LOGGER.warn('Found no answers associated with response with id {response_id}'.format(response_id=response.id))

            questions = db.session.query(Question).filter(Question.application_form_id == response.application_form_id).all()
            if questions is None:
                LOGGER.warn('Found no questions associated with application form with id {form_id}'.format(form_id=response.application_form_id))

            application_form = db.session.query(ApplicationForm).filter(ApplicationForm.id == response.application_form_id).first() 
            if application_form is None:
                LOGGER.warn('Found no application form with id {form_id}'.format(form_id=response.application_form_id))

            event = db.session.query(Event).filter(Event.id == application_form.event_id).first() 
            if event is None:
                LOGGER.warn('Found no event id {event_id}'.format(form_id=application_form.event_id))
        except:
            LOGGER.error('Could not connect to the database to retrieve response confirmation email data on response with ID : {response_id}'.format(response_id=response.id))

        try:
            # Building the summary, where the summary is a dictionary whose key is the question headline, and the value is the relevant answer
            summary = {}
            for answer in answers:
                for question in questions:
                    if answer.question_id == question.id:
                        summary[question.headline] = _get_answer_value(answer, question)

            subject = 'Your application to {}'.format(event.description)
            greeting = strings.build_response_email_greeting(user.user_title, user.firstname, user.lastname)
            body_text = greeting + '\n\n' + strings.build_response_email_body(event.name, event.description, summary)
            emailer.send_mail(user.email, subject, body_text=body_text)

        except:
            LOGGER.error('Could not send confirmation email for response with id : {response_id}'.format(response_id=response.id))
Ejemplo n.º 16
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
Ejemplo n.º 17
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
Ejemplo n.º 18
0
    def _serialise_response(response: Response, review_form: ReviewForm,
                            language: str):
        scores = []
        for review_section in review_form.review_sections:
            for review_question in review_section.review_questions:
                if review_question.weight > 0:
                    review_question_translation = review_question.get_translation(
                        language)
                    if not review_question_translation:
                        review_question_translation = review_question.get_translation(
                            'en')
                        LOGGER.warn(
                            'Could not find {} translation for review question id {}'
                            .format(language, review_score.review_question.id))

                    average_score = review_repository.get_average_score_for_review_question(
                        response.id, review_question.id)

                    score = {
                        "review_question_id": review_question.id,
                        "headline": review_question_translation.headline,
                        "description": review_question_translation.description,
                        "type": review_question.type,
                        "score": average_score,
                        "weight": review_question.weight
                    }
                    scores.append(score)

        response_summary = {
            "response_id":
            response.id,
            "response_user_title":
            response.user.user_title,
            "response_user_firstname":
            response.user.firstname,
            "response_user_lastname":
            response.user.lastname,
            "identifiers": [
                ReviewResponseDetailListAPI._serialise_identifier(
                    answer, response.language) for answer in response.answers
                if answer.question.is_review_identifier()
            ],
            "scores":
            scores,
            "total":
            sum(score['score'] * score['weight'] for score in scores)
        }
        return response_summary
Ejemplo n.º 19
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
Ejemplo n.º 20
0
    def _serialise_score(review_score, language):
        review_question_translation = review_score.review_question.get_translation(
            language)
        if review_question_translation is None:
            review_question_translation = review_score.review_question.get_translation(
                'en')
            LOGGER.warn(
                'Could not find {} translation for review question id {}'.
                format(language, review_score.review_question.id))

        return {
            'review_question_id': review_score.review_question.id,
            'headline': review_question_translation.headline,
            'description': review_question_translation.description,
            'type': review_score.review_question.type,
            'score': review_score.value,
            'weight': review_score.review_question.weight,
        }
Ejemplo n.º 21
0
    def get(self):
        LOGGER.debug('Received get request for application form')
        args = self.req_parser.parse_args()
        LOGGER.debug('Parsed Args for event_id: {}'.format(args))

        try:
            form = db.session.query(ApplicationForm).filter(
                ApplicationForm.event_id == args['event_id']).first()
            if (not form):
                LOGGER.warn('Form not found for event_id: {}'.format(
                    args['event_id']))
                return FORM_NOT_FOUND

            if not form.is_open:
                return APPLICATIONS_CLOSED

            sections = db.session.query(Section).filter(
                Section.application_form_id ==
                form.id).all()  #All sections in our form
            if (not sections):
                LOGGER.warn('Sections not found for event_id: {}'.format(
                    args['event_id']))
                return SECTION_NOT_FOUND

            questions = db.session.query(Question).filter(
                Question.application_form_id ==
                form.id).all()  #All questions in our form
            if (not questions):
                LOGGER.warn('Questions not found for  event_id: {}'.format(
                    args['event_id']))
                return QUESTION_NOT_FOUND

            form.sections = sections

            for s in form.sections:
                s.questions = []
                for q in questions:
                    if (q.section_id == s.id):
                        s.questions.append(q)

            if (form):
                return marshal(form, self.form_fields)
            else:
                LOGGER.warn("Event not found for event_id: {}".format(
                    args['event_id']))
                return EVENT_NOT_FOUND

        except SQLAlchemyError as e:
            LOGGER.error("Database error encountered: {}".format(e))
            return DB_NOT_AVAILABLE
        except:
            LOGGER.error("Encountered unknown error: {}".format(
                traceback.format_exc()))
            return DB_NOT_AVAILABLE
Ejemplo n.º 22
0
def _serialize_review_question(review_question, language):
    translation = review_question.get_translation(language)
    if translation is None:
        LOGGER.warn(
            'Missing {} translation for review review_question id {}'.format(
                language, review_question.id))
        translation = review_question.get_translation('en')
    return {
        'id': review_question.id,
        'question_id': review_question.question_id,
        'description': translation.description,
        'headline': translation.headline,
        'type': review_question.type,
        'placeholder': translation.placeholder,
        'options': translation.options,
        'is_required': review_question.is_required,
        'order': review_question.order,
        'validation_regex': translation.validation_regex,
        'validation_text': translation.validation_text,
        'weight': review_question.weight
    }
Ejemplo n.º 23
0
def _serialize_review_form(review_form: ReviewForm,
                           language: str) -> Mapping[str, Any]:
    review_sections = []

    for section in review_form.review_sections:
        translation = section.get_translation(language)
        if translation is None:
            LOGGER.warn(
                'Missing {} translation for review section id {}'.format(
                    language, section.id))
            translation = section.get_translation('en')
        review_sections.append({
            'id':
            section.id,
            'order':
            section.order,
            'headline':
            translation.headline,
            'description':
            translation.description,
            'review_questions': [
                _serialize_review_question(q, language)
                for q in section.review_questions
            ]
        })

    form = {
        'id': review_form.id,
        'application_form_id': review_form.application_form_id,
        'is_open': review_form.is_open,
        'deadline': review_form.deadline.isoformat(),
        'stage': review_form.stage,
        'review_sections': review_sections
    }

    return form
Ejemplo n.º 24
0
    def send_confirmation(self, user, response):
        try:
            answers = db.session.query(Answer).join(
                Question, Answer.question_id == Question.id).filter(
                    Answer.response_id == response.id).order_by(
                        Question.order).all()
            if answers is None:
                LOGGER.warn(
                    'Found no answers associated with response with id {response_id}'
                    .format(response_id=response.id))

            application_form = db.session.query(ApplicationForm).filter(
                ApplicationForm.id == response.application_form_id).first()
            if application_form is None:
                LOGGER.warn(
                    'Found no application form with id {form_id}'.format(
                        form_id=response.application_form_id))

            event = db.session.query(Event).filter(
                Event.id == application_form.event_id).first()
            if event is None:
                LOGGER.warn('Found no event id {event_id}'.format(
                    form_id=application_form.event_id))
        except:
            LOGGER.error(
                'Could not connect to the database to retrieve response confirmation email data on response with ID : {response_id}'
                .format(response_id=response.id))

        try:
            subject = 'Your application to {}'.format(event.description)
            question_answer_summary = strings.build_response_email_body(
                answers)

            template = email_repository.get(event.id,
                                            'confirmation-response').template
            body_text = template.format(
                title=user.user_title,
                firstname=user.firstname,
                lastname=user.lastname,
                event_description=event.description,
                question_answer_summary=question_answer_summary,
                event_name=event.name)
            emailer.send_mail(user.email,
                              subject,
                              body_text=body_text,
                              sender_name=g.organisation.name,
                              sender_email=g.organisation.email_from)

        except:
            LOGGER.error(
                'Could not send confirmation email for response with id : {response_id}'
                .format(response_id=response.id))
Ejemplo n.º 25
0
    def send_confirmation(self, user, response):
        try:
            answers = response.answers
            if not answers:
                LOGGER.warn(
                    'Found no answers associated with response with id {response_id}'
                    .format(response_id=response.id))

            application_form = response.application_form
            if application_form is None:
                LOGGER.warn(
                    'Found no application form with id {form_id}'.format(
                        form_id=response.application_form_id))

            event = application_form.event
            if event is None:
                LOGGER.warn('Found no event id {event_id}'.format(
                    form_id=application_form.event_id))
        except:
            LOGGER.error(
                'Could not connect to the database to retrieve response confirmation email data on response with ID : {response_id}'
                .format(response_id=response.id))

        try:
            question_answer_summary = strings.build_response_email_body(
                answers, user.user_primaryLanguage, application_form)

            if event.has_specific_translation(user.user_primaryLanguage):
                event_description = event.get_description(
                    user.user_primaryLanguage)
            else:
                event_description = event.get_description('en')

            emailer.email_user(
                'confirmation-response-call' if event.event_type
                == EventType.CALL else 'confirmation-response',
                template_parameters=dict(
                    event_description=event_description,
                    question_answer_summary=question_answer_summary,
                ),
                event=event,
                user=user)

        except Exception as e:
            LOGGER.error(
                'Could not send confirmation email for response with id : {response_id} due to: {e}'
                .format(response_id=response.id, e=e))
Ejemplo n.º 26
0
    def get(self):
        args = self.req_parser.parse_args()
        event_id = args['event_id']
        offer_id = args['offer_id']
        try:
            offer = db.session.query(Offer).filter(
                Offer.id == offer_id).first()

            user_id = verify_token(request.headers.get('Authorization'))['id']

            if offer and (not offer.user_id == user_id):
                return errors.FORBIDDEN
            
            if not offer.candidate_response:
                return errors.OFFER_NOT_ACCEPTED

            registration_form = db.session.query(RegistrationForm).filter(
                RegistrationForm.event_id == event_id).first()

            if not registration_form:
                return errors.REGISTRATION_FORM_NOT_FOUND

            sections = db.session.query(RegistrationSection).filter(
                RegistrationSection.registration_form_id == registration_form.id).all()

            if not sections:
                LOGGER.warn(
                    'Sections not found for event_id: {}'.format(args['event_id']))
                return errors.SECTION_NOT_FOUND

            included_sections = []

            for section in sections:

                if (section.show_for_travel_award is None) and (section.show_for_accommodation_award is None) and  \
                        (section.show_for_payment_required is None):
                    included_sections.append(section)

                elif (section.show_for_travel_award and offer.travel_award and offer.accepted_travel_award) or \
                        (section.show_for_accommodation_award and offer.accommodation_award and offer.accepted_accommodation_award) or \
                        (section.show_for_payment_required and offer.payment_required):
                    included_sections.append(section)

            registration_form.registration_sections = included_sections

            questions = db.session.query(RegistrationQuestion).filter(
                RegistrationQuestion.registration_form_id == registration_form.id).all()

            if not questions:
                LOGGER.warn(
                    'Questions not found for  event_id: {}'.format(args['event_id']))
                return errors.QUESTION_NOT_FOUND

            for s in registration_form.registration_sections:
                s.registration_questions = []
                for q in questions:
                    if q.section_id == s.id:
                        s.registration_questions.append(q)

            return marshal(registration_form, self.registration_form_fields), 201

        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