Exemplo n.º 1
0
def showQuestion(question_id, methods=['GET', 'POST']):
    # Shows the respective question related to the current survey (latest active one).
    # If there already is a feedback id stored in cookie, the controller's action retrieves it and
    #   fills the form/question if there was already an answer to that question.
    # The page has links to next and previous question.
    # Renders a different view based on the question type.

    # Get feedback object
    cookie = request.cookies['feedback_id']
    feedback = session.query(Feedback).filter_by(id_=int(cookie)).one()

    # Form dict - can this be factored out of each function?
    qtype_forms = {
        'Freeform': AnswerFormFree(request.form),  # can this be removed?
        'Text': AnswerFormFree(request.form),
        'Thumbs': AnswerFormThumbs(request.form),
        'Stars': AnswerFormStars(request.form),
        'Smileys': AnswerFormSmileys(request.form),
        'Choices': AnswerFormChoices(request.form),
        'Picture': AnswerFormFree(request.form)
    }

    progress = 0

    # GET: Show question with prefilled answer
    if request.method == 'GET':
        # Get list of survey questions
        q = session.query(Question).filter_by(id_=question_id).one()
        q_list = session.query(Question).filter_by(
            survey_id_=q.survey_id_).all()
        q_list_ids = [question.id_ for question in q_list]

        # Figure out next_url and prev_url
        prev_q_ix = q_list_ids.index(
            q.id_) - 1 if q_list_ids.index(q.id_) - 1 >= 0 else None
        next_q_ix = q_list_ids.index(
            q.id_) + 1 if q_list_ids.index(q.id_) + 1 < len(q_list) else None
        prev_url = url_for('controllers.showQuestion',
                           question_id=q_list_ids[prev_q_ix]
                           ) if prev_q_ix != None else None  # <---
        next_url = url_for(
            'controllers.showQuestion', question_id=q_list_ids[next_q_ix]
        ) if next_q_ix != None else url_for('controllers.thankYou')
        is_first = prev_url == None

        # Set up proper template and form_action_url
        template = templates.get(
            q.type_, 'freeform.html')  # Freeform is default fallback
        form_action_url = '/feedback/questions/' + str(q.id_)

        # Set up question form and fetch possible pre-existing answer
        form = qtype_forms.get(q.type_, AnswerFormFree(request.form))

        # Check for pre-existing answers
        try:
            pre_existing_answer = session.query(Answer).filter_by(
                question_id_=q.id_,
                feedback_id_=request.cookies['feedback_id']).order_by(
                    Answer.created_at_.desc()).first()
        except:
            pre_existing_answer = None

        if pre_existing_answer != None:
            # Parse answer in db to response parameters for displaying it
            form.value_.data = pre_existing_answer.value_

        if q.type_ == 'Choices':
            form.setChoices(q.questionchoices)

        # Get progress
        progress, missing = get_progress(feedback)

        response = make_response(
            render_template(template,
                            form=form,
                            form_action_url=form_action_url,
                            question_id=q.id_,
                            question_title=q.title_,
                            question_type=q.type_,
                            prev_url=prev_url,
                            next_url=next_url,
                            is_first=is_first,
                            progress=progress,
                            answer=pre_existing_answer))

        return response

    # POST: Write answer to database
    elif request.method == 'POST':
        # Get question type
        question = session.query(Question).filter_by(
            id_=request.form['question_id']).first()

        # Parse new answer from form if it exists
        if request.form.get('value_'):
            new_answer_val = str(request.form['value_'])

        # If mandatory question is missing answer
        elif bool(question.optional_) == False:
            flash('Please answer this question.')
            this_url = url_for('controllers.showQuestion',
                               question_id=question.id_)
            return redirect(this_url)

        # If optional question is missing answer, create empty answer value
        else:
            new_answer_val = ''

        # Get possible pre-existing answer
        answers = session.query(Answer).filter_by(
            feedback_id_=int(request.cookies['feedback_id']),
            question_id_=int(request.form['question_id'])).all()

        # If pre-existing answer found, take the answer object for updating
        if len(answers) > 0:
            answer_object = answers[0]
        # If no pre-existing answer found
        else:
            # Add placeholder '' to value_
            answer_object = Answer('', int(request.cookies['feedback_id']),
                                   int(request.form['question_id']))

        # Special question type (Picture)
        if question.type_ == 'Picture':
            # user gave a new file:
            if request.files.get('userPicture'):
                file = request.files['userPicture']
                if file:
                    fileName = 'F' + str(answer_object.feedback_id_) + 'A' + str(question.id_) + \
                                '_' + str(datetime.datetime.now().hour) + \
                                '_' + str(datetime.datetime.now().minute) + \
                                '_' + str(datetime.datetime.now().second) + '.PNG'
                    imgPath = '/static/' + fileName
                    file.save(parentdir + imgPath)
                    answer_object.image_source_ = imgPath
                    answer_object.value_ = imgPath
                    session.add(answer_object)
                    session.commit()
        # All other question types:
        else:
            answer_object.value_ = new_answer_val

        session.add(answer_object)
        session.commit()

        #----------------------------------------------------------------------
        # NOTE: Replacing value_ with '' will only removes path to img, img data has to be removed separately
        #----------------------------------------------------------------------

        # Redirect to previous if 'Prev' was clicked
        if 'Previous' in request.form.keys():
            return redirect(request.form['prev_url'])

        # Redirect to next if 'Next' was clicked
        if 'Next' in request.form.keys():
            return redirect(request.form['next_url'])

        return 'POST redirection to next/prev failed'
def showQuestion(question_id, methods=['GET', 'POST']):
    # Shows the respective question related to the current survey (latest active one).
    # If there already is a feedback id stored in cookie, the controller's action retrieves it and
    #   fills the form/question if there was already an answer to that question.
    # The page has links to next and previous question.
    # Renders a different view based on the question type.

    print('\n--- ENTERING showQuestion WITH METHOD {}: {}'.format(
        request.method, 70 * '*'))

    # Get feedback object
    cookie = request.cookies['feedback_id']
    feedback = session.query(Feedback).filter_by(id_=int(cookie)).one()
    print('\n--- COOKIE / SESSION ID: {}'.format(cookie))
    print('---FEEDBACK: {}'.format(feedback.serialize))

    # Form dict - can this be factored out of each function?
    qtype_forms = {
        'Freeform': AnswerFormFree(request.form),  # can this be removed?
        'Text': AnswerFormFree(request.form),
        'Thumbs': AnswerFormThumbs(request.form),
        'Stars': AnswerFormStars(request.form),
        'Smileys': AnswerFormSmileys(request.form),
        'Choices': AnswerFormChoices(request.form),
        'Picture': AnswerFormFree(request.form)
    }

    progress = 0

    # GET: Show question with prefilled answer
    if request.method == 'GET':
        print('GET')
        print('request.form: {}'.format(request.form))

        # Get list of survey questions
        q = session.query(Question).filter_by(id_=question_id).one()
        q_list = session.query(Question).filter_by(
            survey_id_=q.survey_id_).all()
        q_list_ids = [question.id_ for question in q_list]

        # Figure out next_url and prev_url
        prev_q_ix = q_list_ids.index(
            q.id_) - 1 if q_list_ids.index(q.id_) - 1 >= 0 else None
        next_q_ix = q_list_ids.index(
            q.id_) + 1 if q_list_ids.index(q.id_) + 1 < len(q_list) else None
        prev_url = url_for('controllers.showQuestion',
                           question_id=q_list_ids[prev_q_ix]
                           ) if prev_q_ix != None else None  # <---
        next_url = url_for(
            'controllers.showQuestion', question_id=q_list_ids[next_q_ix]
        ) if next_q_ix != None else url_for('controllers.thankYou')
        is_first = prev_url == None

        # Set up proper template and form_action_url
        template = templates.get(
            q.type_, 'freeform.html')  # Freeform is default fallback
        print('Chose template {} from templates: {}'.format(
            template, templates))
        form_action_url = '/feedback/questions/' + str(q.id_)

        # Set up question form and fetch possible pre-existing answer
        form = qtype_forms.get(q.type_, AnswerFormFree(request.form))
        print('Chose form {} from qtype_forms'.format(form))
        print('---FORM.value_: {}'.format(form.value_))
        print('---FORM.value_.data: {}'.format(form.value_.data))
        # flash('Feedback_id == Cookie == {}'.format(feedback.id_))
        # flash('form.value_.data: {}'.format(form.value_.data))

        # Check for pre-existing answers
        try:
            print('---CHECK FOR PRE-EXISTING ANSWER:')
            pre_existing_answer = session.query(Answer).filter_by(
                question_id_=q.id_,
                feedback_id_=request.cookies['feedback_id']).order_by(
                    Answer.created_at_.desc()).first()
            print('---FOUND PRE-EXISTING ANSWER:', pre_existing_answer)
        except:
            pre_existing_answer = None

        if pre_existing_answer != None:
            print('---PRE-EXISTING ANSWER FOUND WITH VALUE {}'.format(
                pre_existing_answer.value_))

            # Parse answer in db to response parameters for displaying it
            print('--- CREATING RESPONSE PARAMS FROM PRE-EXISTING ANSWER:')
            print(
                '--- PRE-EXISTING ANSWER: {}, QTYPE: {}, FORM.VALUE_.DATA: {}'.
                format(pre_existing_answer.value_, q.type_, form.value_.data))
            form.value_.data = pre_existing_answer.value_
            print('form.value_.data is now {} "{}"'.format(
                type(form.value_.data), form.value_.data))
        else:
            print('---NO PRE-EXISTING ANSWER FOUND.')

        if q.type_ == 'Choices':
            form.setChoices(q.questionchoices)

        # Debug statements
        print('---TEMPLATE: {}, {}'.format(type(template), template))
        print('---FORM: {}, {}'.format(type(form), form))
        print('---FORM.VALUE_: {}'.format(form.value_))
        print('---FORM.VALUE_.DATA: {}'.format(form.value_.data))
        print('---FORM_ACTION_URL: {}, {}'.format(type(form_action_url),
                                                  form_action_url))
        print('---LIST OF QUESTION IDS: {}'.format(q_list_ids))
        print('---QUESTION: {}, {}'.format(type(q), q))
        print('---QUESTION TYPE: {}, {}'.format(type(q.type_), q.type_))
        print('---IS_FIRST: {}, {}'.format(type(is_first), is_first))
        print('---QUESTION_ID: {}, {}'.format(type(q.id_), q.id_))
        print('---QUESTION_TITLE: {}, {}'.format(type(q.title_), q.title_))
        print('---NEXT_URL: {}, {}'.format(type(next_url), next_url))
        print('---PREV_URL: {}, {}'.format(type(prev_url), prev_url))

        # Get progress
        progress, missing = get_progress(feedback)

        # print('---PROGRESS {}'.format(progress))
        # print('---MISSING {}'.format(missing))
        # print('---MISSING MANDATORY {}'.format(missing))
        # flash('progress: {}'.format(progress))
        # flash('missing: {}'.format(missing))
        # flash('missing: {}'.format(missing))

        #
        #--------- DEBUG HERE Thumbs form!!!
        # form = qtype_forms.get('Thumb', AnswerFormFree(request.form))
        print('form.value_: "{}"'.format(form.value_))
        print('form.value_.data: "{}"'.format(form.value_.data))
        if q.type_ not in ['Freeform', 'Text', 'Picture', 'Thankyou']:
            print('form.value_.choices: "{}"'.format(form.value_.choices))

        print('---FORM: {}'.format(form))
        print('---FORM.VALUE_.DATA: {}'.format(form.value_.data))

        response = make_response(
            render_template(template,
                            form=form,
                            form_action_url=form_action_url,
                            question_id=q.id_,
                            question_title=q.title_,
                            question_type=q.type_,
                            prev_url=prev_url,
                            next_url=next_url,
                            is_first=is_first,
                            progress=progress,
                            answer=pre_existing_answer))

        print('---RESPONSE CREATED. EXITING showQuestion AND RENDERING {}'.
              format(template))

        return response

    # POST: Write answer to database
    elif request.method == 'POST':
        print('POST')
        print('request.form: {}'.format(request.form))
        print('request.cookies: {}'.format(request.cookies))

        # Get question type
        question = session.query(Question).filter_by(
            id_=request.form['question_id']).first()

        # Parse new answer from form if it exists
        if request.form.get('value_'):
            new_answer_val = str(request.form['value_'])

        # If mandatory question is missing answer
        elif bool(question.optional_) == False:
            print('---THIS QUESTION ({}) IS MANDATORY!'.format(question.id_))
            flash('Please answer this question.')
            this_url = url_for('controllers.showQuestion',
                               question_id=question.id_)
            return redirect(this_url)

        # If optional question is missing answer, create empty answer value
        else:
            new_answer_val = ''
        print('---GOT new_answer_val FROM FORM: {}'.format(new_answer_val))

        # Get possible pre-existing answer
        print('---GET POSSIBLE PRE-EXISTING ANSWER')
        answers = session.query(Answer).filter_by(
            feedback_id_=int(request.cookies['feedback_id']),
            question_id_=int(request.form['question_id'])).all()
        print('len(answer_object): {}'.format(len(answers)))

        # If pre-existing answer found, take the answer object for updating
        if len(answers) > 0:
            answer_object = answers[0]
            print('---FOUND PRE-EXISTING ANSWER: {}'.format(answer_object))
            print('---PRE-EXISTING answer.value_: {}'.format(
                answer_object.value_))
        # If no pre-existing answer found
        else:
            print('---NO PRE-EXISTING ANSWER FOUND!')
            # Add placeholder '' to value_
            answer_object = Answer('', int(request.cookies['feedback_id']),
                                   int(request.form['question_id']))
            print('---CREATED NEW ANSWER OBJECT:')

        # Special question type (Picture)
        if question.type_ == 'Picture':
            # user gave a new file:
            if request.files.get('userPicture'):
                file = request.files['userPicture']
                if file:
                    fileName = 'F' + str(answer_object.feedback_id_) + 'A' + str(question.id_) + \
                                '_' + str(datetime.datetime.now().hour) + \
                                '_' + str(datetime.datetime.now().minute) + \
                                '_' + str(datetime.datetime.now().second) + '.PNG'
                    imgPath = '/static/' + fileName
                    file.save(parentdir + imgPath)
                    answer_object.image_source_ = imgPath
                    answer_object.value_ = imgPath
                    session.add(answer_object)
                    session.commit()
        # All other question types:
        else:
            answer_object.value_ = new_answer_val

        print('answer.serialize {}'.format(answer_object.serialize))
        print('---ANSWER_OBJECT.value_ type: {}, len {} value_ {}'.format(
            type(answer_object.value_),
            len(answer_object.value_),
            answer_object.value_,
        ))

        session.add(answer_object)
        session.commit()

        #----------------------------------------------------------------------
        # TODO: Maybe allow for zero length answer if user wants to remove answer?
        # NOTE: Replacing value_ with '' will only removes path to img, img data has to be removed separately
        #----------------------------------------------------------------------

        # Redirect to previous if 'Prev' was clicked
        if 'Previous' in request.form.keys():
            print('---EXITING showQuestion [POST], REDIRECTING TO PREV: {}'.
                  format(request.form['prev_url']))
            return redirect(request.form['prev_url'])

        # Redirect to next if 'Next' was clicked
        if 'Next' in request.form.keys():
            print('---EXITING showQuestion [POST], REDIRECTING TO NEXT: {}'.
                  format(request.form['next_url']))
            return redirect(request.form['next_url'])

        return 'POST redirection to next/prev failed'