def survey_update(request, survey_id, template_name="survey/survey_register.html"): survey = get_object_or_404(Survey, pk=survey_id) surveys = Questionnaires() survey_title = surveys.get_survey_title(survey.lime_survey_id) limesurvey_available = check_limesurvey_access(request, surveys) surveys.release_session_key() survey_form = SurveyForm(request.POST or None, instance=survey, initial={'title': str(survey.lime_survey_id) + ' - ' + survey_title}) if request.method == "POST": if request.POST['action'] == "save": if survey_form.is_valid(): if survey_form.has_changed(): survey_form.save() messages.success(request, _('Questionnaire updated successfully.')) else: messages.success(request, _('There are no changes to save.')) redirect_url = reverse("survey_view", args=(survey.id,)) return HttpResponseRedirect(redirect_url) context = { "limesurvey_available": limesurvey_available, "survey": survey, "survey_form": survey_form, "survey_title": survey_title, "editing": True, "creating": False} return render(request, template_name, context)
def survey_list(request, template_name='survey/survey_list.html'): surveys = Questionnaires() limesurvey_available = check_limesurvey_access(request, surveys) questionnaires_list = [] language_code = request.LANGUAGE_CODE for survey in Survey.objects.all(): language = get_questionnaire_language(surveys, survey.lime_survey_id, language_code) questionnaires_list.append({ 'id': survey.id, 'lime_survey_id': survey.lime_survey_id, 'title': surveys.get_survey_title(survey.lime_survey_id, language), 'is_initial_evaluation': survey.is_initial_evaluation }) surveys.release_session_key() questionnaires_list = sorted(questionnaires_list, key=itemgetter('title')) context = { 'questionnaires_list': questionnaires_list, 'limesurvey_available': limesurvey_available } return render(request, template_name, context)
def survey_update(request, survey_id, template_name="survey/survey_register.html"): survey = get_object_or_404(Survey, pk=survey_id) surveys = Questionnaires() language = get_questionnaire_language(surveys, survey.lime_survey_id, request.LANGUAGE_CODE) survey_title = surveys.get_survey_title(survey.lime_survey_id, language) limesurvey_available = check_limesurvey_access(request, surveys) surveys.release_session_key() survey_form = SurveyForm(request.POST or None, instance=survey, initial={'title': str(survey.lime_survey_id) + ' - ' + survey_title}) if request.method == "POST": if request.POST['action'] == "save": if survey_form.is_valid(): if survey_form.has_changed(): survey_form.save() messages.success(request, _('Questionnaire updated successfully.')) else: messages.success(request, _('There are no changes to save.')) redirect_url = reverse("survey_view", args=(survey.id,)) return HttpResponseRedirect(redirect_url) context = { "limesurvey_available": limesurvey_available, "survey": survey, "survey_form": survey_form, "survey_title": survey_title, "editing": True, "creating": False} return render(request, template_name, context)
def survey_list(request, template_name='survey/survey_list.html'): surveys = Questionnaires() limesurvey_available = check_limesurvey_access(request, surveys) questionnaires_list = [] for survey in Survey.objects.all(): questionnaires_list.append( { 'id': survey.id, 'lime_survey_id': survey.lime_survey_id, 'title': surveys.get_survey_title(survey.lime_survey_id), 'is_initial_evaluation': survey.is_initial_evaluation } ) surveys.release_session_key() questionnaires_list = sorted(questionnaires_list, key=itemgetter('title')) context = { 'questionnaires_list': questionnaires_list, 'limesurvey_available': limesurvey_available } return render(request, template_name, context)
def survey_view(request, survey_id, template_name="survey/survey_register.html"): survey = get_object_or_404(Survey, pk=survey_id) surveys = Questionnaires() limesurvey_available = check_limesurvey_access(request, surveys) language = get_questionnaire_language(surveys, survey.lime_survey_id, request.LANGUAGE_CODE) survey_title = surveys.get_survey_title(survey.lime_survey_id, language) # There is no need to use "request.POST or None" because the data will never be changed here. In fact we have to # use "None" only, because request.POST does not contain any value because the fields are disabled, and this results # in the form being created without considering the initial value. survey_form = SurveyForm( None, instance=survey, initial={'title': str(survey.lime_survey_id) + ' - ' + survey_title}) for field in survey_form.fields: survey_form.fields[field].widget.attrs['disabled'] = True if request.method == "POST": if request.POST['action'] == "remove": try: survey.delete() messages.success(request, _('Questionnaire deleted successfully.')) return redirect('survey_list') except ProtectedError: messages.error( request, _("It was not possible to delete questionnaire, because there are experimental " "answers or steps associated.")) patients_questionnaire_data_list = create_patients_questionnaire_data_list( survey, surveys) if request.user.has_perm("experiment.view_researchproject"): experiments_questionnaire_data_list = create_experiments_questionnaire_data_list( survey, surveys) else: experiments_questionnaire_data_list = [] context = { "limesurvey_available": limesurvey_available, "patients_questionnaire_data_list": patients_questionnaire_data_list, "experiments_questionnaire_data_list": experiments_questionnaire_data_list, "survey": survey, "survey_form": survey_form, "survey_title": survey_title, } return render(request, template_name, context)
def get_survey_title_based_on_the_user_language(survey, language_code, update=False): if not update: # Get the titles in both languages and return the one compatible with the user's language, # If the title is blank in that language, return it in the other language, and # if that one is also blank, try to update the titles in each language # if any of them updates isn't blank, recursively calls this function # otherwise, try to get the title for this survey at LimeSurvey and return it titles = {'pt-br': survey.pt_title, 'en': survey.en_title} fallback_language = 'en' if language_code == 'pt-br' else 'pt-br' if titles[language_code]: return titles[language_code] elif titles[fallback_language]: return titles[fallback_language] surveys = Questionnaires() pt_title = surveys.get_survey_title(survey.lime_survey_id, 'pt-BR') en_title = surveys.get_survey_title(survey.lime_survey_id, 'en') if language_code == 'pt-br' and pt_title: surveys.release_session_key() survey.pt_title = pt_title survey.save() return get_survey_title_based_on_the_user_language(survey, language_code) elif language_code == 'en' and en_title: surveys.release_session_key() survey.en_title = en_title survey.save() return get_survey_title_based_on_the_user_language(survey, language_code) else: title = surveys.get_survey_title(survey.lime_survey_id) surveys.release_session_key() if title: return title else: return survey.lime_survey_id
def get_survey_title_based_on_the_user_language(survey, language_code, update=False): if not update: # Get the titles in both languages and return the one compatible with the user's language, # If the title is blank in that language, return it in the other language, and # if that one is also blank, try to update the titles in each language # if any of them updates isn't blank, recursively calls this function # otherwise, try to get the title for this survey at LimeSurvey and return it titles = {'pt-br': survey.pt_title, 'en': survey.en_title} fallback_language = 'en' if language_code == 'pt-br' else 'pt-br' if titles[language_code]: return titles[language_code] elif titles[fallback_language]: return titles[fallback_language] surveys = Questionnaires() pt_title = surveys.get_survey_title(survey.lime_survey_id, 'pt-BR') en_title = surveys.get_survey_title(survey.lime_survey_id, 'en') if language_code == 'pt-br' and pt_title: surveys.release_session_key() survey.pt_title = pt_title survey.save() return get_survey_title_based_on_the_user_language(survey, language_code) elif language_code == 'en' and en_title: surveys.release_session_key() survey.en_title = en_title survey.save() return get_survey_title_based_on_the_user_language(survey, language_code) else: title = surveys.get_survey_title(survey.lime_survey_id) surveys.release_session_key() if title: return title else: return survey.lime_survey_id
def test_complete_survey(self): lime_survey = Questionnaires() sid = None try: # Cria uma nova survey no lime survey title_survey = 'Questionario de teste' sid = lime_survey.add_survey(9999, title_survey, 'en', 'G') # Obtenho o titulo da survey survey_title = lime_survey.get_survey_title(sid) self.assertEqual(survey_title, title_survey) # Verifica se esta ativa survey_active = lime_survey.get_survey_properties(sid, 'active') self.assertEqual(survey_active, 'N') # Obtem uma propriedade - Administrador da Survey survey_admin = lime_survey.get_survey_properties(sid, 'admin') self.assertEqual(survey_admin, None) # Importar grupo de questoes handle_file_import = \ open('quiz/static/quiz/tests/limesurvey_groups.lsg', 'r') questions_data = handle_file_import.read() questions_id = \ lime_survey.insert_questions(sid, questions_data, 'lsg') self.assertGreaterEqual(questions_id, 1) # Inicia tabela de tokens self.assertEqual(lime_survey.activate_tokens(sid), 'OK') # Ativar survey self.assertEqual(lime_survey.activate_survey(sid), 'OK') # Verifica se esta ativa survey_active = lime_survey.get_survey_properties(sid, 'active') self.assertEqual(survey_active, 'Y') # Adiciona participante e obtem o token result_token = lime_survey.add_participant(sid) # Verifica se o token está presente na tabela de participantes token = lime_survey.get_participant_properties( sid, result_token, "token") self.assertEqual(token, result_token['token']) finally: # Deleta a survey gerada no Lime Survey self.assertEqual(lime_survey.delete_survey(sid), 'OK')
def test_complete_survey(self): lime_survey = Questionnaires() sid = None try: # Cria uma nova survey no lime survey title_survey = 'Questionario de teste' sid = lime_survey.add_survey(9999, title_survey, 'en', 'G') # Obtenho o titulo da survey survey_title = lime_survey.get_survey_title(sid) self.assertEqual(survey_title, title_survey) # Verifica se esta ativa survey_active = lime_survey.get_survey_properties(sid, 'active') self.assertEqual(survey_active, 'N') # Obtem uma propriedade - Administrador da Survey survey_admin = lime_survey.get_survey_properties(sid, 'admin') self.assertEqual(survey_admin, None) # Importar grupo de questoes handle_file_import = \ open('quiz/static/quiz/tests/limesurvey_groups.lsg', 'r') questions_data = handle_file_import.read() questions_id = \ lime_survey.insert_questions(sid, questions_data, 'lsg') self.assertGreaterEqual(questions_id, 1) # Inicia tabela de tokens self.assertEqual(lime_survey.activate_tokens(sid), 'OK') # Ativar survey self.assertEqual(lime_survey.activate_survey(sid), 'OK') # Verifica se esta ativa survey_active = lime_survey.get_survey_properties(sid, 'active') self.assertEqual(survey_active, 'Y') # Adiciona participante e obtem o token result_token = lime_survey.add_participant(sid) # Verifica se o token está presente na tabela de participantes token = lime_survey.get_participant_properties(sid, result_token, "token") self.assertEqual(token, result_token['token']) finally: # Deleta a survey gerada no Lime Survey self.assertEqual(lime_survey.delete_survey(sid), 'OK')
def find_questionnaire_name(survey, language_code): language_code = language_code.lower() titles = {'pt-br': survey.pt_title, 'en': survey.en_title} fallback_language = 'en' if language_code == 'pt-br' else 'pt-br' if titles[language_code] is not None and titles[language_code] != '': title = titles[language_code] elif titles[fallback_language] is not None \ and titles[fallback_language] != '': title = titles[fallback_language] else: surveys = Questionnaires() title = surveys.get_survey_title(survey.lime_survey_id) surveys.release_session_key() return {'sid': survey.lime_survey_id, 'name': title}
def survey_view(request, survey_id, template_name="survey/survey_register.html"): survey = get_object_or_404(Survey, pk=survey_id) surveys = Questionnaires() limesurvey_available = check_limesurvey_access(request, surveys) language = get_questionnaire_language(surveys, survey.lime_survey_id, request.LANGUAGE_CODE) survey_title = surveys.get_survey_title(survey.lime_survey_id, language) # There is no need to use "request.POST or None" because the data will never be changed here. In fact we have to # use "None" only, because request.POST does not contain any value because the fields are disabled, and this results # in the form being created without considering the initial value. survey_form = SurveyForm(None, instance=survey, initial={'title': str(survey.lime_survey_id) + ' - ' + survey_title}) for field in survey_form.fields: survey_form.fields[field].widget.attrs['disabled'] = True if request.method == "POST": if request.POST['action'] == "remove": try: survey.delete() messages.success(request, _('Questionnaire deleted successfully.')) return redirect('survey_list') except ProtectedError: messages.error(request, _("It was not possible to delete questionnaire, because there are experimental " "answers or steps associated.")) patients_questionnaire_data_list = create_patients_questionnaire_data_list(survey, surveys) if request.user.has_perm("experiment.view_researchproject"): experiments_questionnaire_data_list = create_experiments_questionnaire_data_list(survey, surveys) else: experiments_questionnaire_data_list = [] context = { "limesurvey_available": limesurvey_available, "patients_questionnaire_data_list": patients_questionnaire_data_list, "experiments_questionnaire_data_list": experiments_questionnaire_data_list, "survey": survey, "survey_form": survey_form, "survey_title": survey_title, } return render(request, template_name, context)
def get_questionnaire_responses(language_code, lime_survey_id, token_id, request): groups_of_questions = [] surveys = Questionnaires() token = surveys.get_participant_properties( lime_survey_id, token_id, "token" ) question_properties = [] groups = surveys.list_groups(lime_survey_id) # defining language to be showed languages = surveys.get_survey_languages(lime_survey_id) # language to be showed can be the base language, or... language = languages['language'] # ...can be one of the additional languages if language.lower() != language_code.lower() and \ languages['additional_languages']: # search for the right language in addional languages, # considering that the LimeSurvey uses upper case in the two-letter # language code, like en-US and pt-BR. additional_languages_list = languages['additional_languages'].split(' ') additional_languages_list_lower = [item.lower() for item in additional_languages_list] if language_code.lower() in additional_languages_list_lower: index = additional_languages_list_lower.index(language_code.lower()) language = additional_languages_list[index] survey_title = surveys.get_survey_title(lime_survey_id, language) if not isinstance(groups, dict): for group in groups: if 'id' in group and group['id']['language'] == language: question_list = surveys.list_questions( lime_survey_id, group['id']['gid'] ) question_list = sorted(question_list) for question in question_list: properties = surveys.get_question_properties( question, group['id']['language'] ) # cleaning the question field properties['question'] = re.sub( '{.*?}', '', re.sub('<.*?>', '', properties['question']) ) properties['question'] = \ properties['question'].replace(' ', '').strip() is_purely_formula = (properties['type'] == '*') and \ (properties['question'] == '') if not is_purely_formula and properties['question'] != '': if isinstance(properties['subquestions'], dict): question_properties.append({ 'gid': group['id']['gid'], 'group_name': group['group_name'], 'qid': question, 'question': properties['question'], 'question_id': properties['title'], 'answer_options': 'super_question', 'type': 'X', 'other': False, 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) for key, value in sorted( properties['subquestions'].items() ): question_properties.append({ 'gid': group['id']['gid'], 'group_name': group['group_name'], 'qid': question, 'question': value['question'], 'question_id': properties['title'] + '[' + value['title'] + ']', 'answer_options': properties['answeroptions'], 'type': properties['type'], 'other': False, 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) if properties['other'] == 'Y': question_properties.append({ 'gid': group['id']['gid'], 'group_name': group['group_name'], 'qid': question, 'question': _('Other'), 'question_id': properties['title'] + '[other]', 'answer_options': properties['answeroptions'], 'type': properties['type'], 'other': True, 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) else: question_properties.append({ 'gid': group['id']['gid'], 'group_name': group['group_name'], 'qid': question, 'question': properties['question'], 'question_id': properties['title'], 'answer_options': properties['answeroptions'], 'type': properties['type'], 'other': False, 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) else: question_properties.append({ 'gid': group['id']['gid'], 'group_name': group['group_name'], 'qid': question, 'question': _("Formula") + " (" + properties['title'] + ")", 'question_id': properties['title'], 'answer_options': properties['answeroptions'], 'type': properties['type'], 'other': False, 'attributes_lang': properties['attributes_lang'], 'hidden': False }) # Reading from Limesurvey and... responses_string = surveys.get_responses_by_token( lime_survey_id, token, language ) # ... transforming to a list: responses_list = [] if isinstance(responses_string, bytes): reader_ = csv.reader( StringIO(responses_string.decode()), delimiter=',' ) for row in reader_: responses_list.append(row) previous_question = '' last_super_question = '' last_super_question_index = [] # for question in question_properties: for response in responses_list[0]: questions = [] for question_prop in question_properties: question_id = question_prop['question_id'] if question_id in response: if response.split('[')[0] in question_id: questions.append(question_prop) for question in questions: if question and \ (question['question_id'] != previous_question): if not question['hidden']: if isinstance(question['answer_options'], str) \ and question['answer_options'] == \ "super_question": if question['question'] != '' and \ question['question_id'] != \ last_super_question: groups_of_questions = \ add_questionnaire_response_to_group( groups_of_questions, question, '', None, no_response_flag=True ) last_super_question = \ question['question_id'] last_super_question_index = [ len(groups_of_questions) - 1, len(groups_of_questions[-1] ['questionnaire_responses']) - 1] else: previous_question = question['question_id'] answer = '' no_response_flag = False # type 'X' means "Text display" if not question['type'] == 'X': # type "1" means "Array dual scale" if question['type'] == '1': answer_list = [] if question['question_id'] + "[1]" in \ responses_list[0]: index = \ responses_list[0].index( question['question_id'] + "[1]" ) answer_options = \ question['answer_options'] answer = \ question['question_id'] + "[1]: " if responses_list[1][index] in \ answer_options: answer_option = \ answer_options[responses_list[1][index]] answer += \ answer_option['answer'] else: # Sem resposta answer += _('No answer') no_response_flag = True answer_list.append(answer) if question['question_id'] + "[2]" in \ responses_list[0]: index = \ responses_list[0].index( question['question_id'] + "[2]" ) answer_options = \ question['answer_options'] answer = \ question['question_id'] + "[2]: " if responses_list[1][index] in \ answer_options: answer_option = \ answer_options[responses_list[1][index]] answer += \ answer_option['answer'] else: # sem resposta answer += _('No answer') no_response_flag = True answer_list.append(answer) groups_of_questions =\ add_questionnaire_response_to_group( groups_of_questions, question, answer_list, None, no_response_flag ) else: link = '' if question['question_id'] in \ responses_list[0]: index = \ responses_list[0].index(question['question_id']) answer_options = question['answer_options'] if isinstance(answer_options, dict): # type "M" means "Multiple # choice" if question['type'] == 'M': answer = responses_list[1][index] if question['other']: if answer == '': no_response_flag = True else: if answer != 'Y': no_response_flag = True else: if responses_list[1][index] in \ answer_options: answer_option = \ answer_options[responses_list[1][index]] answer = \ answer_option['answer'] else: # sem resposta answer = _('No answer') no_response_flag = True else: # type "D" means "Date/Time" if question['type'] == 'D': if responses_list[1][index]: answer = \ datetime.datetime.strptime( responses_list[1][index], '%Y-%m-%d %H:%M:%S' ) else: answer = '' no_response_flag = True else: answer = responses_list[1][index] # type "M" means "Multiple choice" if question['type'] == 'M': if question['other']: if answer == '': no_response_flag = True else: if answer != 'Y': no_response_flag = True # not show fileupload questions if question['type'] != '|': groups_of_questions = \ add_questionnaire_response_to_group( groups_of_questions, question, answer, link, no_response_flag ) # checking if the super-question # should be unmarked if last_super_question and not \ no_response_flag and \ question['question_id'].split('[')[0] \ == last_super_question: mark_off_super_question( groups_of_questions, last_super_question_index ) else: messages.error( request, _("LimeSurvey did not find fill data for this questionnaire.") ) surveys.release_session_key() return survey_title, groups_of_questions
def survey_update_sensitive_questions(request, survey_id, template_name="survey/survey_sensitive_fields.html"): survey = get_object_or_404(Survey, pk=survey_id) surveys = Questionnaires() language = get_questionnaire_language(surveys, survey.lime_survey_id, request.LANGUAGE_CODE) survey_title = surveys.get_survey_title(survey.lime_survey_id, language) limesurvey_available = check_limesurvey_access(request, surveys) current_selected_fields = SensitiveQuestion.objects.filter(survey=survey) field_code = get_survey_header(surveys, survey, language, 'code') field_text = get_survey_header(surveys, survey, language, 'full') surveys.release_session_key() counter = 0 available_fields = [] while counter < len(field_code): if field_code[counter] not in questionnaire_evaluation_fields_excluded: available_fields.append( {'code': field_code[counter], 'text': field_text[counter], 'checked': current_selected_fields.filter(code=field_code[counter]).exists()}) counter += 1 if request.method == "POST": if request.POST['action'] == "save": changed = False # for each available fields for field in available_fields: field_code = field['code'] field_text = field['text'] # field was selected if "field_" + str(field_code) in request.POST and request.POST["field_" + str(field_code)] == 'on': # field not in current configuration if not current_selected_fields.filter(code=str(field_code)).exists(): # Add itens selected SensitiveQuestion.objects.create(survey=survey, code=field_code, question=field_text) changed = True else: # field in current configuration if current_selected_fields.filter(code=str(field_code)).exists(): current_selected_fields.filter(code=str(field_code)).delete() changed = True # Exclude unknown items unkown_items = SensitiveQuestion.objects.filter(survey=survey).exclude( code__in=[field['code'] for field in available_fields]) if unkown_items.exists(): unkown_items.delete() changed = True if changed: messages.success(request, _('Questionnaire was updated successfully.')) else: messages.success(request, _('There are no changes to save.')) redirect_url = reverse("survey_view", args=(survey.id,)) return HttpResponseRedirect(redirect_url) context = { "available_fields": available_fields, "limesurvey_available": limesurvey_available, "survey": survey, "survey_title": survey_title} return render(request, template_name, context)
def get_questionnaire_fields(questionnaire_code_list, language_current="pt-BR"): """ :param questionnaire_code_list: list with questionnaire id to be formatted with json file :return: 1 list: questionnaires_included - questionnaire_id that was included in the .txt file """ questionnaires_included = [] questionnaire_lime_survey = Questionnaires() for questionnaire in questionnaire_code_list: questionnaire_id = questionnaire["sid"] language_new = get_questionnaire_language(questionnaire_lime_survey, questionnaire_id, language_current) # get a valid token (anyone) survey = Survey.objects.filter(lime_survey_id=questionnaire_id).first() token_id = QuestionnaireResponse.objects.filter(survey=survey).first().token_id token = questionnaire_lime_survey.get_participant_properties(questionnaire_id, token_id, "token") responses_string = questionnaire_lime_survey.get_header_response(questionnaire_id, language_new, token) questionnaire_title = questionnaire_lime_survey.get_survey_title(questionnaire_id, language_new) # print("id: %d " % questionnaire_id) if not isinstance(responses_string, dict): record_question = {'sid': questionnaire_id, "title": questionnaire_title, "output_list": []} questionnaire_questions = perform_csv_response(responses_string) responses_full = questionnaire_lime_survey.get_header_response(questionnaire_id, language_new, token, heading_type='full') questionnaire_questions_full = perform_csv_response(responses_full) index = 0 # line 0 - header information for question in questionnaire_questions[0]: if question not in questionnaire_evaluation_fields_excluded: # properties = questionnaire_lime_survey.get_question_properties(question, language) # record_question["output_list"].append({"field": question, # "header": question}) description = questionnaire_questions_full[0][index] # if len(description)+3+len(question) > 120: # length = 120 - (3+len(question)) # # description_part1 = description[:length-30] # description_part2 = description[-25:] # description = description_part1 + "..." + description_part2 record_question["output_list"].append({"field": question, "header": question, "description": description }) index += 1 questionnaires_included.append(record_question) questionnaire_lime_survey.release_session_key() return questionnaires_included
def get_questionnaire_responses(language_code, lime_survey_id, token_id, request): questionnaire_responses = [] surveys = Questionnaires() token = surveys.get_participant_properties(lime_survey_id, token_id, "token") question_properties = [] groups = surveys.list_groups(lime_survey_id) survey_title = surveys.get_survey_title(lime_survey_id) if not isinstance(groups, dict): # defining language to be showed languages = surveys.get_survey_languages(lime_survey_id) # language to be showed can be the base language, or... language = languages['language'] # ...can be one of the additional languages if language.lower() != language_code.lower() and languages['additional_languages']: # search for the right language in addional languages, # considering that the LimeSurvey uses upper case in the two-letter language code, like en-US and pt-BR. additional_languages_list = languages['additional_languages'].split(' ') additional_languages_list_lower = [item.lower() for item in additional_languages_list] if language_code.lower() in additional_languages_list_lower: index = additional_languages_list_lower.index(language_code.lower()) language = additional_languages_list[index] for group in groups: if 'id' in group and group['id']['language'] == language: question_list = surveys.list_questions(lime_survey_id, group['id']) question_list = sorted(question_list) for question in question_list: properties = surveys.get_question_properties(question, group['id']['language']) # cleaning the question field properties['question'] = re.sub('{.*?}', '', re.sub('<.*?>', '', properties['question'])) properties['question'] = properties['question'].replace(' ', '').strip() is_purely_formula = (properties['type'] == '*') and (properties['question'] == '') if not is_purely_formula and properties['question'] != '': if isinstance(properties['subquestions'], dict): question_properties.append({ 'question': properties['question'], 'question_id': properties['title'], 'answer_options': 'super_question', 'type': properties['type'], 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) for key, value in sorted(properties['subquestions'].items()): question_properties.append({ 'question': value['question'], 'question_id': properties['title'] + '[' + value['title'] + ']', 'answer_options': properties['answeroptions'], 'type': properties['type'], 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) else: question_properties.append({ 'question': properties['question'], 'question_id': properties['title'], 'answer_options': properties['answeroptions'], 'type': properties['type'], 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) # Reading from Limesurvey and... responses_string = surveys.get_responses_by_token(lime_survey_id, token, language) # ... transforming to a list: # response_list[0] has the questions # response_list[1] has the answers responses_list = [] if isinstance(responses_string, bytes): reader = csv.reader(StringIO(responses_string.decode()), delimiter=',') for row in reader: responses_list.append(row) for question in question_properties: if not question['hidden']: if isinstance(question, str) and question['answer_options'] == "super_question": if question['question'] != '': questionnaire_responses.append({ 'question': question['question'], 'answer': '', 'type': question['type'] }) else: answer = '' if question['type'] == '1': answer_list = [] if question['question_id'] + "[1]" in responses_list[0]: index = responses_list[0].index(question['question_id'] + "[1]") answer_options = question['answer_options'] # if 'dualscale_headerA' in question['attributes_lang']: answer = question['attributes_lang']['dualscale_headerA'] + ": " if responses_list[1][index] in answer_options: answer_option = answer_options[responses_list[1][index]] answer += answer_option['answer'] else: answer += 'Sem resposta' # else: # answer += 'Sem resposta' answer_list.append(answer) if question['question_id'] + "[2]" in responses_list[0]: index = responses_list[0].index(question['question_id'] + "[2]") answer_options = question['answer_options'] # if 'dualscale_headerB' in question['attributes_lang']: answer = question['attributes_lang']['dualscale_headerB'] + ": " if responses_list[1][index] in answer_options: answer_option = answer_options[responses_list[1][index]] answer += answer_option['answer'] else: answer += 'Sem resposta' # else: # answer += 'Sem resposta' answer_list.append(answer) questionnaire_responses.append({ 'question': question['question'], 'answer': answer_list, 'type': question['type'] }) else: if question['question_id'] in responses_list[0]: index = responses_list[0].index(question['question_id']) answer_options = question['answer_options'] if isinstance(answer_options, dict): if responses_list[1][index] in answer_options: answer_option = answer_options[responses_list[1][index]] answer = answer_option['answer'] else: answer = 'Sem resposta' else: if question['type'] == 'D': if responses_list[1][index]: answer = datetime.datetime.strptime(responses_list[1][index], '%Y-%m-%d %H:%M:%S') else: answer = '' else: answer = responses_list[1][index] questionnaire_responses.append({ 'question': question['question'], 'answer': answer, 'type': question['type'] }) else: messages.error(request, _("LimeSurvey did not find fill data for this questionnaire.")) surveys.release_session_key() return survey_title, questionnaire_responses
def survey_update_sensitive_questions( request, survey_id, template_name="survey/survey_sensitive_fields.html"): survey = get_object_or_404(Survey, pk=survey_id) surveys = Questionnaires() language = get_questionnaire_language(surveys, survey.lime_survey_id, request.LANGUAGE_CODE) survey_title = surveys.get_survey_title(survey.lime_survey_id, language) limesurvey_available = check_limesurvey_access(request, surveys) current_selected_fields = SensitiveQuestion.objects.filter(survey=survey) field_code = get_survey_header(surveys, survey, language, 'code') field_text = get_survey_header(surveys, survey, language, 'full') surveys.release_session_key() counter = 0 available_fields = [] while counter < len(field_code): if field_code[counter] not in questionnaire_evaluation_fields_excluded: available_fields.append({ 'code': field_code[counter], 'text': field_text[counter], 'checked': current_selected_fields.filter( code=field_code[counter]).exists() }) counter += 1 if request.method == "POST": if request.POST['action'] == "save": changed = False # for each available fields for field in available_fields: field_code = field['code'] field_text = field['text'] # field was selected if "field_" + str(field_code) in request.POST and request.POST[ "field_" + str(field_code)] == 'on': # field not in current configuration if not current_selected_fields.filter( code=str(field_code)).exists(): # Add itens selected SensitiveQuestion.objects.create(survey=survey, code=field_code, question=field_text) changed = True else: # field in current configuration if current_selected_fields.filter( code=str(field_code)).exists(): current_selected_fields.filter( code=str(field_code)).delete() changed = True # Exclude unknown items unkown_items = SensitiveQuestion.objects.filter( survey=survey).exclude( code__in=[field['code'] for field in available_fields]) if unkown_items.exists(): unkown_items.delete() changed = True if changed: messages.success(request, _('Questionnaire was updated successfully.')) else: messages.success(request, _('There are no changes to save.')) redirect_url = reverse("survey_view", args=(survey.id, )) return HttpResponseRedirect(redirect_url) context = { "available_fields": available_fields, "limesurvey_available": limesurvey_available, "survey": survey, "survey_title": survey_title } return render(request, template_name, context)
def test_survey_create_with_fileupload_question(self): lime_survey = Questionnaires() sid = None try: # Cria uma nova survey no lime survey title_survey = 'Questionario de teste' sid = lime_survey.add_survey(9999, title_survey, 'en', 'G') # Obtenho o titulo da survey survey_title = lime_survey.get_survey_title(sid) self.assertEqual(survey_title, title_survey) # Verifica se esta ativa survey_active = lime_survey.get_survey_properties(sid, 'active') self.assertEqual(survey_active, 'N') # Obtem uma propriedade - Administrador da Survey survey_admin = lime_survey.get_survey_properties(sid, 'admin') self.assertEqual(survey_admin, None) # Importar grupo de questoes handle_file_import = \ open('quiz/static/quiz/tests/limesurvey_groups_with_fileupload.lsg', 'r') questions_data = handle_file_import.read() questions_id = \ lime_survey.insert_questions(sid, questions_data, 'lsg') self.assertGreaterEqual(questions_id, 1) # Inicia tabela de tokens self.assertEqual(lime_survey.activate_tokens(sid), 'OK') # Ativar survey self.assertEqual(lime_survey.activate_survey(sid), 'OK') # Verifica se esta ativa survey_active = lime_survey.get_survey_properties(sid, 'active') self.assertEqual(survey_active, 'Y') # Request the survey register screen response = self.client.get(reverse('survey_create')) self.assertEqual(response.status_code, 200) # Set survey data # self.data = {'action': 'save', 'title': 'Survey title'} self.data = {'action': 'save', 'questionnaire_selected': sid} # Count the number of surveys currently in database count_before_insert = Survey.objects.all().count() # Add the new survey response = self.client.post(reverse('survey_create'), self.data) self.assertEqual(response.status_code, 302) # Assert if the message is parsed self.assertEqual( response.wsgi_request._messages._queued_messages[0].message, 'O NES não importa arquivos carregados pelo Limesurvey através de questões do tipo \'Envio de arquivo\'. Veja \"Best Pratices and Recommendations\" em https://nes.rtfd.io para mais detalhes.' ) # Count the number of surveys currently in database count_after_insert = Survey.objects.all().count() # Check if it has increased self.assertEqual(count_after_insert, count_before_insert + 1) finally: # Deleta a survey gerada no Lime Survey self.assertEqual(lime_survey.delete_survey(sid), 'OK')
def get_questionnaire_responses(language_code, lime_survey_id, token_id, request): groups_of_questions = [] surveys = Questionnaires() token = surveys.get_participant_properties(lime_survey_id, token_id, "token") question_properties = [] groups = surveys.list_groups(lime_survey_id) # defining language to be showed languages = surveys.get_survey_languages(lime_survey_id) # language to be showed can be the base language, or... language = languages['language'] # ...can be one of the additional languages if language.lower() != language_code.lower( ) and languages['additional_languages']: # search for the right language in addional languages, # considering that the LimeSurvey uses upper case in the two-letter language code, like en-US and pt-BR. additional_languages_list = languages['additional_languages'].split( ' ') additional_languages_list_lower = [ item.lower() for item in additional_languages_list ] if language_code.lower() in additional_languages_list_lower: index = additional_languages_list_lower.index( language_code.lower()) language = additional_languages_list[index] survey_title = surveys.get_survey_title(lime_survey_id, language) if not isinstance(groups, dict): for group in groups: if 'id' in group and group['id']['language'] == language: question_list = surveys.list_questions(lime_survey_id, group['id']) question_list = sorted(question_list) for question in question_list: properties = surveys.get_question_properties( question, group['id']['language']) # cleaning the question field properties['question'] = re.sub( '{.*?}', '', re.sub('<.*?>', '', properties['question'])) properties['question'] = properties['question'].replace( ' ', '').strip() is_purely_formula = (properties['type'] == '*') and (properties['question'] == '') if not is_purely_formula and properties['question'] != '': if isinstance(properties['subquestions'], dict): question_properties.append({ 'gid': group['id']['gid'], 'group_name': group['group_name'], 'qid': question, 'question': properties['question'], 'question_id': properties['title'], 'answer_options': 'super_question', 'type': 'X', # properties['type'], 'other': False, 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) for key, value in sorted( properties['subquestions'].items()): question_properties.append({ 'gid': group['id']['gid'], 'group_name': group['group_name'], 'qid': question, 'question': value['question'], 'question_id': properties['title'] + '[' + value['title'] + ']', 'answer_options': properties['answeroptions'], 'type': properties['type'], 'other': False, 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) if properties['other'] == 'Y': question_properties.append({ 'gid': group['id']['gid'], 'group_name': group['group_name'], 'qid': question, 'question': _('Other'), 'question_id': properties['title'] + '[other]', 'answer_options': properties['answeroptions'], 'type': properties['type'], 'other': True, 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) else: question_properties.append({ 'gid': group['id']['gid'], 'group_name': group['group_name'], 'qid': question, 'question': properties['question'], 'question_id': properties['title'], 'answer_options': properties['answeroptions'], 'type': properties['type'], 'other': False, 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) else: question_properties.append({ 'gid': group['id']['gid'], 'group_name': group['group_name'], 'qid': question, 'question': _("Formula") + " (" + properties['title'] + ")", 'question_id': properties['title'], 'answer_options': properties['answeroptions'], 'type': properties['type'], 'other': False, 'attributes_lang': properties['attributes_lang'], 'hidden': False }) # Reading from Limesurvey and... responses_string = surveys.get_responses_by_token( lime_survey_id, token, language) # ... transforming to a list: # response_list[0] has the questions # response_list[1] has the answers responses_list = [] if isinstance(responses_string, bytes): reader = csv.reader(StringIO(responses_string.decode()), delimiter=',') for row in reader: responses_list.append(row) previous_question = '' last_super_question = '' last_super_question_index = [] # for question in question_properties: for response in responses_list[0]: questions = [] for question_prop in question_properties: question_id = question_prop['question_id'] if question_id in response: if response.split('[')[0] in question_id: questions.append(question_prop) for question in questions: if question and (question['question_id'] != previous_question): if not question['hidden']: if isinstance(question['answer_options'], str) and \ question['answer_options'] == "super_question": if question['question'] != '' and question[ 'question_id'] != last_super_question: groups_of_questions = add_questionnaire_response_to_group( groups_of_questions, question, '', None, no_response_flag=True) last_super_question = question[ 'question_id'] last_super_question_index = [ len(groups_of_questions) - 1, len(groups_of_questions[-1] ['questionnaire_responses']) - 1 ] else: previous_question = question['question_id'] answer = '' no_response_flag = False # type 'X' means "Text display" if not question['type'] == 'X': # type "1" means "Array dual scale" if question['type'] == '1': answer_list = [] if question[ 'question_id'] + "[1]" in responses_list[ 0]: index = responses_list[0].index( question['question_id'] + "[1]") answer_options = question[ 'answer_options'] answer = question[ 'attributes_lang'][ 'dualscale_headerA'] + ": " if responses_list[1][ index] in answer_options: answer_option = answer_options[ responses_list[1][index]] answer += answer_option[ 'answer'] else: # Sem resposta answer += _('No answer') no_response_flag = True answer_list.append(answer) if question[ 'question_id'] + "[2]" in responses_list[ 0]: index = responses_list[0].index( question['question_id'] + "[2]") answer_options = question[ 'answer_options'] answer = question[ 'attributes_lang'][ 'dualscale_headerB'] + ": " if responses_list[1][ index] in answer_options: answer_option = answer_options[ responses_list[1][index]] answer += answer_option[ 'answer'] else: # Sem resposta answer += _('No answer') no_response_flag = True answer_list.append(answer) groups_of_questions = add_questionnaire_response_to_group( groups_of_questions, question, answer_list, None, no_response_flag) else: link = '' if question[ 'question_id'] in responses_list[ 0]: index = responses_list[0].index( question['question_id']) answer_options = question[ 'answer_options'] if isinstance( answer_options, dict): # type "M" means "Multiple choice" if question['type'] == 'M': answer = responses_list[1][ index] if question['other']: if answer == '': no_response_flag = True else: if answer != 'Y': no_response_flag = True else: if responses_list[1][ index] in answer_options: answer_option = answer_options[ responses_list[1] [index]] answer = answer_option[ 'answer'] else: # Sem resposta answer = _('No answer') no_response_flag = True else: # type "D" means "Date/Time" if question['type'] == 'D': if responses_list[1][ index]: answer = datetime.datetime.strptime( responses_list[1] [index], '%Y-%m-%d %H:%M:%S' ) else: answer = '' no_response_flag = True else: answer = responses_list[1][ index] # type "M" means "Multiple choice" if question['type'] == 'M': if question['other']: if answer == '': no_response_flag = True else: if answer != 'Y': no_response_flag = True if question[ 'type'] == '|' and answer: link = settings.LIMESURVEY['URL_WEB'] + \ '/index.php/admin/responses/sa/browse/fieldname/' + \ str(lime_survey_id) + 'X' + \ str(question['gid']) + 'X' + \ str(question['qid']) + \ '/id/' + responses_list[1][0] + \ '/surveyid/' + str(lime_survey_id) + \ '/downloadindividualfile/' + \ json.loads(answer[1:-1])['name'] groups_of_questions = add_questionnaire_response_to_group( groups_of_questions, question, answer, link, no_response_flag) # checking if the super-question should be unmarked if last_super_question and not no_response_flag \ and question['question_id'].split('[')[0] == last_super_question: mark_off_super_question( groups_of_questions, last_super_question_index) else: messages.error( request, _("LimeSurvey did not find fill data for this questionnaire.")) surveys.release_session_key() return survey_title, groups_of_questions
def get_questionnaire_responses(language_code, lime_survey_id, token_id, request): questionnaire_responses = [] surveys = Questionnaires() token = surveys.get_participant_properties(lime_survey_id, token_id, "token") question_properties = [] groups = surveys.list_groups(lime_survey_id) survey_title = surveys.get_survey_title(lime_survey_id) if not isinstance(groups, dict): # defining language to be showed languages = surveys.get_survey_languages(lime_survey_id) # language to be showed can be the base language, or... language = languages['language'] # ...can be one of the additional languages if language.lower() != language_code.lower( ) and languages['additional_languages']: # search for the right language in addional languages, # considering that the LimeSurvey uses upper case in the two-letter language code, like en-US and pt-BR. additional_languages_list = languages[ 'additional_languages'].split(' ') additional_languages_list_lower = [ item.lower() for item in additional_languages_list ] if language_code.lower() in additional_languages_list_lower: index = additional_languages_list_lower.index( language_code.lower()) language = additional_languages_list[index] for group in groups: if 'id' in group and group['id']['language'] == language: question_list = surveys.list_questions(lime_survey_id, group['id']) question_list = sorted(question_list) for question in question_list: properties = surveys.get_question_properties( question, group['id']['language']) # cleaning the question field properties['question'] = re.sub( '{.*?}', '', re.sub('<.*?>', '', properties['question'])) properties['question'] = properties['question'].replace( ' ', '').strip() is_purely_formula = (properties['type'] == '*') and (properties['question'] == '') if not is_purely_formula and properties['question'] != '': if isinstance(properties['subquestions'], dict): question_properties.append({ 'question': properties['question'], 'question_id': properties['title'], 'answer_options': 'super_question', 'type': properties['type'], 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) for key, value in sorted( properties['subquestions'].items()): question_properties.append({ 'question': value['question'], 'question_id': properties['title'] + '[' + value['title'] + ']', 'answer_options': properties['answeroptions'], 'type': properties['type'], 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) else: question_properties.append({ 'question': properties['question'], 'question_id': properties['title'], 'answer_options': properties['answeroptions'], 'type': properties['type'], 'attributes_lang': properties['attributes_lang'], 'hidden': 'hidden' in properties['attributes'] and properties['attributes']['hidden'] == '1' }) # Reading from Limesurvey and... responses_string = surveys.get_responses_by_token( lime_survey_id, token, language) # ... transforming to a list: # response_list[0] has the questions # response_list[1] has the answers responses_list = [] if isinstance(responses_string, bytes): reader = csv.reader(StringIO(responses_string.decode()), delimiter=',') for row in reader: responses_list.append(row) for question in question_properties: if not question['hidden']: if isinstance( question, str ) and question['answer_options'] == "super_question": if question['question'] != '': questionnaire_responses.append({ 'question': question['question'], 'answer': '', 'type': question['type'] }) else: answer = '' if question['type'] == '1': answer_list = [] if question[ 'question_id'] + "[1]" in responses_list[ 0]: index = responses_list[0].index( question['question_id'] + "[1]") answer_options = question['answer_options'] # if 'dualscale_headerA' in question['attributes_lang']: answer = question['attributes_lang'][ 'dualscale_headerA'] + ": " if responses_list[1][index] in answer_options: answer_option = answer_options[ responses_list[1][index]] answer += answer_option['answer'] else: answer += 'Sem resposta' # else: # answer += 'Sem resposta' answer_list.append(answer) if question[ 'question_id'] + "[2]" in responses_list[ 0]: index = responses_list[0].index( question['question_id'] + "[2]") answer_options = question['answer_options'] # if 'dualscale_headerB' in question['attributes_lang']: answer = question['attributes_lang'][ 'dualscale_headerB'] + ": " if responses_list[1][index] in answer_options: answer_option = answer_options[ responses_list[1][index]] answer += answer_option['answer'] else: answer += 'Sem resposta' # else: # answer += 'Sem resposta' answer_list.append(answer) questionnaire_responses.append({ 'question': question['question'], 'answer': answer_list, 'type': question['type'] }) else: if question['question_id'] in responses_list[0]: index = responses_list[0].index( question['question_id']) answer_options = question['answer_options'] if isinstance(answer_options, dict): if responses_list[1][ index] in answer_options: answer_option = answer_options[ responses_list[1][index]] answer = answer_option['answer'] else: answer = 'Sem resposta' else: if question['type'] == 'D': if responses_list[1][index]: answer = datetime.datetime.strptime( responses_list[1][index], '%Y-%m-%d %H:%M:%S') else: answer = '' else: answer = responses_list[1][index] questionnaire_responses.append({ 'question': question['question'], 'answer': answer, 'type': question['type'] }) else: messages.error( request, _("LimeSurvey did not find fill data for this questionnaire.")) surveys.release_session_key() return survey_title, questionnaire_responses