added gitea activity for fun

This commit is contained in:
Joren de Graaf
2026-10-03 17:11:31 +02:00
parent 184e9d18f3
commit c0eda95f26
78 changed files with 11461 additions and 8 deletions
+28
View File
@@ -145,6 +145,34 @@ class UserSettingsForm(forms.ModelForm):
}
class NtfySettingsForm(forms.ModelForm):
class Meta:
model = UserSettings
fields = ('ntfy_url', 'ntfy_enabled')
widgets = {'ntfy_url': forms.URLInput(attrs={'id': 'ntfy-url', 'placeholder': 'https://ntfy.example.com/my-topic'})}
def clean_ntfy_url(self):
return self.cleaned_data['ntfy_url'].strip()
def clean(self):
data = super().clean()
if data.get('ntfy_enabled') and not data.get('ntfy_url'):
self.add_error('ntfy_url', 'Enter a topic URL before enabling notifications.')
return data
class HydrationGoalForm(forms.ModelForm):
class Meta:
model = UserSettings
fields = ('daily_water_goal_ml',)
labels = {'daily_water_goal_ml': 'Daily water goal (ml)'}
widgets = {'daily_water_goal_ml': forms.NumberInput(attrs={'min': 250, 'max': 10000, 'step': 1})}
class WaterIntakeForm(forms.Form):
amount_ml = forms.IntegerField(min_value=1, max_value=3000)
class SickDaySettingsForm(forms.ModelForm):
class Meta:
model = SickDaySettings
@@ -0,0 +1,11 @@
from django.core.management.base import BaseCommand
from planner.services.fasting_notifications import notify_fasting_phase_changes
class Command(BaseCommand):
help = 'Send ntfy notifications for fasting and eating phase changes.'
def handle(self, *args, **options):
delivered = notify_fasting_phase_changes()
self.stdout.write(f'Delivered {delivered} fasting phase notification(s).')
@@ -0,0 +1,36 @@
# Generated by Django 6.1.1 on 2026-10-02 19:50
import django.core.validators
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('planner', '0015_bowelhealthcheckin_toothbrushing'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddField(
model_name='usersettings',
name='daily_water_goal_ml',
field=models.PositiveIntegerField(default=2000, validators=[django.core.validators.MinValueValidator(250), django.core.validators.MaxValueValidator(10000)]),
),
migrations.CreateModel(
name='WaterIntakeEntry',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount_ml', models.PositiveIntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(3000)])),
('recorded_at', models.DateTimeField(db_index=True, default=django.utils.timezone.now)),
('created_at', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='water_entries', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('-recorded_at', '-pk'),
},
),
]
@@ -0,0 +1,11 @@
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('planner', '0016_usersettings_daily_water_goal_ml_waterintakeentry')]
operations = [
migrations.AddField(model_name='usersettings', name='ntfy_url', field=models.URLField(blank=True)),
migrations.AddField(model_name='usersettings', name='ntfy_enabled', field=models.BooleanField(default=False)),
migrations.AddField(model_name='usersettings', name='ntfy_last_tested_at', field=models.DateTimeField(blank=True, null=True)),
]
@@ -0,0 +1,12 @@
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('planner', '0017_usersettings_ntfy')]
operations = [
migrations.AddField(
model_name='fastingsettings', name='last_phase_notification_at',
field=models.DateTimeField(blank=True, null=True),
),
]
+18
View File
@@ -5,6 +5,7 @@ from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.urls import reverse
from django.utils import timezone
class Task(models.Model):
@@ -116,6 +117,12 @@ class UserSettings(models.Model):
)
onboarding_enabled = models.BooleanField(default=True)
onboarding_step = models.PositiveSmallIntegerField(default=0)
daily_water_goal_ml = models.PositiveIntegerField(
default=2000, validators=[MinValueValidator(250), MaxValueValidator(10000)],
)
ntfy_url = models.URLField(blank=True)
ntfy_enabled = models.BooleanField(default=False)
ntfy_last_tested_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@@ -341,6 +348,7 @@ class FastingSettings(models.Model):
validators=[MinValueValidator(1), MaxValueValidator((24 * 60) - 1)],
)
tracking_started_at = models.DateTimeField(blank=True, null=True)
last_phase_notification_at = models.DateTimeField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@@ -366,6 +374,16 @@ class FastingPause(models.Model):
return f'Fasting pause for {self.user} at {self.paused_at}'
class WaterIntakeEntry(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='water_entries')
amount_ml = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(3000)])
recorded_at = models.DateTimeField(default=timezone.now, db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-recorded_at', '-pk')
class FastingPeriod(models.Model):
class Status(models.TextChoices):
COMPLETED = 'completed', 'Completed'
+8
View File
@@ -113,6 +113,7 @@ def configure_fasting(
'fasting_start_time': fasting_start_time,
'fasting_duration_minutes': fasting_duration_minutes,
'tracking_started_at': now if enabled else None,
'last_phase_notification_at': now,
},
)
if created:
@@ -121,9 +122,16 @@ def configure_fasting(
return settings
was_enabled = settings.enabled
schedule_changed = (
settings.fasting_start_time != fasting_start_time
or settings.fasting_duration_minutes != fasting_duration_minutes
or was_enabled != enabled
)
settings.fasting_start_time = fasting_start_time
settings.fasting_duration_minutes = fasting_duration_minutes
settings.enabled = enabled
if schedule_changed:
settings.last_phase_notification_at = now
if enabled and settings.tracking_started_at is None:
settings.tracking_started_at = now
settings.save()
@@ -0,0 +1,43 @@
"""Deliver the latest fasting phase transition once per tracked schedule."""
import logging
from django.db import transaction
from django.utils import timezone
from planner.models import FastingSettings
from planner.services.fasting import current_fasting_phase
from planner.services.notifications import NotificationError, send_notification
logger = logging.getLogger(__name__)
def notify_fasting_phase_changes(now=None):
now = now or timezone.now()
delivered = 0
for settings_id in FastingSettings.objects.filter(enabled=True).values_list('pk', flat=True):
with transaction.atomic():
settings = FastingSettings.objects.select_for_update().select_related('user').get(pk=settings_id)
if not settings.enabled:
continue
phase = current_fasting_phase(settings, now)
boundary = phase.cycle_start
cursor = settings.last_phase_notification_at
if cursor is None:
# Existing configurations start at the current phase without a catch-up alert.
settings.last_phase_notification_at = now
settings.save(update_fields=['last_phase_notification_at'])
continue
if boundary <= cursor or boundary > now:
continue
title = 'Fasting started' if phase.is_fasting else 'Eating window started'
message = 'Your fasting window has started.' if phase.is_fasting else 'Your eating window is open.'
try:
sent = send_notification(settings.user, title, message)
except NotificationError:
logger.warning('Could not deliver fasting phase notification for user %s.', settings.user_id)
continue
settings.last_phase_notification_at = boundary
settings.save(update_fields=['last_phase_notification_at'])
delivered += int(sent)
return delivered
+87
View File
@@ -0,0 +1,87 @@
"""Fetch and shape a Gitea user's contribution heatmap for the dashboard."""
from datetime import datetime, timedelta, timezone as utc_timezone
import json
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen
from django.conf import settings
from django.core.cache import cache
from django.utils import timezone
HEATMAP_CACHE_SECONDS = 15 * 60
def fetch_heatmap():
username = settings.GITEA_USERNAME
if not username:
return None
key = f'gitea-heatmap:{settings.GITEA_BASE_URL}:{username}'
cached = cache.get(key)
if cached is not None:
return cached
url = f'{settings.GITEA_BASE_URL}/api/v1/users/{quote(username, safe="")}/heatmap'
headers = {'Accept': 'application/json'}
if settings.GITEA_TOKEN:
headers['Authorization'] = f'token {settings.GITEA_TOKEN}'
try:
with urlopen(Request(url, headers=headers), timeout=4) as response:
data = json.load(response)
except (HTTPError, URLError, TimeoutError, OSError, ValueError):
return None
if not isinstance(data, list):
return None
cache.set(key, data, HEATMAP_CACHE_SECONDS)
return data
def activity_level(count):
if count <= 0:
return 0
if count == 1:
return 1
if count <= 3:
return 2
if count <= 6:
return 3
return 4
def activity_context(today=None):
"""Return 53 Sunday-first weeks ending in the current week."""
today = today or timezone.localdate()
data = fetch_heatmap()
if data is None:
return {'activity_unavailable': True}
counts = {}
for item in data:
try:
day = datetime.fromtimestamp(item['timestamp'], utc_timezone.utc).date()
count = max(0, int(item['contributions']))
except (KeyError, TypeError, ValueError, OverflowError, OSError):
continue
counts[day] = count
first = today - timedelta(days=364)
first -= timedelta(days=(first.weekday() + 1) % 7)
weeks = []
total = 0
for week_number in range(53):
week_start = first + timedelta(days=week_number * 7)
week = []
for weekday in range(7):
day = week_start + timedelta(days=weekday)
count = counts.get(day, 0) if day <= today else 0
if day <= today and day >= today - timedelta(days=364):
total += count
week.append({
'date': day, 'count': count, 'level': activity_level(count),
'future': day > today,
})
month = week_start.strftime('%b') if week_number == 0 or week_start.month != (week_start - timedelta(days=7)).month else ''
weeks.append({'days': week, 'month': month})
return {
'activity_weeks': weeks,
'activity_total': total, 'activity_username': settings.GITEA_USERNAME,
'activity_profile_url': f'{settings.GITEA_BASE_URL}/{quote(settings.GITEA_USERNAME, safe="")}',
}
+41
View File
@@ -0,0 +1,41 @@
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)},
]}
+37
View File
@@ -0,0 +1,37 @@
import socket
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from planner.models import UserSettings
class NotificationError(Exception):
"""A delivery error safe to display without exposing the topic URL."""
def send_ntfy_notification(url, title, message, timeout=10):
request = Request(
url,
data=message.encode('utf-8'),
headers={'Content-Type': 'text/plain; charset=utf-8', 'Title': title},
method='POST',
)
try:
with urlopen(request, timeout=timeout) as response:
status = response.getcode()
except HTTPError as error:
raise NotificationError(f'ntfy server responded with HTTP {error.code}.') from error
except (TimeoutError, socket.timeout):
raise NotificationError('Connection to the ntfy server timed out.') from None
except (URLError, OSError):
raise NotificationError('Could not connect to the ntfy server.') from None
if not 200 <= status < 300:
raise NotificationError(f'ntfy server responded with HTTP {status}.')
def send_notification(user, title, message):
preferences = UserSettings.objects.filter(user=user).first()
if not preferences or not preferences.ntfy_enabled or not preferences.ntfy_url:
return False
send_ntfy_notification(preferences.ntfy_url, title, message)
return True
+8 -2
View File
@@ -11,7 +11,13 @@
</div>
</section>
<div class="health-layout">
{% include 'planner/partials/neck_headache_checkin.html' %}
{% include 'planner/partials/bowel_health_checkin.html' %}
<div class="health-layout__main">
{% include 'planner/partials/neck_headache_checkin.html' %}
{% include 'planner/partials/bowel_health_checkin.html' %}
</div>
<aside class="health-layout__sidebar" aria-label="Health routines">
{% include 'planner/partials/fasting_widget.html' %}
{% include 'planner/partials/hydration_widget.html' %}
</aside>
</div>
{% endblock %}
@@ -0,0 +1,23 @@
<section class="gitea-activity" id="gitea-activity" aria-labelledby="gitea-activity-heading">
<div class="gitea-activity__header">
<div><p class="eyebrow">Code garden</p><h2 id="gitea-activity-heading">Gitea activity</h2></div>
{% if activity_profile_url %}<a class="text-link" href="{{ activity_profile_url }}" target="_blank" rel="noopener noreferrer">View profile<span class="visually-hidden"> on Gitea</span></a>{% endif %}
</div>
{% if activity_unavailable %}
<p class="gitea-activity__message">Activity is unavailable right now.</p>
{% else %}
<p class="gitea-activity__summary"><strong>{{ activity_total }}</strong> contributions in the last year</p>
<div class="gitea-activity__scroller">
<div class="gitea-activity__chart" role="img" aria-label="Gitea contribution calendar: {{ activity_total }} contributions in the last year">
<div class="gitea-activity__day-labels" aria-hidden="true"><span></span><span>Mon</span><span></span><span>Wed</span><span></span><span>Fri</span><span></span></div>
{% for week in activity_weeks %}
<div class="gitea-activity__week" aria-hidden="true">
<span class="gitea-activity__month">{{ week.month }}</span>
{% for day in week.days %}<time class="gitea-activity__cell gitea-activity__cell--{{ day.level }}{% if day.future %} gitea-activity__cell--future{% endif %}" datetime="{{ day.date|date:'Y-m-d' }}" title="{{ day.date|date:'j M Y' }}: {{ day.count }} contribution{{ day.count|pluralize }}"></time>{% endfor %}
</div>
{% endfor %}
</div>
</div>
<div class="gitea-activity__legend" aria-hidden="true"><span>Less</span>{% for level in '01234' %}<i class="gitea-activity__cell gitea-activity__cell--{{ level }}"></i>{% endfor %}<span>More</span></div>
{% endif %}
</section>
@@ -0,0 +1,9 @@
<svg class="hydration-bottle" viewBox="0 0 112 184" width="112" height="184" aria-hidden="true" focusable="false">
<defs><clipPath id="hydration-bottle-clip"><path d="M35 42 Q30 47 30 58 V151 Q30 168 47 168 H77 Q94 168 94 151 V58 Q94 47 89 42 Z"/></clipPath></defs>
<path d="M46 16 Q46 9 53 9 H71 Q78 9 78 16 V32 H46 Z" fill="none" stroke="var(--bottle-stroke)" stroke-width="2"/>
<rect x="44" y="27" width="36" height="12" rx="3" fill="var(--bottle-cap)" stroke="var(--bottle-stroke)" stroke-width="2"/>
<path d="M35 42 Q30 47 30 58 V151 Q30 168 47 168 H77 Q94 168 94 151 V58 Q94 47 89 42 Z" fill="var(--bottle-shell)" stroke="var(--bottle-stroke)" stroke-width="2"/>
<g clip-path="url(#hydration-bottle-clip)" class="hydration-bottle__water"><rect x="30" y="{{ hydration_fill_y }}" width="64" height="{{ hydration_fill_height }}" fill="var(--bottle-fill)" opacity=".85"/><ellipse cx="62" cy="{{ hydration_fill_y }}" rx="33" ry="3" fill="var(--bottle-fill)" opacity=".85"/></g>
<path d="M35 42 Q30 47 30 58 V151 Q30 168 47 168 H77 Q94 168 94 151 V58 Q94 47 89 42 Z" fill="none" stroke="var(--bottle-stroke)" stroke-width="2"/>
{% for marker in hydration_markers %}<path d="M22 {{ marker.y }} h6" stroke="var(--bottle-stroke)" stroke-width="1.5"/><text x="20" y="{{ marker.y|add:3 }}" text-anchor="end" fill="var(--bottle-stroke)" font-size="8">{{ marker.value }}</text>{% endfor %}
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,19 @@
<article id="hydration-widget" class="hydration-widget" aria-labelledby="hydration-heading" aria-live="polite">
<p class="eyebrow">Daily hydration</p>
<h2 id="hydration-heading">Water</h2>
<div class="hydration-widget__main">
<div class="hydration-widget__stats">
<p class="hydration-widget__total">{{ hydration_total|floatformat:0 }} <span>/ {{ hydration_goal }} ml</span></p>
<p>{{ hydration_percent }}% of daily goal</p>
<div class="hydration-widget__track" role="progressbar" aria-label="Daily water goal" aria-valuenow="{{ hydration_visual }}" aria-valuemin="0" aria-valuemax="100"><span style="width:{{ hydration_visual }}%"></span></div>
</div>
{% include 'planner/partials/hydration_bottle.html' %}
</div>
<div class="hydration-widget__actions">
<form method="post" action="{% url 'planner:hydration-add' %}" hx-post="{% url 'planner:hydration-add' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<button type="submit" name="amount_ml" value="250">+250 ml</button><button type="submit" name="amount_ml" value="500">+500 ml</button></form>
<details class="hydration-widget__other"><summary>Other</summary><form method="post" action="{% url 'planner:hydration-add' %}" hx-post="{% url 'planner:hydration-add' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<label for="hydration-amount">Amount (ml)</label><input id="hydration-amount" name="amount_ml" type="number" min="1" max="3000" step="1" required inputmode="numeric"><button type="submit">Add</button></form></details>
</div>
{% if hydration_error %}<p class="hydration-widget__error" role="alert">Enter a whole amount from 1 to 3000 ml.</p>{% endif %}
<div class="hydration-widget__info">{% if hydration_last %}<span>Last: {{ hydration_last.amount_ml }} ml at {{ hydration_last_time }}</span><form method="post" action="{% url 'planner:hydration-undo' %}" hx-post="{% url 'planner:hydration-undo' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<button type="submit">Undo last</button></form>{% else %}<span>No water logged today</span>{% endif %}</div>
<div class="hydration-widget__week"><p>This week</p><div class="hydration-widget__days">{% for day in hydration_days %}<span class="hydration-widget__day hydration-widget__day--{{ day.state }}{% if day.today %} hydration-widget__day--today{% endif %}" title="{{ day.date|date:'l' }}: {{ day.total }} ml, {{ day.state_label }}" aria-label="{{ day.date|date:'l' }}: {{ day.total }} ml, {{ day.state_label }}">{{ day.label }}</span>{% endfor %}</div></div>
</article>
@@ -0,0 +1 @@
{% if success %}<p class="ntfy-result ntfy-result--success">Test notification sent successfully.</p>{% else %}<p class="ntfy-result ntfy-result--error">Could not send the test notification: {{ error }}</p>{% endif %}
@@ -41,11 +41,17 @@
</section>
{% include 'planner/partials/workout_section.html' %}
{% if gitea_activity_enabled %}
<div id="gitea-activity" hx-get="{% url 'planner:gitea-activity' %}" hx-trigger="load" hx-swap="outerHTML" aria-live="polite">
<section class="gitea-activity" aria-label="Gitea activity"><p>Loading Gitea activity…</p></section>
</div>
{% endif %}
</div>
{% if user.is_authenticated %}
<aside class="homepage-sidebar" aria-label="Personal routines">
<div class="desktop-weather-slot">{% include 'planner/partials/weather_widget.html' %}</div>
{% include 'planner/partials/tooth_brushing_widget.html' %}
{% include 'planner/partials/hydration_widget.html' %}
{% include 'planner/partials/fasting_widget.html' %}
</aside>
{% endif %}
@@ -7,6 +7,18 @@
<section class="settings-card"><h2>First-run help</h2><p>{% if onboarding_enabled %}The guided tour is ready to continue on your dashboard.{% else %}Help is off. You can run the tour again whenever you want.{% endif %}</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="onboarding"><button class="button" type="submit" name="action" value="restart">Run feature tour</button><button class="text-link" type="submit" name="action" value="disable">Turn help off</button></form></section>
<section class="settings-card"><h2>Location &amp; weather</h2><p>Location is optional and private. It is used only to retrieve your forecast.</p><form method="post" data-geolocation-form>{% csrf_token %}<input type="hidden" name="section" value="location">{% for field in profile_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button button--secondary" type="button" data-use-location>Use my current location</button><span data-location-status role="status"></span><button class="button" type="submit">Save location</button></form></section>
<section class="settings-card"><h2>Sick Day Mode</h2><p>Temporarily defer routine work while you recover.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="sick-day">{% for field in sick_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save Sick Day settings</button></form></section>
<section class="settings-card"><h2>Hydration</h2><p>Set your daily water goal.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="hydration">{% for field in hydration_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save water goal</button></form></section>
<section class="settings-card" aria-labelledby="ntfy-title">
<h2 id="ntfy-title">Notifications / ntfy</h2>
<p>Enter your private topic URL, test it, then enable notifications.</p>
<form method="post" data-ntfy-form>{% csrf_token %}<input type="hidden" name="section" value="ntfy">
<div class="form-field">{{ ntfy_form.ntfy_url.label_tag }}{{ ntfy_form.ntfy_url }}{{ ntfy_form.ntfy_url.errors }}</div>
<div class="ntfy-check">{{ ntfy_form.ntfy_enabled }}<label for="{{ ntfy_form.ntfy_enabled.id_for_label }}">Enable ntfy notifications</label></div>
<button class="button button--secondary" type="button" hx-post="{% url 'planner:ntfy-test' %}" hx-include="closest form" hx-target="#ntfy-test-result" hx-swap="innerHTML">Test notification</button>
<div id="ntfy-test-result" role="status" aria-live="polite"></div>
<button class="button" type="submit">Save notification settings</button>
</form>
</section>
<section class="settings-card"><h2>Fasting</h2><form method="post">{% csrf_token %}<input type="hidden" name="section" value="fasting">{% for field in fasting_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save fasting settings</button></form></section>
</section>
{% endblock %}
@@ -0,0 +1,57 @@
from datetime import datetime, time
from unittest.mock import patch
from zoneinfo import ZoneInfo
from django.contrib.auth import get_user_model
from django.test import TestCase
from .models import FastingSettings
from .services.fasting import configure_fasting
from .services.fasting_notifications import notify_fasting_phase_changes
from .services.notifications import NotificationError
class FastingNotificationTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='phase-user')
self.at = lambda hour, minute=0: datetime(2026, 10, 3, hour, minute, tzinfo=ZoneInfo('Europe/Amsterdam'))
configure_fasting(
self.user, enabled=True, fasting_start_time=time(20),
fasting_duration_minutes=16 * 60, now=self.at(13),
)
@patch('planner.services.fasting_notifications.send_notification', return_value=True)
def test_each_phase_is_sent_once(self, sender):
self.assertEqual(notify_fasting_phase_changes(self.at(19, 59)), 0)
self.assertEqual(notify_fasting_phase_changes(self.at(20)), 1)
self.assertEqual(notify_fasting_phase_changes(self.at(20, 1)), 0)
self.assertEqual(notify_fasting_phase_changes(datetime(2026, 10, 4, 12, tzinfo=ZoneInfo('Europe/Amsterdam'))), 1)
self.assertEqual(sender.call_count, 2)
self.assertEqual(sender.call_args.args[1], 'Eating window started')
@patch('planner.services.fasting_notifications.send_notification', side_effect=[NotificationError('failed'), True])
def test_delivery_failure_is_retried(self, sender):
self.assertEqual(notify_fasting_phase_changes(self.at(20)), 0)
self.assertEqual(notify_fasting_phase_changes(self.at(20, 1)), 1)
self.assertEqual(sender.call_count, 2)
@patch('planner.services.fasting_notifications.send_notification', return_value=True)
def test_paused_tracking_and_schedule_changes_do_not_send_old_transition(self, sender):
configure_fasting(
self.user, enabled=False, fasting_start_time=time(20),
fasting_duration_minutes=16 * 60, now=self.at(19),
)
self.assertEqual(notify_fasting_phase_changes(self.at(20)), 0)
configure_fasting(
self.user, enabled=True, fasting_start_time=time(20),
fasting_duration_minutes=16 * 60, now=self.at(21),
)
self.assertEqual(notify_fasting_phase_changes(self.at(21, 1)), 0)
sender.assert_not_called()
@patch('planner.services.fasting_notifications.send_notification', return_value=False)
def test_disabled_ntfy_does_not_queue_old_phase_for_later(self, sender):
self.assertEqual(notify_fasting_phase_changes(self.at(20)), 0)
self.assertEqual(notify_fasting_phase_changes(self.at(20, 1)), 0)
self.assertEqual(sender.call_count, 1)
self.assertEqual(FastingSettings.objects.get(user=self.user).last_phase_notification_at, self.at(20))
+60
View File
@@ -0,0 +1,60 @@
from datetime import date, datetime, timezone
from io import BytesIO
import json
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.test import TestCase, override_settings
from django.urls import reverse
from .services.gitea_activity import activity_context, fetch_heatmap
@override_settings(GITEA_BASE_URL='https://git.example.com', GITEA_USERNAME='coder', GITEA_TOKEN='private-token')
class GiteaActivityTests(TestCase):
def setUp(self):
cache.clear()
@patch('planner.services.gitea_activity.urlopen')
def test_fetch_uses_server_side_token_and_cache(self, open_url):
timestamp = int(datetime(2026, 10, 3, tzinfo=timezone.utc).timestamp())
open_url.return_value.__enter__.return_value = BytesIO(json.dumps([
{'timestamp': timestamp, 'contributions': 7},
]).encode())
context = activity_context(date(2026, 10, 3))
self.assertEqual(context['activity_total'], 7)
self.assertEqual(context['activity_weeks'][-1]['days'][-1]['level'], 4)
request = open_url.call_args.args[0]
self.assertEqual(request.get_header('Authorization'), 'token private-token')
self.assertEqual(request.full_url, 'https://git.example.com/api/v1/users/coder/heatmap')
fetch_heatmap()
self.assertEqual(open_url.call_count, 1)
@patch('planner.services.gitea_activity.urlopen', side_effect=OSError('offline'))
def test_api_failure_is_a_widget_message(self, open_url):
self.assertTrue(activity_context(date(2026, 10, 3))['activity_unavailable'])
@patch('planner.services.gitea_activity.urlopen')
def test_widget_renders_contribution_cells(self, open_url):
timestamp = int(datetime(2026, 10, 3, tzinfo=timezone.utc).timestamp())
open_url.return_value.__enter__.return_value = BytesIO(json.dumps([
{'timestamp': timestamp, 'contributions': 7},
]).encode())
user = get_user_model().objects.create_user(username='chart-user')
self.client.force_login(user)
response = self.client.get(reverse('planner:gitea-activity'))
self.assertContains(response, '7</strong> contributions')
self.assertContains(response, '2026-10-03')
self.assertContains(response, 'gitea-activity__cell--4')
@patch('planner.views.activity_context', return_value={'activity_unavailable': True})
def test_widget_requires_login_and_is_below_workout(self, context):
url = reverse('planner:gitea-activity')
self.assertEqual(self.client.get(url).status_code, 302)
user = get_user_model().objects.create_user(username='dashboard-user')
self.client.force_login(user)
response = self.client.get(reverse('planner:task-list'))
html = response.content.decode()
self.assertLess(html.index('id="workout-section"'), html.index('id="gitea-activity"'))
self.assertContains(self.client.get(url), 'Activity is unavailable right now.')
+49
View File
@@ -0,0 +1,49 @@
from unittest.mock import Mock, patch
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from .models import UserSettings
from .services.notifications import NotificationError, send_notification
class NtfySettingsTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='ntfy-user', password='test-password')
self.client.force_login(self.user)
self.settings_url = reverse('planner:user-settings')
self.test_url = reverse('planner:ntfy-test')
self.topic = 'https://ntfy.example.com/private-topic'
def save(self, url=None, enabled=True):
return self.client.post(self.settings_url, {
'section': 'ntfy', 'ntfy_url': self.topic if url is None else url,
'ntfy_enabled': 'on' if enabled else '',
})
def test_enable_requires_successful_test(self):
response = self.save()
self.assertContains(response, 'Test this URL successfully')
self.assertFalse(UserSettings.objects.get(user=self.user).ntfy_enabled)
@patch('planner.views.send_ntfy_notification')
def test_successful_test_allows_enable_and_changed_url_requires_retest(self, sender):
self.assertEqual(self.client.post(self.test_url, {'ntfy_url': 'invalid'}).status_code, 400)
self.assertEqual(self.client.post(self.test_url, {'ntfy_url': self.topic}).status_code, 200)
sender.assert_called_once()
self.assertEqual(self.save().status_code, 302)
preferences = UserSettings.objects.get(user=self.user)
self.assertTrue(preferences.ntfy_enabled)
self.assertIsNotNone(preferences.ntfy_last_tested_at)
self.assertContains(self.save(url='https://ntfy.example.com/other'), 'Test this URL successfully')
@patch('planner.views.send_ntfy_notification', side_effect=NotificationError('Could not connect.'))
def test_failed_test_does_not_allow_enable(self, sender):
self.assertEqual(self.client.post(self.test_url, {'ntfy_url': self.topic}).status_code, 502)
self.assertContains(self.save(), 'Test this URL successfully')
@patch('planner.services.notifications.send_ntfy_notification')
def test_disabled_preference_suppresses_delivery(self, sender):
self.assertFalse(send_notification(self.user, 'Title', 'Message'))
sender.assert_not_called()
+47
View File
@@ -9,6 +9,8 @@ from django.utils import timezone
from django.urls import reverse
from .models import FastingPause, FastingPeriod, FastingSettings, SickDaySettings, Task
from .models import UserSettings, WaterIntakeEntry
from .services.hydration import hydration_context
from .forms import DAILY_FASTING_DURATION_CHOICES, FastingSettingsForm
from .services.deferrals import (
apply_missed_task_deferrals,
@@ -1511,3 +1513,48 @@ class TaskCompletionViewTests(TestCase):
self.client.post(reverse('planner:task-toggle-completed', args=[foreign.pk])).status_code,
404,
)
class HydrationWidgetTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='hydration-user', password='test-password')
self.client.force_login(self.user)
UserSettings.objects.update_or_create(user=self.user, defaults={'daily_water_goal_ml': 500})
def test_entries_total_and_over_goal_visual_cap(self):
self.client.post(reverse('planner:hydration-add'), {'amount_ml': 250})
self.client.post(reverse('planner:hydration-add'), {'amount_ml': 500})
self.assertEqual(WaterIntakeEntry.objects.filter(user=self.user).count(), 2)
context = hydration_context(self.user)
self.assertEqual(context['hydration_total'], 750)
self.assertEqual(context['hydration_percent'], 150)
self.assertEqual(context['hydration_visual'], 100)
self.assertEqual(next(day for day in context['hydration_days'] if day['today'])['state'], 'goal')
def test_health_page_reuses_widgets_and_live_hydration(self):
response = self.client.get(reverse('planner:health'))
self.assertContains(response, 'Health routines')
self.assertContains(response, 'id="fasting-widget"')
self.assertContains(response, 'id="hydration-widget"')
self.client.post(reverse('planner:hydration-add'), {'amount_ml': 250})
self.assertContains(self.client.get(reverse('planner:health')), '250 <span>/ 500 ml</span>', html=True)
def test_undo_only_current_user_current_day(self):
other = get_user_model().objects.create_user(username='other-hydration-user')
WaterIntakeEntry.objects.create(user=other, amount_ml=500)
yesterday = timezone.now() - timedelta(days=1)
WaterIntakeEntry.objects.create(user=self.user, amount_ml=250, recorded_at=yesterday)
self.client.post(reverse('planner:hydration-add'), {'amount_ml': 500})
self.client.post(reverse('planner:hydration-undo'))
self.assertEqual(hydration_context(self.user)['hydration_total'], 0)
self.assertEqual(WaterIntakeEntry.objects.filter(user=self.user).count(), 1)
self.assertEqual(WaterIntakeEntry.objects.filter(user=other).count(), 1)
def test_week_rolls_forward_and_invalid_amount_is_rejected(self):
monday = timezone.now().astimezone(ZoneInfo('Europe/Amsterdam'))
monday = monday - timedelta(days=monday.weekday())
prior_week = monday - timedelta(days=7)
WaterIntakeEntry.objects.create(user=self.user, amount_ml=500, recorded_at=prior_week)
self.assertTrue(all(day['state'] == 'none' for day in hydration_context(self.user)['hydration_days']))
response = self.client.post(reverse('planner:hydration-add'), {'amount_ml': 3001})
self.assertContains(response, 'Enter a whole amount')
self.assertEqual(WaterIntakeEntry.objects.filter(user=self.user).count(), 1)
+5 -1
View File
@@ -8,7 +8,7 @@ from .views import (
TaskUpdateView, WorkoutCreateView, WorkoutUpdateView, delete_workout, fasting_configure, neck_headache_checkin_panel,
fasting_toggle_tracking, fasting_widget, logout_view, register, toggle_task_active, toggle_task_completed,
save_neck_headache_checkin, save_sleep_checkin, advance_onboarding, toggle_workout_completed, user_settings, workout_today,
bowel_health_panel, save_bowel_health_checkin, toggle_tooth_brushing,
bowel_health_panel, save_bowel_health_checkin, toggle_tooth_brushing, hydration_add, hydration_undo, test_ntfy, gitea_activity,
)
app_name = 'planner'
@@ -20,6 +20,8 @@ urlpatterns = [
path('register/', register, name='register'),
path('logout/', logout_view, name='logout'),
path('settings/', user_settings, name='user-settings'),
path('settings/notifications/ntfy/test/', test_ntfy, name='ntfy-test'),
path('gitea/activity/', gitea_activity, name='gitea-activity'),
path('onboarding/advance/', advance_onboarding, name='onboarding-advance'),
path('daily/', DailyPlannerView.as_view(), name='daily-planner'),
path('fasting/widget/', fasting_widget, name='fasting-widget'),
@@ -29,6 +31,8 @@ urlpatterns = [
path('check-ins/save/', save_neck_headache_checkin, name='neck-headache-checkin-save'),
path('sleep-check-ins/save/', save_sleep_checkin, name='sleep-checkin-save'),
path('teeth/toggle/', toggle_tooth_brushing, name='tooth-brushing-toggle'),
path('hydration/add/', hydration_add, name='hydration-add'),
path('hydration/undo/', hydration_undo, name='hydration-undo'),
path('bowel-health/panel/', bowel_health_panel, name='bowel-health-panel'),
path('bowel-health/save/', save_bowel_health_checkin, name='bowel-health-save'),
path('check-ins/export/<str:period>/', export_pain_csv, name='pain-export'),
+87 -2
View File
@@ -1,9 +1,13 @@
import calendar
from hashlib import sha256
from datetime import timedelta
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse, reverse_lazy
@@ -16,9 +20,12 @@ from django.views.generic import CreateView, DeleteView, DetailView, ListView, T
from .forms import (
DailyPlannerForm, FastingSettingsForm, RegistrationForm, SickDaySettingsForm, SleepCheckInForm, TimeZoneSettingsForm,
BowelHealthCheckInForm, NeckHeadacheCheckInForm, TaskForm, UserSettingsForm, WorkoutForm,
BowelHealthCheckInForm, NeckHeadacheCheckInForm, TaskForm, UserSettingsForm, WorkoutForm, HydrationGoalForm, WaterIntakeForm, NtfySettingsForm,
)
from .models import BowelHealthCheckIn, FastingPeriod, FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, ToothBrushing, UserSettings, Workout
from .models import BowelHealthCheckIn, FastingPeriod, FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, ToothBrushing, UserSettings, Workout, WaterIntakeEntry
from .services.hydration import hydration_context
from .services.gitea_activity import activity_context
from .services.notifications import NotificationError, send_ntfy_notification
from .services.checkins import (
ANNUAL_PHYSIOTHERAPY_SESSION_ALLOWANCE, LOW_PAIN_STREAK_THRESHOLD, calculate_check_in_streaks,
)
@@ -513,11 +520,19 @@ class TaskListView(LoginRequiredMixin, ListView):
context.update(dashboard_weather_context(self.request.user))
context.update(workout_context(self.request.user))
context.update(brushing_context(self.request.user))
context.update(hydration_context(self.request.user))
context['gitea_activity_enabled'] = bool(settings.GITEA_USERNAME)
profile, _ = UserSettings.objects.get_or_create(user=self.request.user)
context['onboarding_tour'] = onboarding_context(profile)
return context
@login_required
@require_http_methods(['GET'])
def gitea_activity(request):
return render(request, 'planner/partials/gitea_activity.html', activity_context())
class HealthView(LoginRequiredMixin, TemplateView):
template_name = 'planner/health.html'
@@ -530,6 +545,8 @@ class HealthView(LoginRequiredMixin, TemplateView):
context.update(bowel_context(
self.request.user, selected_check_in_date(self.request.GET.get('bowel_date'), self.request.user),
))
context.update(fasting_widget_context(self.request.user))
context.update(hydration_context(self.request.user))
return context
@@ -735,9 +752,11 @@ def user_settings(request):
sick_day, _ = SickDaySettings.objects.get_or_create(user=request.user)
fasting = FastingSettings.objects.filter(user=request.user).first()
profile_form = UserSettingsForm(instance=profile)
hydration_goal_form = HydrationGoalForm(instance=profile)
sick_form = SickDaySettingsForm(instance=sick_day)
fasting_form = FastingSettingsForm(instance=fasting)
time_zone_form = TimeZoneSettingsForm(instance=profile)
ntfy_form = NtfySettingsForm(instance=profile)
if request.method == 'POST':
section = request.POST.get('section')
@@ -747,6 +766,34 @@ def user_settings(request):
profile_form.save()
messages.success(request, 'Your weather location was saved.')
return redirect('planner:user-settings')
elif section == 'hydration':
hydration_goal_form = HydrationGoalForm(request.POST, instance=profile)
if hydration_goal_form.is_valid():
hydration_goal_form.save()
messages.success(request, 'Your daily water goal was saved.')
return redirect('planner:user-settings')
elif section == 'ntfy':
old_url = profile.ntfy_url
ntfy_form = NtfySettingsForm(request.POST, instance=profile)
if ntfy_form.is_valid():
url = ntfy_form.cleaned_data['ntfy_url']
tested = bool(url) and request.session.get(f'ntfy_tested:{request.user.pk}') == sha256(url.encode()).hexdigest()
previously_tested = url == old_url and profile.ntfy_last_tested_at is not None
if ntfy_form.cleaned_data['ntfy_enabled'] and not (tested or previously_tested):
ntfy_form.add_error('ntfy_url', 'Test this URL successfully before enabling notifications.')
else:
profile = ntfy_form.save(commit=False)
if not url:
profile.ntfy_enabled = False
profile.ntfy_last_tested_at = None
elif tested:
profile.ntfy_last_tested_at = timezone.now()
elif url != old_url:
profile.ntfy_last_tested_at = None
profile.save()
request.session.pop(f'ntfy_tested:{request.user.pk}', None)
messages.success(request, 'Notification settings were saved.')
return redirect('planner:user-settings')
elif section == 'sick-day':
sick_form = SickDaySettingsForm(request.POST, instance=sick_day)
if sick_form.is_valid():
@@ -794,13 +841,51 @@ def user_settings(request):
return render(request, 'planner/user_settings.html', {
'profile_form': profile_form,
'hydration_goal_form': hydration_goal_form,
'sick_form': sick_form,
'fasting_form': fasting_form,
'time_zone_form': time_zone_form,
'ntfy_form': ntfy_form,
'onboarding_enabled': profile.onboarding_enabled,
})
@login_required
@require_POST
def test_ntfy(request):
url = request.POST.get('ntfy_url', '').strip()
try:
URLValidator(schemes=['http', 'https'])(url)
except ValidationError:
return render(request, 'planner/partials/ntfy_test_result.html', {'error': 'Enter a valid HTTP or HTTPS topic URL.'}, status=400)
try:
send_ntfy_notification(url, 'Tasknest', 'Test notification sent successfully.')
except NotificationError as error:
return render(request, 'planner/partials/ntfy_test_result.html', {'error': str(error)}, status=502)
request.session[f'ntfy_tested:{request.user.pk}'] = sha256(url.encode()).hexdigest()
return render(request, 'planner/partials/ntfy_test_result.html', {'success': True})
@login_required
@require_POST
def hydration_add(request):
form = WaterIntakeForm(request.POST)
if form.is_valid():
WaterIntakeEntry.objects.create(user=request.user, amount_ml=form.cleaned_data['amount_ml'])
context = hydration_context(request.user)
context['hydration_error'] = form.errors.get('amount_ml') if not form.is_valid() else None
return render(request, 'planner/partials/hydration_widget.html', context)
@login_required
@require_POST
def hydration_undo(request):
context = hydration_context(request.user)
if context['hydration_last']:
context['hydration_last'].delete()
return render(request, 'planner/partials/hydration_widget.html', hydration_context(request.user))
@require_http_methods(['GET', 'POST'])
def register(request):
if request.user.is_authenticated: