Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return previous survey results #466

Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions microsetta_private_api/api/_survey.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ def read_survey_template(account_id, source_id, survey_template_id,

with Transaction() as t:
survey_template_repo = SurveyTemplateRepo(t)

info = survey_template_repo.get_survey_template_link_info(
survey_template_id)
remote_surveys = set(survey_template_repo.remote_surveys())
Expand Down Expand Up @@ -242,6 +243,28 @@ def read_survey_template(account_id, source_id, survey_template_id,
if field.id in client_side_validation:
field.set(**client_side_validation[field.id])

results = survey_template_repo.get_survey_responses(account_id,
survey_template_id,
latest_only=True)

if results:
# get_survey_responses() returns a list of dicts whether
# latest_only is True or False. We only want the values and the
# percentage of questions answered for the _latest_ response.
info.percentage_completed = results[0]['percentage_completed']
charles-cowart marked this conversation as resolved.
Show resolved Hide resolved
results = results[0]['responses']
results = {str(v['survey_question_id']):
v['response'] for v in results}

# modify info with previous results before returning to client.
for group in info.survey_template_text.groups:
for field in group.fields:
previous_response = results[field.inputName]
if previous_response:
field.default = previous_response
else:
info.percentage_completed = '0.00%'

return jsonify(info), 200


Expand Down
3 changes: 1 addition & 2 deletions microsetta_private_api/api/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1768,8 +1768,7 @@ def test_edit_sample_locked(self):

# if sample date is greater than 30 days
now = datetime.datetime.now()
delta = relativedelta(month=now.month+2)
date = now+delta
date = now + datetime.timedelta(days=61)
post_resp = self.client.put(
'%s?%s' % (base_url, self.default_lang_querystring),
content_type='application/json',
Expand Down
84 changes: 84 additions & 0 deletions microsetta_private_api/repo/survey_template_repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,90 @@ def _get_group_localized_text(self, group_id, language_tag):
return None
return row[0]

def get_survey_responses(self, login_id, survey_template_id, latest_only=True):
# get the total number of questions in the survey.
# for most tables a.survey_id is known as 'survey_template_id'.
# (These are the values 1-7 and later 10-21). Aliasing here for
# clarity.
sql = f"""select a.survey_id as survey_template_id,
count(b.survey_question_id) from
ag.surveys a,
ag.group_questions b where
a.survey_group = b.survey_group and
survey_id = {survey_template_id} group by
charles-cowart marked this conversation as resolved.
Show resolved Hide resolved
survey_template_id"""

total_count = None

with self._transaction.cursor() as cur:
cur.execute(sql)
total_count = cur.fetchone()[1]

# adding indexes to these individual columns may improve performance.
charles-cowart marked this conversation as resolved.
Show resolved Hide resolved
# ag.survey_answers.survey_question_id
# ag.surveys.survey_id

sql = f"""select a.survey_id, a.survey_question_id, a.response,
charles-cowart marked this conversation as resolved.
Show resolved Hide resolved
b.display_index, c.source_id, c.creation_time
from ag.survey_answers as a, ag.group_questions b,
ag.ag_login_surveys c, ag.surveys d where c.ag_login_id =
'{login_id}' and d.survey_id = {survey_template_id} and
a.survey_question_id = b.survey_question_id and c.survey_id
= a.survey_id and d.survey_group = b.survey_group union
select a.survey_id, a.survey_question_id, a.response,
b.display_index, c.source_id, c.creation_time
from ag.survey_answers_other as a, ag.group_questions b,
ag.ag_login_surveys c, ag.surveys d where c.ag_login_id =
'{login_id}' and d.survey_id = {survey_template_id} and
a.survey_question_id = b.survey_question_id and c.survey_id
= a.survey_id and d.survey_group = b.survey_group order by
creation_time desc, display_index asc"""

with self._transaction.cursor() as cur:
# dict_cursor() isn't returning rows as dicts.
# another option is to return a tuple of lists, rather than a
# list of dicts.
cur.execute(sql)
rows = cur.fetchall()

charles-cowart marked this conversation as resolved.
Show resolved Hide resolved
results = {}
count = 0
for (survey_id, question_id, response, display_idx, source_id, timestamp) in rows:
if survey_id not in results:
count += 1
if latest_only and count > 1:
# if the client is requesting only the responses of
# the last survey, then don't process the rest of
# them.
break

# add the new entry to results
results[survey_id] = {'survey_id': survey_id,
'source_id': source_id,
'timestamp': str(timestamp),
'responses': []}

# new survey_id or not, append the response to the list of
# responses for that survey_id.
r = {'survey_question_id': question_id, 'response': response,
'display_index': int(display_idx)}

results[survey_id]['responses'].append(r)

# turn the nested dict into a list of dicts sorted by insertion
# order. (Python 3.6+)
results = [results[x] for x in results]

# calculate the percentage of each survey completed against the
# _current_ total number of questions in the survey.
for result in results:
pc = len(result['responses'])/total_count
pc = "{0:.2f}%".format(pc * 100)

result['percentage_completed'] = pc

return results

def _get_question_valid_responses(self, survey_question_id, language_tag):
tag_to_col = {
localization.EN_US: "survey_response.american",
Expand Down
57 changes: 57 additions & 0 deletions microsetta_private_api/repo/tests/test_survey_template_repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,3 +397,60 @@ def test_get_vioscreen_sample_to_user(self):
('000023245', '52abc2ea83c08b96')]
for sample, user in tests:
self.assertEqual(obs.get(sample), user)

def test_get_survey_results(self):
with Transaction() as t:
template_repo = SurveyTemplateRepo(t)

login_id = 'd8592c74-7da1-2135-e040-8a80115d6401'

# get only the latest responses: implicit latest_only=True
obs = template_repo.get_survey_responses(login_id, 1)

# erase the timestamp as it's dependent on db init.
# source_id is also dynamic.
for response in obs:
response['timestamp'] = ''
response['source_id'] = ''

# the expected latest response
exp = [{
"survey_id": "4b1af551332dc84e",
"source_id": "",
"timestamp": "",
"responses": [
{
"survey_question_id": 52,
"response": "Unspecified",
"display_index": -2
},
{
"survey_question_id": 97,
"response": "Unspecified",
"display_index": -1
}
],
"percentage_completed": "1.44%"
}
]

self.assertEqual(obs, exp)

# repeat the test, except return all responses.
charles-cowart marked this conversation as resolved.
Show resolved Hide resolved
obs = template_repo.get_survey_responses(login_id, 1,
latest_only=False)

for response in obs:
response['timestamp'] = ''
response['source_id'] = ''

# results should not be equal. Additional surveys from other
# tests will have been taken.
self.assertNotEqual(obs, exp)

# non-existent login_id should return empty list.
login_id = 'abc92c74-7da1-2135-e040-8a80115d6401'

obs = template_repo.get_survey_responses(login_id, 1)

self.assertEqual(obs, [])