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

WIP: Add context to Timer model #575 #576

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions core/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def set_initial_values(kwargs, form_type):

# Set start and end time based on Timer from `timer` kwarg.
timer_id = kwargs.get("timer", None)
timer = None
if timer_id:
timer = models.Timer.objects.get(id=timer_id)
kwargs["initial"].update(
Expand All @@ -61,6 +62,17 @@ def set_initial_values(kwargs, form_type):
last_feed_args["method"] = last_method
kwargs["initial"].update(last_feed_args)

if (
form_type == FeedingForm
and timer is not None
and timer.context is not None
and timer.context.get("timer_type") == "feeding"
):

for arg in ["method", "type"]:
if timer.context.get(arg) is not None:
kwargs["initial"][arg] = timer.context[arg]

# Remove custom kwargs so they do not interfere with `super` calls.
for key in ["child", "timer"]:
try:
Expand Down
20 changes: 20 additions & 0 deletions core/migrations/0025_timer_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 4.1.3 on 2022-11-20 13:49

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("core", "0024_alter_tag_slug"),
]

operations = [
migrations.AddField(
model_name="timer",
name="context",
field=models.JSONField(
blank=True, default=None, null=True, verbose_name="Context"
),
),
]
32 changes: 32 additions & 0 deletions core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,33 @@ def validate_time(time, field_name):
)


def validate_timer_context(context):
"""
Confirm that a Timer's context contains valid information.
:param context: A JSON store of context for the Timer
:return:
"""
if context is None:
return

valid_types = ["feeding"]

if context.get("timer_type") not in valid_types:
raise ValidationError(_("Not a valid timer type"), code="invalid_timer_type")

excludes = []
fields = Feeding._meta.get_fields()
feeding = Feeding()

for field in fields:
if context.get(field.name) is None:
excludes.append(field.name)
else:
setattr(feeding, field.name, context.get(field.name))

feeding.clean_fields(exclude=excludes)


class Tag(TagBase):
DARK_COLOR = "#101010"
LIGHT_COLOR = "#EFEFEF"
Expand Down Expand Up @@ -556,6 +583,10 @@ class Timer(models.Model):
verbose_name=_("User"),
)

context = models.JSONField(
default=None, blank=True, null=True, verbose_name=_("Context")
)

objects = models.Manager()

class Meta:
Expand Down Expand Up @@ -619,6 +650,7 @@ def clean(self):
if self.end:
validate_time(self.end, "end")
validate_duration(self)
validate_timer_context(self.context)


class TummyTime(models.Model):
Expand Down
12 changes: 12 additions & 0 deletions core/tests/tests_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,18 @@ def test_timer_stop_on_save(self):
self.assertFalse(self.timer.active)
self.assertEqual(self.localtime_string(self.timer.end), params["end"])

def test_timer_set_initial_from_context(self):
self.timer.context = {
"timer_type": "feeding",
"method": "bottle",
"type": "formula",
}
self.timer.stop()

page = self.c.get("/feedings/add/?timer={}".format(self.timer.id))
self.assertEqual(page.context["form"].initial["method"], "bottle")
self.assertEqual(page.context["form"].initial["type"], "formula")


class BMIFormsTestCase(FormsTestCaseBase):
@classmethod
Expand Down
39 changes: 39 additions & 0 deletions core/tests/tests_models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.core.management import call_command
from django.core.exceptions import ValidationError
from django.test import TestCase
from django.utils import timezone

Expand Down Expand Up @@ -326,6 +327,44 @@ def test_timer_duration(self):
timer.stop()
self.assertEqual(timer.duration.seconds, timezone.timedelta(minutes=30).seconds)

def test_timer_valid_context(self):
timer = models.Timer.objects.create(user=User.objects.first())
timer.context = dict(timer_type="feeding", method="bottle", type="formula")

timer.clean()
self.assertEqual(timer.context["timer_type"], "feeding")

# Don't need to specify method
timer.context = dict(timer_type="feeding", type="breast milk")
timer.clean()
self.assertEqual(timer.context["timer_type"], "feeding")

# Don't need to specify type or method
timer.context = dict(timer_type="feeding")
timer.clean()
self.assertEqual(timer.context["timer_type"], "feeding")

def test_timer_invalid_type(self):
timer = models.Timer.objects.create(user=User.objects.first())
timer.context = dict(timer_type="invalid", method="bottle", type="formula")

with self.assertRaises(ValidationError):
timer.clean()

def test_timer_invalid_feeding_method(self):
timer = models.Timer.objects.create(user=User.objects.first())
timer.context = dict(timer_type="feeding", method="bottleohno", type="formula")

with self.assertRaises(ValidationError):
timer.clean()

def test_timer_invalid_feeding_type(self):
timer = models.Timer.objects.create(user=User.objects.first())
timer.context = dict(timer_type="feeding", method="bottle", type="formulaohno")

with self.assertRaises(ValidationError):
timer.clean()


class TummyTimeTestCase(TestCase):
def setUp(self):
Expand Down