from datetime import datetime, time, timedelta from django.utils import timezone from planner.models import UserSettings, WaterIntakeEntry from planner.timezones import timezone_for_user def hydration_context(user, now=None): zone = timezone_for_user(user) today = timezone.localtime(now or timezone.now(), zone).date() start = today - timedelta(days=today.weekday()) week_start = timezone.make_aware(datetime.combine(start, time.min), zone) week_end = timezone.make_aware(datetime.combine(start + timedelta(days=7), time.min), zone) goal = UserSettings.objects.get_or_create(user=user)[0].daily_water_goal_ml entries = WaterIntakeEntry.objects.filter(user=user, recorded_at__gte=week_start, recorded_at__lt=week_end) totals = {start + timedelta(days=i): 0 for i in range(7)} for entry in entries: totals[timezone.localtime(entry.recorded_at, zone).date()] += entry.amount_ml total = totals[today] last = entries.filter( recorded_at__gte=timezone.make_aware(datetime.combine(today, time.min), zone), recorded_at__lt=timezone.make_aware(datetime.combine(today + timedelta(days=1), time.min), zone), ).order_by('-recorded_at', '-pk').first() percent = round(total * 100 / goal) visual = min(100, percent) days = [] for day, amount in totals.items(): state = 'none' if amount == 0 else ('goal' if amount >= goal else 'partial') days.append({'date': day, 'label': day.strftime('%a')[0], 'total': amount, 'state': state, 'state_label': {'none': 'no water logged', 'partial': 'partial goal', 'goal': 'goal met'}[state], 'today': day == today}) return {'hydration_total': total, 'hydration_goal': goal, 'hydration_percent': percent, 'hydration_visual': visual, 'hydration_fill_y': 168 - round(visual * 1.22), 'hydration_fill_height': round(visual * 1.22), 'hydration_last': last, 'hydration_last_time': timezone.localtime(last.recorded_at, zone).strftime('%H:%M') if last else None, 'hydration_zone': zone, 'hydration_days': days, 'hydration_markers': [ {'y': 46, 'value': goal}, {'y': 77, 'value': round(goal * .75)}, {'y': 107, 'value': round(goal * .5)}, {'y': 138, 'value': round(goal * .25)}, ]}