From 743785c2e0e41514c8dd18c035b7ea21716d87de Mon Sep 17 00:00:00 2001 From: Joren de Graaf Date: Mon, 19 Oct 2026 16:51:53 +0200 Subject: [PATCH] Fix OAuth page --- main/MCP.md | 10 +- main/dreams/__init__.py | 0 main/dreams/api.py | 149 ++++++++++++++++++ main/dreams/forms.py | 66 ++++++++ main/dreams/migrations/0001_initial.py | 43 +++++ main/dreams/migrations/__init__.py | 0 main/dreams/models.py | 31 ++++ main/dreams/templates/dreams/_form.html | 14 ++ main/dreams/templates/dreams/detail.html | 3 + main/dreams/templates/dreams/edit.html | 3 + main/dreams/templates/dreams/journal.html | 15 ++ main/dreams/tests.py | 79 ++++++++++ main/dreams/urls.py | 10 ++ main/dreams/views.py | 69 ++++++++ main/food/api.py | 2 +- main/food/api_schema.py | 42 ++++- main/food/api_urls.py | 6 + main/food/oauth_authorize.py | 53 +++++++ main/food/services/diary.py | 29 +++- main/food/static/food/food.css | 12 ++ main/food/templates/food/diary.html | 2 +- .../food/partials/nutrition_summary.html | 3 +- .../food/partials/progress_ring.html | 10 ++ main/food/templates/food/tokens.html | 6 +- ...authorize.html => authorize_tasknest.html} | 4 +- main/food/test_oauth_mcp.py | 138 +++++++++++++++- main/food/tests.py | 29 +++- main/mcp_server/server.py | 114 +++++++++++++- main/mcp_server/tests.py | 79 +++++++++- main/planner/static/planner/nav_spacing.css | 4 + main/planner/templates/planner/base.html | 5 +- main/planner/templates/planner/health.html | 2 + .../partials/neck_headache_checkin.html | 1 + main/planner/templates/planner/task_list.html | 9 +- main/planner/views.py | 6 + main/stress/__init__.py | 0 main/stress/api.py | 117 ++++++++++++++ main/stress/forms.py | 78 +++++++++ main/stress/migrations/0001_initial.py | 39 +++++ ...ily_date_stressentry_revisions_and_more.py | 29 ++++ main/stress/migrations/__init__.py | 0 main/stress/models.py | 45 ++++++ main/stress/services.py | 47 ++++++ main/stress/static/stress/stress.css | 8 + main/stress/static/stress/widget.css | 30 ++++ .../templates/stress/_daily_widget.html | 17 ++ main/stress/templates/stress/_form.html | 12 ++ main/stress/templates/stress/edit.html | 10 ++ main/stress/templates/stress/journal.html | 50 ++++++ main/stress/tests.py | 133 ++++++++++++++++ main/stress/urls.py | 11 ++ main/stress/views.py | 139 ++++++++++++++++ main/tasksnest/settings.py | 4 + main/tasksnest/urls.py | 4 + 54 files changed, 1794 insertions(+), 27 deletions(-) create mode 100644 main/dreams/__init__.py create mode 100644 main/dreams/api.py create mode 100644 main/dreams/forms.py create mode 100644 main/dreams/migrations/0001_initial.py create mode 100644 main/dreams/migrations/__init__.py create mode 100644 main/dreams/models.py create mode 100644 main/dreams/templates/dreams/_form.html create mode 100644 main/dreams/templates/dreams/detail.html create mode 100644 main/dreams/templates/dreams/edit.html create mode 100644 main/dreams/templates/dreams/journal.html create mode 100644 main/dreams/tests.py create mode 100644 main/dreams/urls.py create mode 100644 main/dreams/views.py create mode 100644 main/food/oauth_authorize.py create mode 100644 main/food/templates/food/partials/progress_ring.html rename main/food/templates/oauth2_provider/{authorize.html => authorize_tasknest.html} (64%) create mode 100644 main/planner/static/planner/nav_spacing.css create mode 100644 main/stress/__init__.py create mode 100644 main/stress/api.py create mode 100644 main/stress/forms.py create mode 100644 main/stress/migrations/0001_initial.py create mode 100644 main/stress/migrations/0002_stressentry_daily_date_stressentry_revisions_and_more.py create mode 100644 main/stress/migrations/__init__.py create mode 100644 main/stress/models.py create mode 100644 main/stress/services.py create mode 100644 main/stress/static/stress/stress.css create mode 100644 main/stress/static/stress/widget.css create mode 100644 main/stress/templates/stress/_daily_widget.html create mode 100644 main/stress/templates/stress/_form.html create mode 100644 main/stress/templates/stress/edit.html create mode 100644 main/stress/templates/stress/journal.html create mode 100644 main/stress/tests.py create mode 100644 main/stress/urls.py create mode 100644 main/stress/views.py diff --git a/main/MCP.md b/main/MCP.md index 9a4aea4..006ad76 100644 --- a/main/MCP.md +++ b/main/MCP.md @@ -1,6 +1,6 @@ # TaskNest MCP server -The Streamable HTTP MCP endpoint exposes the Food, Kitchen, and Recipes API to an AI assistant. The server in `mcp_server.server` is an HTTP adapter: every user operation goes through `/api/v1/` with the connected user's bearer token. It does not read Django models directly. +The Streamable HTTP MCP endpoint exposes the Food, Kitchen, Recipes, and private Stress Journal API to an AI assistant. The server in `mcp_server.server` is an HTTP adapter: every user operation goes through `/api/v1/` with the connected user's bearer token. It does not read Django models directly. ## Local development @@ -47,12 +47,20 @@ Before reconnecting ChatGPT, verify the public endpoints: `/.well-known/oauth-pr Open **Settings → API tokens → Connect an AI assistant**. For ChatGPT, use the public MCP URL and OAuth sign-in. ChatGPT must be able to reach the HTTPS URL and its OAuth metadata. For Open WebUI or another bearer-token client, create a personal token with only the scopes needed, choose Streamable HTTP, and enter the same MCP URL and token as a bearer credential. The helper's password field is local to the browser and clears when the page is left; it does not submit the token to the helper. Revoke a token from Settings when it is no longer needed. +An existing ChatGPT connection may continue to request its original food and inventory scopes even after the server advertises the newer journal scopes. During a fresh OAuth consent, select **Also allow reading and changing my private dream and stress journals** if you want journal tools. The box is off by default; leaving it off preserves the requested scopes. Reconnecting without new consent or merely refreshing an old token does not add journal access. If ChatGPT skips the consent screen, revoke its old TaskNest authorization in API tokens and reconnect once. The consent screen lists the requested permissions and the optional journal upgrade separately. + The server exposes tools for food diary, product catalogue, inventory, and hydration reads and changes. `food_attach_image` and `food_log_with_image` accept a ChatGPT file object via `image_file` or base64 data via `image_base64`. Images must be JPEG, PNG, or WebP and at most 5 MiB. A client-supplied file URL must use HTTPS and an allowed host. The API performs image validation and ownership checks. Creation tools accept an `idempotency_key`; reuse the same key and arguments when retrying a request. `food_log_with_image` reports whether the entry was created even if its later attachment upload fails. `food_get_today` accepts an optional `date` in `YYYY-MM-DD` format. Omit it for the user's local today; pass a calendar date to read another day, such as yesterday. The HTTP API supports the same parameter on `GET /api/v1/food/today/?date=YYYY-MM-DD`. `hydration_get_daily` returns combined fluid intake, manual and Food Diary contributions, the daily goal, and remaining amount. `hydration_log`, `hydration_update`, and `hydration_delete` manage standalone manual entries. Use an `idempotency_key` with `hydration_log` when retrying. `hydration_settings_get` and `hydration_settings_update` configure automatic Food Diary counting and optional beverage rules. The Food Diary tools count eligible millilitre drinks during the food write; no additional hydration tool call is needed. +## Private stress journal + +The `stress_search`, `stress_get`, `stress_create`, `stress_update`, and `stress_delete` tools use `journal:read` and `journal:write` scopes. Existing food and inventory tokens cannot read journal content. A check-in has a 0–10 score, optional note, stressor tags and physical symptoms, a timestamp, and a timing value: `anytime`, `before_sleep`, or `after_waking`. Naive timestamps use the user's saved time zone. Search supports text, local date, and timing filters. Create returns an ID; use that ID with `stress_update` for later conversational corrections rather than creating another entry. Reuse the same idempotency key and payload on creation retries. The web journal at `/stress/` provides history, a 30-day calendar, descriptive stress summaries, and nearby dream/stress entries. These comparisons describe timing only and do not establish causation. + +The `dream_search`, `dream_get`, `dream_create`, `dream_update`, and `dream_delete` tools use the same private journal scopes. Dreams are associated with the local date on waking, matching Health > Sleep, and can be backdated. Keep the narrative separate from the user's own interpretation; do not infer or invent either. `dream_search` supports keywords, tag, date, date range, limit, and offset. Creation returns an ID and idempotency key; use the ID for follow-up corrections. `dream_update` can replace supplied fields or append narrative/after-waking details. Appends require an idempotency key to avoid duplicate text on retries. The web journal is at `/dreams/`; the Health sleep panel links to a matching dream on the selected wake-up date. + ## Product discovery and grocery photographs Image interpretation belongs to the AI client. For a grocery photograph, identify the visible products and any readable barcodes, brands, package sizes, quantities, and storage locations, then send structured data to TaskNest. Unreadable details should remain unknown. diff --git a/main/dreams/__init__.py b/main/dreams/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main/dreams/api.py b/main/dreams/api.py new file mode 100644 index 0000000..9c2a2c2 --- /dev/null +++ b/main/dreams/api.py @@ -0,0 +1,149 @@ +"""Private dream journal API for the authenticated user's MCP tools.""" +from django.core.exceptions import ValidationError +from django.db.models import Q +from django.http import JsonResponse +from django.utils import timezone +from django.utils.dateparse import parse_date, parse_datetime + +from food.api import api_view, error, _json, _idempotent +from planner.timezones import timezone_for_user +from .forms import normalize_terms +from .models import DreamEntry + +FIELDS = {'wake_up_date', 'dreamed_at', 'title', 'narrative', 'interpretation', + 'tags', 'emotions', 'vividness', 'is_nightmare', 'after_waking_notes'} +APPEND_FIELDS = {'append_narrative': 'narrative', 'append_after_waking_notes': 'after_waking_notes'} + + +def serialize(entry): + return {'id': str(entry.pk), 'wake_up_date': entry.wake_up_date.isoformat(), + 'dreamed_at': entry.dreamed_at.isoformat() if entry.dreamed_at else None, + 'title': entry.title, 'narrative': entry.narrative, 'interpretation': entry.interpretation, + 'tags': entry.tags, 'emotions': entry.emotions, 'vividness': entry.vividness, + 'is_nightmare': entry.is_nightmare, 'after_waking_notes': entry.after_waking_notes, + 'created_at': entry.created_at.isoformat(), 'updated_at': entry.updated_at.isoformat()} + + +def validate(data, user, *, updating=False): + if not isinstance(data, dict): + raise ValueError('Expected a JSON object.') + unknown = set(data) - FIELDS - (set(APPEND_FIELDS) if updating else set()) + if unknown: + raise ValueError('Unknown fields: ' + ', '.join(sorted(unknown))) + if 'narrative' in data and 'append_narrative' in data: + raise ValueError('Choose narrative or append_narrative, not both.') + if 'after_waking_notes' in data and 'append_after_waking_notes' in data: + raise ValueError('Choose after_waking_notes or append_after_waking_notes, not both.') + result = {} + if 'wake_up_date' in data: + value = data['wake_up_date'] + day = parse_date(value) if isinstance(value, str) else None + if day is None or day.isoformat() != value: + raise ValueError('Use YYYY-MM-DD for wake_up_date.') + result['wake_up_date'] = day + if 'dreamed_at' in data: + value = data['dreamed_at'] + if value is None: + result['dreamed_at'] = None + else: + moment = parse_datetime(value) if isinstance(value, str) else None + if moment is None: + raise ValueError('Use an ISO date and time for dreamed_at.') + result['dreamed_at'] = timezone.make_aware(moment, timezone_for_user(user)) if timezone.is_naive(moment) else moment + for name, limit in [('title', 160), ('narrative', 20000), ('interpretation', 4000), + ('after_waking_notes', 4000)]: + if name in data: + value = data[name] + if not isinstance(value, str) or len(value) > limit or (name in {'title', 'narrative'} and not value.strip()): + raise ValueError(f'{name} must be non-empty text within {limit} characters.' if name in {'title', 'narrative'} else f'{name} must be text within {limit} characters.') + result[name] = value + for name in ('tags', 'emotions'): + if name in data: + result[name] = normalize_terms(data[name]) + if 'vividness' in data: + score = data['vividness'] + if score is not None and (isinstance(score, bool) or not isinstance(score, int) or not 0 <= score <= 10): + raise ValueError('Vividness must be 0–10 or null.') + result['vividness'] = score + if 'is_nightmare' in data: + if not isinstance(data['is_nightmare'], bool): + raise ValueError('is_nightmare must be true or false.') + result['is_nightmare'] = data['is_nightmare'] + for append_name in APPEND_FIELDS: + if append_name in data: + value = data[append_name] + if not isinstance(value, str) or not value.strip(): + raise ValueError(f'{append_name} must be non-empty text.') + result[append_name] = value.strip() + return result + + +@api_view({'GET': 'journal:read', 'POST': 'journal:write'}, ('GET', 'POST')) +def collection(request): + if request.method == 'GET': + entries = DreamEntry.objects.filter(user=request.api_user) + query = request.GET.get('query', '').strip()[:100] + if query: + entries = entries.filter(Q(title__icontains=query) | Q(narrative__icontains=query) | + Q(tags__icontains=query) | Q(emotions__icontains=query)) + tag = request.GET.get('tag', '').strip()[:40] + if tag: + entries = entries.filter(tags__icontains=tag) + for key, lookup in (('date', 'wake_up_date'), ('date_from', 'wake_up_date__gte'), + ('date_to', 'wake_up_date__lte')): + if text := request.GET.get(key): + day = parse_date(text) + if day is None or day.isoformat() != text: + return error('invalid_date', f'Use YYYY-MM-DD for {key}.') + entries = entries.filter(**{lookup: day}) + try: + limit = min(max(int(request.GET.get('limit', 30)), 1), 100) + offset = max(int(request.GET.get('offset', 0)), 0) + except ValueError: + return error('invalid_pagination', 'Limit and offset must be integers.') + return JsonResponse({'items': [serialize(entry) for entry in entries[offset:offset + limit]], + 'total': entries.count()}) + data = _json(request) + cleaned = validate(data, request.api_user) + if not {'wake_up_date', 'title', 'narrative'} <= cleaned.keys(): + return error('missing_fields', 'wake_up_date, title, and narrative are required.') + + def action(): + entry = DreamEntry(user=request.api_user, **cleaned) + entry.full_clean() + entry.save() + return JsonResponse(serialize(entry), status=201) + return _idempotent(request, data, action) + + +@api_view({'GET': 'journal:read', 'PATCH': 'journal:write', 'DELETE': 'journal:write'}, + ('GET', 'PATCH', 'DELETE')) +def item(request, identifier): + entry = DreamEntry.objects.filter(pk=identifier, user=request.api_user).first() + if entry is None: + return error('not_found', 'Dream entry not found.', 404) + if request.method == 'GET': + return JsonResponse(serialize(entry)) + if request.method == 'DELETE': + entry.delete() + return JsonResponse({'deleted': True}) + data = _json(request) + cleaned = validate(data, request.api_user, updating=True) + if any(name in cleaned for name in APPEND_FIELDS) and not request.headers.get('Idempotency-Key'): + return error('idempotency_required', 'Use an Idempotency-Key when appending dream details.') + + def action(): + for name, value in cleaned.items(): + if name in APPEND_FIELDS: + field = APPEND_FIELDS[name] + current = getattr(entry, field) + combined = f'{current}\n\n{value}' if current else value + if len(combined) > (20000 if field == 'narrative' else 4000): + return error('too_long', f'{field} is too long.') + setattr(entry, field, combined) + else: + setattr(entry, name, value) + entry.full_clean() + entry.save() + return JsonResponse(serialize(entry)) + return _idempotent(request, data, action) if request.headers.get('Idempotency-Key') else action() diff --git a/main/dreams/forms.py b/main/dreams/forms.py new file mode 100644 index 0000000..c9a574f --- /dev/null +++ b/main/dreams/forms.py @@ -0,0 +1,66 @@ +from django import forms +from django.utils import timezone + +from planner.timezones import localdate_for_user, timezone_for_user +from .models import DreamEntry + + +def normalize_terms(value): + if not isinstance(value, list) or len(value) > 12: + raise forms.ValidationError('Use up to 12 terms.') + result = [] + for item in value: + if not isinstance(item, str) or not item.strip() or len(item.strip()) > 40: + raise forms.ValidationError('Each term must be 1–40 characters.') + term = item.strip() + if term.casefold() not in {existing.casefold() for existing in result}: + result.append(term) + return result + + +class DreamEntryForm(forms.ModelForm): + dreamed_at = forms.DateTimeField(required=False, label='Approximate time of dream', + input_formats=['%Y-%m-%dT%H:%M'], + widget=forms.DateTimeInput(format='%Y-%m-%dT%H:%M', attrs={'type': 'datetime-local'})) + tags_text = forms.CharField(required=False, label='Themes or tags', max_length=500) + emotions_text = forms.CharField(required=False, label='Emotions', max_length=500) + + class Meta: + model = DreamEntry + fields = ('wake_up_date', 'dreamed_at', 'title', 'narrative', 'vividness', + 'is_nightmare', 'after_waking_notes', 'interpretation') + widgets = { + 'wake_up_date': forms.DateInput(format='%Y-%m-%d', attrs={'type': 'date'}), + 'narrative': forms.Textarea(attrs={'rows': 6}), + 'after_waking_notes': forms.Textarea(attrs={'rows': 3}), + 'interpretation': forms.Textarea(attrs={'rows': 3}), + 'vividness': forms.NumberInput(attrs={'min': 0, 'max': 10}), + } + + def __init__(self, *args, user=None, **kwargs): + super().__init__(*args, **kwargs) + self.user = user + if not self.is_bound and self.instance._state.adding and user: + self.fields['wake_up_date'].initial = localdate_for_user(user) + if not self.instance._state.adding: + self.fields['tags_text'].initial = ', '.join(self.instance.tags) + self.fields['emotions_text'].initial = ', '.join(self.instance.emotions) + if self.instance.dreamed_at: + self.fields['dreamed_at'].initial = timezone.localtime( + self.instance.dreamed_at, timezone_for_user(user)) + + def clean_tags_text(self): + return normalize_terms([part.strip() for part in self.cleaned_data['tags_text'].split(',') if part.strip()]) + + def clean_emotions_text(self): + return normalize_terms([part.strip() for part in self.cleaned_data['emotions_text'].split(',') if part.strip()]) + + def save(self, commit=True): + entry = super().save(commit=False) + if entry.dreamed_at and timezone.is_naive(entry.dreamed_at): + entry.dreamed_at = timezone.make_aware(entry.dreamed_at, timezone_for_user(self.user)) + entry.tags = self.cleaned_data['tags_text'] + entry.emotions = self.cleaned_data['emotions_text'] + if commit: + entry.save() + return entry diff --git a/main/dreams/migrations/0001_initial.py b/main/dreams/migrations/0001_initial.py new file mode 100644 index 0000000..4f38084 --- /dev/null +++ b/main/dreams/migrations/0001_initial.py @@ -0,0 +1,43 @@ +# Generated by Django 6.1.1 on 2026-10-18 15:34 + +import django.core.validators +import django.db.models.deletion +import django.utils.timezone +import uuid +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='DreamEntry', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('wake_up_date', models.DateField(db_index=True)), + ('dreamed_at', models.DateTimeField(blank=True, null=True)), + ('title', models.CharField(max_length=160)), + ('narrative', models.TextField(max_length=20000)), + ('interpretation', models.TextField(blank=True, max_length=4000)), + ('tags', models.JSONField(blank=True, default=list)), + ('emotions', models.JSONField(blank=True, default=list)), + ('vividness', models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)])), + ('is_nightmare', models.BooleanField(default=False)), + ('after_waking_notes', models.TextField(blank=True, max_length=4000)), + ('created_at', models.DateTimeField(default=django.utils.timezone.now)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='dream_entries', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'ordering': ('-wake_up_date', '-created_at'), + 'indexes': [models.Index(fields=['user', '-wake_up_date'], name='dreams_drea_user_id_f28241_idx')], + }, + ), + ] diff --git a/main/dreams/migrations/__init__.py b/main/dreams/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main/dreams/models.py b/main/dreams/models.py new file mode 100644 index 0000000..5a6a308 --- /dev/null +++ b/main/dreams/models.py @@ -0,0 +1,31 @@ +import uuid + +from django.conf import settings +from django.core.validators import MaxValueValidator, MinValueValidator +from django.db import models +from django.utils import timezone + + +class DreamEntry(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='dream_entries') + wake_up_date = models.DateField(db_index=True) + dreamed_at = models.DateTimeField(null=True, blank=True) + title = models.CharField(max_length=160) + narrative = models.TextField(max_length=20000) + interpretation = models.TextField(blank=True, max_length=4000) + tags = models.JSONField(default=list, blank=True) + emotions = models.JSONField(default=list, blank=True) + vividness = models.PositiveSmallIntegerField(null=True, blank=True, + validators=[MinValueValidator(0), MaxValueValidator(10)]) + is_nightmare = models.BooleanField(default=False) + after_waking_notes = models.TextField(blank=True, max_length=4000) + created_at = models.DateTimeField(default=timezone.now) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + ordering = ('-wake_up_date', '-created_at') + indexes = [models.Index(fields=('user', '-wake_up_date'))] + + def __str__(self): + return f'{self.title} ({self.wake_up_date})' diff --git a/main/dreams/templates/dreams/_form.html b/main/dreams/templates/dreams/_form.html new file mode 100644 index 0000000..15f6a8b --- /dev/null +++ b/main/dreams/templates/dreams/_form.html @@ -0,0 +1,14 @@ +{% csrf_token %} +{% if form.non_field_errors %}
{{ form.non_field_errors }}
{% endif %} +
+{% for field in form %} +
+ {% if field.name == 'is_nightmare' %}{% else %}{{ field.label_tag }}{{ field }}{% endif %} + {% if field.name == 'wake_up_date' %}Use the date you woke up, matching Health > Sleep.{% endif %} + {% if field.name == 'tags_text' or field.name == 'emotions_text' %}Separate terms with commas.{% endif %} + {% if field.name == 'interpretation' %}Your own interpretation, kept separate from what happened in the dream.{% endif %} + {% for error in field.errors %}

{{ error }}

{% endfor %} +
+{% endfor %} +
+ diff --git a/main/dreams/templates/dreams/detail.html b/main/dreams/templates/dreams/detail.html new file mode 100644 index 0000000..5546afa --- /dev/null +++ b/main/dreams/templates/dreams/detail.html @@ -0,0 +1,3 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}{{ entry.title }} · Dream journal{% endblock %} +{% block content %}
← Dream journal

Private dream entry

{{ entry.title }}

Woke {{ entry.wake_up_date|date:'j F Y' }}{% if entry.dreamed_at %} · Dreamed around {% endif %}{% if entry.is_nightmare %} · Nightmare{% endif %}{% if entry.vividness is not None %} · Vividness {{ entry.vividness }}/10{% endif %}

Dream

{{ entry.narrative|linebreaksbr }}

{% if entry.tags %}

{% for tag in entry.tags %}{{ tag }}{% endfor %}

{% endif %}{% if entry.emotions %}

Emotions: {{ entry.emotions|join:', ' }}

{% endif %}{% if entry.after_waking_notes %}

After waking

{{ entry.after_waking_notes|linebreaksbr }}

{% endif %}{% if entry.interpretation %}

Your interpretation

{{ entry.interpretation|linebreaksbr }}

{% endif %}Edit dream
{% endblock %} diff --git a/main/dreams/templates/dreams/edit.html b/main/dreams/templates/dreams/edit.html new file mode 100644 index 0000000..39a0976 --- /dev/null +++ b/main/dreams/templates/dreams/edit.html @@ -0,0 +1,3 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}Edit dream · Tasknest{% endblock %} +{% block content %}
← Dream

Edit dream

{% include 'dreams/_form.html' with submit_label='Save changes' %}

Delete dream

This permanently removes this entry.

{% csrf_token %}
{% endblock %} diff --git a/main/dreams/templates/dreams/journal.html b/main/dreams/templates/dreams/journal.html new file mode 100644 index 0000000..34686a2 --- /dev/null +++ b/main/dreams/templates/dreams/journal.html @@ -0,0 +1,15 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}Dream journal · Tasknest{% endblock %} +{% block content %} + +
+

Private journal

Dream journal

Record what you remember. Dream details and your own interpretation stay separate.

+
+

Log a dream

Use the date you woke up. You can backdate entries and add details later.

{% include 'dreams/_form.html' with submit_label='Save dream' %}
+

History

{% if selected_date %}{% endif %}{% if query or selected_date %}Clear filters{% endif %}
+ {% if selected_date %}

Dreams for {{ selected_date|date:'j F Y' }}.

{% endif %} +
    {% for entry in entries %}
  1. {{ entry.title }}
    {% if entry.is_nightmare %}Nightmare{% endif %}

    {{ entry.narrative|truncatewords:45 }}

    {% if entry.tags %}

    {% for tag in entry.tags %}{{ tag }}{% endfor %}

    {% endif %}
  2. {% empty %}
  3. No dreams match this view.
  4. {% endfor %}
+
+
+
+{% endblock %} diff --git a/main/dreams/tests.py b/main/dreams/tests.py new file mode 100644 index 0000000..1ec2910 --- /dev/null +++ b/main/dreams/tests.py @@ -0,0 +1,79 @@ +import json +from datetime import date, datetime, timezone as datetime_timezone + +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.urls import reverse + +from food.api import create_token +from planner.models import UserSettings +from planner.timezones import localdate_for_user +from stress.models import StressEntry +from .models import DreamEntry + + +class DreamJournalTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(username='dreamer', password='test') + self.other = get_user_model().objects.create_user(username='other-dreamer', password='test') + UserSettings.objects.create(user=self.user, time_zone='Europe/Amsterdam') + + def test_web_journal_is_private_and_keeps_interpretation_separate(self): + self.client.force_login(self.user) + self.assertContains(self.client.get(reverse('dreams:journal')), + f'value="{localdate_for_user(self.user).isoformat()}"') + response = self.client.post(reverse('dreams:journal'), { + 'wake_up_date': '2026-10-18', 'title': 'A house', 'narrative': 'A remembered scene.', + 'interpretation': 'My own thought.', 'tags_text': 'house, vivid', + 'emotions_text': 'fear', 'vividness': '8', 'is_nightmare': 'on'}) + entry = DreamEntry.objects.get(user=self.user) + self.assertRedirects(response, reverse('dreams:detail', args=[entry.pk])) + self.assertEqual(entry.narrative, 'A remembered scene.') + self.assertEqual(entry.interpretation, 'My own thought.') + self.assertContains(self.client.get(reverse('dreams:detail', args=[entry.pk])), 'A remembered scene.') + self.client.force_login(self.other) + self.assertEqual(self.client.get(reverse('dreams:detail', args=[entry.pk])).status_code, 404) + self.assertEqual(self.client.post(reverse('dreams:delete', args=[entry.pk])).status_code, 404) + self.assertNotContains(self.client.get(reverse('dreams:journal')), 'A house') + + def test_api_idempotent_create_append_search_and_scope(self): + _, secret = create_token(self.user, 'Dream write', ['journal:read', 'journal:write']) + headers = {'HTTP_AUTHORIZATION': f'Bearer {secret}', 'content_type': 'application/json'} + payload = {'wake_up_date': '2026-10-18', 'title': 'A house', + 'narrative': 'First memory.', 'tags': ['house'], 'vividness': 8} + options = {**headers, 'HTTP_IDEMPOTENCY_KEY': 'dream-create-1'} + response = self.client.post('/api/v1/dreams/', json.dumps(payload), **options) + self.assertEqual(response.status_code, 201) + entry_id = response.json()['id'] + self.assertEqual(self.client.post('/api/v1/dreams/', json.dumps(payload), **options).json()['id'], entry_id) + self.assertEqual(DreamEntry.objects.count(), 1) + url = f'/api/v1/dreams/{entry_id}/' + self.assertEqual(self.client.patch(url, json.dumps({'append_narrative': 'Second memory.'}), **headers).status_code, 400) + append_options = {**headers, 'HTTP_IDEMPOTENCY_KEY': 'dream-append-1'} + changed = self.client.patch(url, json.dumps({'append_narrative': 'Second memory.'}), **append_options) + self.assertEqual(changed.status_code, 200) + self.assertEqual(self.client.patch(url, json.dumps({'append_narrative': 'Second memory.'}), **append_options).status_code, 200) + self.assertEqual(DreamEntry.objects.get(pk=entry_id).narrative, 'First memory.\n\nSecond memory.') + self.assertEqual(self.client.get('/api/v1/dreams/', {'tag': 'house', 'date': '2026-10-18'}, + HTTP_AUTHORIZATION=f'Bearer {secret}').json()['total'], 1) + _, other_secret = create_token(self.other, 'Dream read', ['journal:read']) + self.assertEqual(self.client.get(url, HTTP_AUTHORIZATION=f'Bearer {other_secret}').status_code, 404) + self.assertEqual(self.client.delete(url, HTTP_AUTHORIZATION=f'Bearer {other_secret}').status_code, 403) + + def test_selected_sleep_date_and_prior_evening_stress(self): + dream = DreamEntry.objects.create(user=self.user, wake_up_date=date(2026, 10, 18), + title='A house', narrative='A remembered scene.', is_nightmare=True) + StressEntry.objects.create(user=self.user, score=7, timing='before_sleep', + recorded_at=datetime(2026, 10, 17, 20, tzinfo=datetime_timezone.utc)) + StressEntry.objects.create(user=self.user, score=5, timing='after_waking', + recorded_at=datetime(2026, 10, 18, 6, tzinfo=datetime_timezone.utc)) + self.client.force_login(self.user) + health = self.client.get(reverse('planner:health'), {'check_in_date': '2026-10-18', 'wellbeing_tab': 'sleep'}) + self.assertContains(health, f'Dream logged · {dream.title}') + self.assertContains(health, reverse('dreams:detail', args=[dream.pk])) + historical = self.client.get(reverse('planner:neck-headache-checkin-panel'), + {'date': '2026-10-17', 'tab': 'sleep'}) + self.assertNotContains(historical, 'Dream logged') + stress = self.client.get(reverse('stress:journal')) + self.assertContains(stress, 'Before sleep: 7/10') + self.assertContains(stress, 'After waking: 5/10') diff --git a/main/dreams/urls.py b/main/dreams/urls.py new file mode 100644 index 0000000..e54a7d7 --- /dev/null +++ b/main/dreams/urls.py @@ -0,0 +1,10 @@ +from django.urls import path +from . import views + +app_name = 'dreams' +urlpatterns = [ + path('', views.journal, name='journal'), + path('/', views.detail, name='detail'), + path('/edit/', views.edit, name='edit'), + path('/delete/', views.delete, name='delete'), +] diff --git a/main/dreams/views.py b/main/dreams/views.py new file mode 100644 index 0000000..8d0d8ab --- /dev/null +++ b/main/dreams/views.py @@ -0,0 +1,69 @@ +from datetime import timedelta + +from django.contrib.auth.decorators import login_required +from django.db.models import Q +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect, render +from django.utils.dateparse import parse_date +from django.views.decorators.http import require_http_methods, require_POST + +from planner.timezones import localdate_for_user +from .forms import DreamEntryForm +from .models import DreamEntry + + +@login_required +@require_http_methods(['GET', 'POST']) +def journal(request): + query = request.GET.get('q', '').strip()[:100] + date_text = request.GET.get('date', '') + selected_date = parse_date(date_text) if date_text else None + if date_text and (selected_date is None or selected_date.isoformat() != date_text): + raise Http404('Invalid date') + form = DreamEntryForm(request.POST or None, user=request.user) + if selected_date and request.method == 'GET': + form.fields['wake_up_date'].initial = selected_date + if request.method == 'POST' and form.is_valid(): + entry = form.save(commit=False) + entry.user = request.user + entry.save() + return redirect('dreams:detail', identifier=entry.pk) + entries = DreamEntry.objects.filter(user=request.user) + if query: + entries = entries.filter(Q(title__icontains=query) | Q(narrative__icontains=query) | + Q(tags__icontains=query) | Q(emotions__icontains=query)) + if selected_date: + entries = entries.filter(wake_up_date=selected_date) + today = localdate_for_user(request.user) + counts = {} + for day in DreamEntry.objects.filter(user=request.user, wake_up_date__range=(today - timedelta(days=29), today)).values_list('wake_up_date', flat=True): + counts[day] = counts.get(day, 0) + 1 + calendar = [{'date': today - timedelta(days=offset), 'count': counts.get(today - timedelta(days=offset), 0)} + for offset in range(29, -1, -1)] + return render(request, 'dreams/journal.html', {'form': form, 'entries': entries[:80], + 'query': query, 'selected_date': selected_date, 'calendar': calendar}) + + +@login_required +def detail(request, identifier): + entry = get_object_or_404(DreamEntry, pk=identifier, user=request.user) + return render(request, 'dreams/detail.html', {'entry': entry}) + + +@login_required +@require_http_methods(['GET', 'POST']) +def edit(request, identifier): + entry = get_object_or_404(DreamEntry, pk=identifier, user=request.user) + form = DreamEntryForm(request.POST or None, instance=entry, user=request.user) + if request.method == 'POST' and form.is_valid(): + form.save() + return redirect('dreams:detail', identifier=entry.pk) + return render(request, 'dreams/edit.html', {'form': form, 'entry': entry}) + + +@login_required +@require_POST +def delete(request, identifier): + entry = get_object_or_404(DreamEntry, pk=identifier, user=request.user) + entry.delete() + return redirect('dreams:journal') diff --git a/main/food/api.py b/main/food/api.py index c754df4..70929d8 100644 --- a/main/food/api.py +++ b/main/food/api.py @@ -32,7 +32,7 @@ from .services.product_resolution import (create_manual, external_matches, impor local_matches, match_data) from .services.inventory_consumption import FACTORS, StockError, consume as consume_stock, preview as preview_stock, stock as stock_packages, undo as undo_stock -SCOPES = {'food:read', 'food:write', 'inventory:read', 'inventory:write'} +SCOPES = {'food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal:write'} NUTRIENTS = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g') MANUAL_FIELDS = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g') MAX_IMAGE_BYTES = 5 * 1024 * 1024 diff --git a/main/food/api_schema.py b/main/food/api_schema.py index f27e6c2..411e156 100644 --- a/main/food/api_schema.py +++ b/main/food/api_schema.py @@ -104,15 +104,55 @@ RECIPE_ANALYSIS = {'type': 'object', 'properties': { 'include_optional': {'type': 'boolean'}, 'substitutions': {'type': 'object', 'additionalProperties': {'type': 'string'}}, }} +STRESS = {'type': 'object', 'required': ['score'], 'properties': { + 'score': {'type': 'integer', 'minimum': 0, 'maximum': 10}, + 'recorded_at': {'type': 'string', 'format': 'date-time', 'description': 'Defaults to now; naive times use the user time zone'}, + 'timing': {'type': 'string', 'enum': ['anytime', 'before_sleep', 'after_waking']}, + 'note': {'type': 'string', 'maxLength': 2000}, + 'tags': {'type': 'array', 'maxItems': 12, 'items': {'type': 'string', 'maxLength': 40}}, + 'symptoms': {'type': 'array', 'items': {'type': 'string', 'enum': ['tension', 'headache', 'fatigue', 'restlessness']}}, +}} +DREAM = {'type': 'object', 'required': ['wake_up_date', 'title', 'narrative'], 'properties': { + 'wake_up_date': {'type': 'string', 'format': 'date', 'description': 'Local date on waking; matches Health > Sleep'}, + 'dreamed_at': {'type': ['string', 'null'], 'format': 'date-time'}, + 'title': {'type': 'string', 'maxLength': 160}, + 'narrative': {'type': 'string', 'maxLength': 20000}, + 'interpretation': {'type': 'string', 'maxLength': 4000}, + 'tags': {'type': 'array', 'maxItems': 12, 'items': {'type': 'string'}}, + 'emotions': {'type': 'array', 'maxItems': 12, 'items': {'type': 'string'}}, + 'vividness': {'type': ['integer', 'null'], 'minimum': 0, 'maximum': 10}, + 'is_nightmare': {'type': 'boolean'}, + 'after_waking_notes': {'type': 'string', 'maxLength': 4000}, + 'append_narrative': {'type': 'string', 'description': 'PATCH only; requires Idempotency-Key'}, + 'append_after_waking_notes': {'type': 'string', 'description': 'PATCH only; requires Idempotency-Key'}, +}} @require_GET def schema(request): document = { - 'openapi': '3.1.0', 'info': {'title': 'TaskNest Food and Kitchen API', 'version': '1.0.0'}, + 'openapi': '3.1.0', 'info': {'title': 'TaskNest API', 'version': '1.0.0'}, 'servers': [{'url': '/api/v1'}], 'components': {'securitySchemes': {'bearerToken': {'type': 'http', 'scheme': 'bearer'}}}, 'paths': { + '/dreams/': { + 'get': operation('Search own dreams by keywords, tags, and wake-up date', 'journal:read'), + 'post': operation('Create own dream with optional Idempotency-Key', 'journal:write', DREAM), + }, + '/dreams/{id}/': { + 'get': operation('Read own dream', 'journal:read'), + 'patch': operation('Update or append to own dream; append requires Idempotency-Key', 'journal:write', DREAM), + 'delete': operation('Delete own dream', 'journal:write'), + }, + '/stress/': { + 'get': operation('Search own stress check-ins by text, date, and timing', 'journal:read'), + 'post': operation('Create own stress check-in with optional Idempotency-Key', 'journal:write', STRESS), + }, + '/stress/{id}/': { + 'get': operation('Read own stress check-in', 'journal:read'), + 'patch': operation('Update own stress check-in', 'journal:write', STRESS), + 'delete': operation('Delete own stress check-in', 'journal:write'), + }, '/food/today/': {'get': operation('Food log for an optional local calendar date, defaulting to today', 'food:read')}, '/food/products/': {'get': operation('Search own food products', 'food:read')}, '/food/products/lookup/': {'get': operation('Look up local and optional Open Food Facts product candidates', 'food:read')}, diff --git a/main/food/api_urls.py b/main/food/api_urls.py index e474b48..970d284 100644 --- a/main/food/api_urls.py +++ b/main/food/api_urls.py @@ -1,9 +1,15 @@ from django.urls import path from . import api, api_schema from recipes import api as recipe_api +from stress import api as stress_api +from dreams import api as dream_api urlpatterns = [ path('auth/whoami/', api.whoami), + path('stress/', stress_api.collection), + path('stress//', stress_api.item), + path('dreams/', dream_api.collection), + path('dreams//', dream_api.item), path('schema/', api_schema.schema), path('food/today/', api.today), path('food/products/', api.products), diff --git a/main/food/oauth_authorize.py b/main/food/oauth_authorize.py new file mode 100644 index 0000000..21f591b --- /dev/null +++ b/main/food/oauth_authorize.py @@ -0,0 +1,53 @@ +"""Offer an explicit journal-scope upgrade for existing MCP OAuth clients.""" + +from django.conf import settings +from django.core import signing +from oauth2_provider.views import AuthorizationView + + +JOURNAL_SCOPES = ('journal:read', 'journal:write') +OFFER_SALT = 'tasknest-mcp-journal-consent' +CHATGPT_CLIENT_ID = 'https://chatgpt.com/oauth/client.json' + + +def is_mcp_consent(client_id, resource): + """ChatGPT can omit the resource parameter on a reconnect.""" + return (resource.strip() == settings.TASKNEST_MCP_PUBLIC_URL.rstrip('/') + or client_id == CHATGPT_CLIENT_ID) + + +class JournalAuthorizationView(AuthorizationView): + template_name = 'oauth2_provider/authorize_tasknest.html' + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + form = context.get('form') + if not form or not context.get('application'): + return context + requested = form['scope'].value() or '' + resource = form['resource'].value() or '' + if (is_mcp_consent(form['client_id'].value(), resource) + and not set(JOURNAL_SCOPES).issubset(requested.split())): + context['offer_journal_scopes'] = True + context['journal_scope_offer'] = signing.dumps({ + 'scope': requested, 'client_id': form['client_id'].value(), + 'resource': resource, + }, salt=OFFER_SALT) + return context + + def form_valid(self, form): + if form.cleaned_data.get('allow') and self.request.POST.get('grant_journal_scopes') == 'on': + try: + offer = signing.loads(self.request.POST.get('journal_scope_offer', ''), + salt=OFFER_SALT, max_age=600) + except signing.BadSignature: + form.add_error(None, 'Journal permission offer expired. Please reconnect and try again.') + return self.form_invalid(form) + scope = form.cleaned_data['scope'] + if (offer != {'scope': scope, 'client_id': form.cleaned_data['client_id'], + 'resource': form.cleaned_data.get('resource', '')} + or not is_mcp_consent(offer['client_id'], offer['resource'])): + form.add_error(None, 'Journal permission offer changed. Please reconnect and try again.') + return self.form_invalid(form) + form.cleaned_data['scope'] = ' '.join(dict.fromkeys([*scope.split(), *JOURNAL_SCOPES])) + return super().form_valid(form) diff --git a/main/food/services/diary.py b/main/food/services/diary.py index 8b96f7e..c2b25e3 100644 --- a/main/food/services/diary.py +++ b/main/food/services/diary.py @@ -1,5 +1,5 @@ from datetime import timedelta -from decimal import Decimal +from decimal import Decimal, ROUND_HALF_UP from django.utils import timezone from django.utils.dateparse import parse_date @@ -11,6 +11,26 @@ from planner.timezones import localdate_for_user ZERO = Decimal('0') + + +def ring_progress(amount, goal): + """Presentation values for a two-lap ring; totals and goals stay untouched. + + After two laps, the inner arc shows progress in the current lap. The + accompanying text states how many full laps have already been completed. + """ + progress = max(ZERO, amount * 100 / goal) + whole_laps = int(progress // 100) + current_lap = progress % 100 + if progress and current_lap == 0: + current_lap = Decimal('100') + return { + 'percent': int(progress.quantize(Decimal('1'), rounding=ROUND_HALF_UP)), + 'base_lap': format(min(progress, Decimal('100')), '.2f'), + 'extra_lap': format(current_lap if progress > 100 else ZERO, '.2f'), + 'full_laps': whole_laps, + 'current_lap': current_lap, + } NUTRIENT_NAMES = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g') NUTRIENT_LABELS = {'calories_kcal': 'calories', 'carbohydrates_g': 'carbs', 'protein_g': 'protein', 'fat_g': 'fat', 'fibre_g': 'fibre', @@ -72,10 +92,15 @@ def diary_context(user, day, language='en'): ): eaten = totals[name] is_incomplete = incomplete[name] + ring = ring_progress(eaten, goal) if goal and (known_counts[name] or not entries) else None macros.append({'label': label, 'slug': name, 'guidance': nutrient_guidance(name, language), 'eaten': eaten if known_counts[name] or not entries else None, 'goal': goal, 'remaining': goal - eaten if goal is not None and not is_incomplete else None, - 'percent': min(100, int(eaten * 100 / goal)) if goal and (known_counts[name] or not entries) else None, + 'percent': ring['percent'] if ring else None, + 'base_lap': ring['base_lap'] if ring else ZERO, + 'extra_lap': ring['extra_lap'] if ring else ZERO, + 'full_laps': ring['full_laps'] if ring else 0, + 'current_lap': ring['current_lap'] if ring else ZERO, 'color': color, 'incomplete': is_incomplete}) calorie_goal = goals.daily_calorie_goal calories = totals['calories_kcal'] diff --git a/main/food/static/food/food.css b/main/food/static/food/food.css index eac4c9b..972dc1d 100644 --- a/main/food/static/food/food.css +++ b/main/food/static/food/food.css @@ -93,3 +93,15 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317} @media(max-width:600px){.inventory-page>.food-heading{align-items:flex-start;flex-wrap:wrap}.inventory-heading-actions{justify-content:flex-start;width:100%}} .food-quantity-form{display:flex;align-items:center;gap:.35rem}.food-quantity{font-weight:700;white-space:nowrap}.food-quantity-form button{min-width:44px;min-height:44px;border:1px solid var(--food-border);border-radius:50%;background:var(--food-surface);color:var(--food-ink);font:inherit;font-size:1.4rem;cursor:pointer}.food-quantity-form button:focus-visible{outline:2px solid var(--food-green);outline-offset:2px}.food-quantity-form.htmx-request button{opacity:.6;cursor:progress}.food-screen-reader{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} .food-quantity-controls{display:flex;align-items:center;gap:.35rem;white-space:nowrap}.food-quantity-controls .food-quantity{min-width:2.5ch;text-align:center}.food-quantity-controls .food-quantity-form{margin:0} + +/* Shared ring geometry: the outer lap stays complete beneath excess progress. */ +.food-ring{position:relative;display:grid;place-items:center;background:none} +.food-ring svg{display:block;width:100%;height:100%;transform:rotate(-90deg);overflow:visible} +.food-ring circle{fill:none;stroke-width:5} +.food-ring__track{stroke:var(--food-ring-track)} +.food-ring__base{stroke:var(--accent)} +.food-ring__extra{stroke:var(--accent);stroke-width:4;opacity:.8} +.food-ring>span{position:absolute;inset:0;display:grid;place-items:center;width:auto;height:auto;background:none;border-radius:0;font-variant-numeric:tabular-nums;font-size:.7rem;letter-spacing:-.035em} +.food-ring-laps{font-size:.7rem} +.food-macro--pink{--accent:#d45b8b} +.food-macro .food-ring{--accent:inherit} diff --git a/main/food/templates/food/diary.html b/main/food/templates/food/diary.html index bb701f4..16ec446 100644 --- a/main/food/templates/food/diary.html +++ b/main/food/templates/food/diary.html @@ -2,7 +2,7 @@ {% load static %} {% block title %}Food · Tasknest{% endblock %} {% block content %} - + {% include 'food/partials/diary_content.html' %} diff --git a/main/food/templates/food/partials/nutrition_summary.html b/main/food/templates/food/partials/nutrition_summary.html index c7529bf..a9c9f7b 100644 --- a/main/food/templates/food/partials/nutrition_summary.html +++ b/main/food/templates/food/partials/nutrition_summary.html @@ -25,10 +25,11 @@
{% for macro in macros %}
-
+ {% include 'food/partials/progress_ring.html' with ring=macro %}

{{ macro.label }}

{% if macro.eaten is None %}Known amount unavailable{% elif macro.incomplete %}At least {{ macro.eaten|floatformat:1 }} g{% else %}{{ macro.eaten|floatformat:1 }} g eaten{% endif %}{% if macro.goal is not None %} · {{ macro.goal|floatformat:1 }} g goal{% endif %}

{% if macro.incomplete %}

{% if macro.goal is not None %}Remaining unknown{% else %}Nutrition incomplete · No target{% endif %}

{% elif macro.goal is not None %}

{% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}

{% else %}

No target

{% endif %} + {% if macro.percent > 200 %}

{{ macro.full_laps }} full laps{% if macro.current_lap < 100 %} + {{ macro.current_lap|floatformat:0 }}% of next{% endif %}

{% endif %}