48 lines
2.1 KiB
Python
48 lines
2.1 KiB
Python
"""One revisable daily stress score alongside freeform journal check-ins."""
|
|
from datetime import datetime
|
|
from django.contrib.auth import get_user_model
|
|
from django.core.exceptions import ValidationError
|
|
from django.db import transaction
|
|
from django.utils import timezone
|
|
|
|
from planner.timezones import localdate_for_user, timezone_for_user
|
|
from .models import StressEntry
|
|
|
|
|
|
def daily_widget_context(user):
|
|
day = localdate_for_user(user)
|
|
entry = StressEntry.objects.filter(user=user, daily_date=day).first()
|
|
revisions = []
|
|
if entry:
|
|
for revision in entry.revisions[-5:]:
|
|
revisions.append({'score': revision['score'],
|
|
'time': timezone.localtime(datetime.fromisoformat(revision['time']),
|
|
timezone_for_user(user))})
|
|
return {'stress_daily_date': day,
|
|
'stress_daily_entry': entry, 'stress_daily_revisions': revisions}
|
|
|
|
|
|
def save_daily_entry(user, *, score, timing='anytime', note='', stressor=''):
|
|
if isinstance(score, bool) or not isinstance(score, int) or not 0 <= score <= 10:
|
|
raise ValidationError('Choose a stress score from 0 to 10.')
|
|
if timing not in StressEntry.Timing.values:
|
|
raise ValidationError('Choose when the stress was felt.')
|
|
if not isinstance(note, str) or len(note) > 200:
|
|
raise ValidationError('Keep the note under 200 characters.')
|
|
if not isinstance(stressor, str) or len(stressor.strip()) > 40:
|
|
raise ValidationError('Keep the stressor under 40 characters.')
|
|
day = localdate_for_user(user)
|
|
moment = timezone.now()
|
|
with transaction.atomic():
|
|
get_user_model().objects.select_for_update().get(pk=user.pk)
|
|
entry, _ = StressEntry.objects.select_for_update().get_or_create(
|
|
user=user, daily_date=day,
|
|
defaults={'score': score, 'recorded_at': moment})
|
|
entry.record_score(score, at=moment)
|
|
entry.timing = timing
|
|
entry.note = note.strip()
|
|
entry.tags = [stressor.strip()] if stressor.strip() else []
|
|
entry.full_clean()
|
|
entry.save()
|
|
return entry
|