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

feat: implement flat_answer_map #2088

Merged
merged 1 commit into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
34 changes: 34 additions & 0 deletions caluma/caluma_form/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,40 @@ class Document(core_models.UUIDModel):
)
meta = models.JSONField(default=dict)

def flat_answer_map(self):
"""
Return a dictionary with the flattened answer map for this document.

The keys are the question IDs, and the values are either the answer value
or date for non-table questions, or a list of flattened answer maps for
table questions.

Example usage:
>>> doc = Document.objects.get(pk=1)
>>> flat_map = doc.flat_answer_map()
>>> print(flat_map)
{
"first-name": 'John',
"second-name": 'Doe',
"email-in-subform": '[email protected]',
"projects": [
{"title": 'Project A', "date": '2022-01-01'},
{"title": 'Project B', "date": '2022-02-01'},
{"title": 'Project C', "date": '2022-03-01'}
]
}
"""
answers = {}
for answer in self.answers.all():
if answer.question.type == Question.TYPE_TABLE:
answers[answer.question_id] = [
answer.flat_answer_map() for answer in answer.documents.all()
]
else:
answers[answer.question_id] = answer.value or answer.date

return answers

def set_family(self, root_doc):
"""Set the family to the given root_doc.

Expand Down
14 changes: 14 additions & 0 deletions caluma/caluma_form/tests/test_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -1714,3 +1714,17 @@ def test_selected_options(
)

assert returned_value == expected_values


def test_flat_answer_map(db, form_and_document):
(_form, document, _questions_dict, answers_dict) = form_and_document(
use_table=True, use_subform=True
)

flat_answer_map = document.flat_answer_map()

assert flat_answer_map["top_question"] == answers_dict["top_question"].value
assert flat_answer_map["sub_question"] == answers_dict["sub_question"].value
assert flat_answer_map["table"] == [
{"column": answers_dict["table"].documents.first().answers.first().value}
]
Loading