Skip to content

Commit

Permalink
feat: implement flat_answer_map (analog to ember-caluma)
Browse files Browse the repository at this point in the history
  • Loading branch information
StephanH90 committed Oct 19, 2023
1 parent 70e875c commit d96d33e
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
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}
]

0 comments on commit d96d33e

Please sign in to comment.