Fix OAuth page
This commit is contained in:
+9
-1
@@ -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.
|
||||
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -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})'
|
||||
@@ -0,0 +1,14 @@
|
||||
{% csrf_token %}
|
||||
{% if form.non_field_errors %}<div class="stress-errors">{{ form.non_field_errors }}</div>{% endif %}
|
||||
<div class="stress-form-grid">
|
||||
{% for field in form %}
|
||||
<div class="stress-field{% if field.name == 'narrative' or field.name == 'after_waking_notes' or field.name == 'interpretation' %} stress-field--wide{% endif %}">
|
||||
{% if field.name == 'is_nightmare' %}<label>{{ field }} {{ field.label }}</label>{% else %}{{ field.label_tag }}{{ field }}{% endif %}
|
||||
{% if field.name == 'wake_up_date' %}<small>Use the date you woke up, matching Health > Sleep.</small>{% endif %}
|
||||
{% if field.name == 'tags_text' or field.name == 'emotions_text' %}<small>Separate terms with commas.</small>{% endif %}
|
||||
{% if field.name == 'interpretation' %}<small>Your own interpretation, kept separate from what happened in the dream.</small>{% endif %}
|
||||
{% for error in field.errors %}<p class="stress-errors">{{ error }}</p>{% endfor %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<button class="button" type="submit">{{ submit_label }}</button>
|
||||
@@ -0,0 +1,3 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}{{ entry.title }} · Dream journal{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'stress/stress.css' %}?v=1"><div class="stress-page stress-edit"><a href="{% url 'dreams:journal' %}">← Dream journal</a><article class="stress-panel"><p class="eyebrow">Private dream entry</p><h1>{{ entry.title }}</h1><p class="stress-muted">Woke {{ entry.wake_up_date|date:'j F Y' }}{% if entry.dreamed_at %} · Dreamed around <time datetime="{{ entry.dreamed_at|date:'c' }}">{{ entry.dreamed_at|date:'j M Y, H:i' }}</time>{% endif %}{% if entry.is_nightmare %} · Nightmare{% endif %}{% if entry.vividness is not None %} · Vividness {{ entry.vividness }}/10{% endif %}</p><h2>Dream</h2><p>{{ entry.narrative|linebreaksbr }}</p>{% if entry.tags %}<p class="stress-chips" aria-label="Themes">{% for tag in entry.tags %}<span>{{ tag }}</span>{% endfor %}</p>{% endif %}{% if entry.emotions %}<p><strong>Emotions:</strong> {{ entry.emotions|join:', ' }}</p>{% endif %}{% if entry.after_waking_notes %}<h2>After waking</h2><p>{{ entry.after_waking_notes|linebreaksbr }}</p>{% endif %}{% if entry.interpretation %}<h2>Your interpretation</h2><p>{{ entry.interpretation|linebreaksbr }}</p>{% endif %}<a class="button button--secondary" href="{% url 'dreams:edit' entry.pk %}">Edit dream</a></article></div>{% endblock %}
|
||||
@@ -0,0 +1,3 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Edit dream · Tasknest{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'stress/stress.css' %}?v=1"><div class="stress-page stress-edit"><a href="{% url 'dreams:detail' entry.pk %}">← Dream</a><section class="stress-panel"><h1>Edit dream</h1><form method="post">{% include 'dreams/_form.html' with submit_label='Save changes' %}</form></section><section class="stress-panel stress-delete"><h2>Delete dream</h2><p>This permanently removes this entry.</p><form method="post" action="{% url 'dreams:delete' entry.pk %}" onsubmit="return confirm('Delete this dream?')">{% csrf_token %}<button class="button button--secondary" type="submit">Delete dream</button></form></section></div>{% endblock %}
|
||||
@@ -0,0 +1,15 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Dream journal · Tasknest{% endblock %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'stress/stress.css' %}?v=1">
|
||||
<div class="stress-page">
|
||||
<header class="stress-header"><p class="eyebrow">Private journal</p><h1>Dream journal</h1><p>Record what you remember. Dream details and your own interpretation stay separate.</p></header>
|
||||
<div class="stress-layout"><div class="stress-main">
|
||||
<section class="stress-panel"><h2>Log a dream</h2><p class="stress-muted">Use the date you woke up. You can backdate entries and add details later.</p><form method="post">{% include 'dreams/_form.html' with submit_label='Save dream' %}</form></section>
|
||||
<section class="stress-panel" id="dream-history"><h2>History</h2><form class="stress-filter" method="get" aria-label="Filter dream history"><label>Search dreams <input type="search" name="q" value="{{ query }}"></label>{% if selected_date %}<input type="hidden" name="date" value="{{ selected_date|date:'Y-m-d' }}">{% endif %}<button class="button button--secondary" type="submit">Filter</button>{% if query or selected_date %}<a href="{% url 'dreams:journal' %}">Clear filters</a>{% endif %}</form>
|
||||
{% if selected_date %}<p>Dreams for {{ selected_date|date:'j F Y' }}.</p>{% endif %}
|
||||
<ol class="stress-entries">{% for entry in entries %}<li class="stress-entry"><div class="stress-entry__top"><div><strong><a href="{% url 'dreams:detail' entry.pk %}">{{ entry.title }}</a></strong><time datetime="{{ entry.wake_up_date|date:'Y-m-d' }}">Woke {{ entry.wake_up_date|date:'j M Y' }}</time></div>{% if entry.is_nightmare %}<span class="stress-chips"><span>Nightmare</span></span>{% endif %}</div><p>{{ entry.narrative|truncatewords:45 }}</p>{% if entry.tags %}<p class="stress-chips" aria-label="Themes">{% for tag in entry.tags %}<span>{{ tag }}</span>{% endfor %}</p>{% endif %}</li>{% empty %}<li class="stress-empty">No dreams match this view.</li>{% endfor %}</ol>
|
||||
</section>
|
||||
</div><aside class="stress-side"><section class="stress-panel"><h2>Past 30 days</h2><p class="stress-muted">Choose a wake-up date to see its dreams.</p><div class="stress-calendar">{% for day in calendar %}<a href="?date={{ day.date|date:'Y-m-d' }}#dream-history" aria-label="{{ day.date|date:'j F Y' }}: {{ day.count }} dream{{ day.count|pluralize }}" class="{% if day.count %}has-entry{% endif %}{% if selected_date == day.date %} is-selected{% endif %}"><span>{{ day.date|date:'j' }}</span>{% if day.count %}<small>{{ day.count }}</small>{% endif %}</a>{% endfor %}</div></section></aside></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -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')
|
||||
@@ -0,0 +1,10 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
app_name = 'dreams'
|
||||
urlpatterns = [
|
||||
path('', views.journal, name='journal'),
|
||||
path('<uuid:identifier>/', views.detail, name='detail'),
|
||||
path('<uuid:identifier>/edit/', views.edit, name='edit'),
|
||||
path('<uuid:identifier>/delete/', views.delete, name='delete'),
|
||||
]
|
||||
@@ -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')
|
||||
+1
-1
@@ -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
|
||||
|
||||
+41
-1
@@ -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')},
|
||||
|
||||
@@ -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/<uuid:identifier>/', stress_api.item),
|
||||
path('dreams/', dream_api.collection),
|
||||
path('dreams/<uuid:identifier>/', dream_api.item),
|
||||
path('schema/', api_schema.schema),
|
||||
path('food/today/', api.today),
|
||||
path('food/products/', api.products),
|
||||
|
||||
@@ -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)
|
||||
@@ -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']
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
{% load static %}
|
||||
{% block title %}Food · Tasknest{% endblock %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261017-nutrition">
|
||||
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261018-rings">
|
||||
{% include 'food/partials/diary_content.html' %}
|
||||
<script defer src="{% static 'food/quantity.js' %}?v=20261015"></script>
|
||||
<script defer src="{% static 'food/nutrient_help.js' %}?v=20261015-quantity"></script>
|
||||
|
||||
@@ -25,10 +25,11 @@
|
||||
<section class="food-macros" id="food-macro-summary" aria-label="Daily nutrition goals">
|
||||
{% for macro in macros %}<article class="food-card food-macro food-macro--{{ macro.color }}" aria-labelledby="food-goal-{{ macro.slug }}">
|
||||
<button class="food-help-trigger" type="button" aria-label="{% if help_language|slice:':2' == 'nl' %}Hulp bij {{ macro.guidance.title }}{% else %}About {{ macro.guidance.title }}{% endif %}" aria-expanded="false" aria-controls="food-help-{{ macro.slug }}" data-food-help-trigger><span aria-hidden="true">?</span></button>
|
||||
<div class="food-ring" {% if macro.percent is not None %}style="--progress:{{ macro.percent }}%" role="progressbar" aria-label="{{ macro.label }} progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ macro.percent }}" aria-valuetext="{% if macro.incomplete %}At least {% endif %}{{ macro.eaten|floatformat:1 }} g of {{ macro.goal|floatformat:1 }} g{% if macro.incomplete %}; total incomplete{% endif %}"{% else %}aria-label="{{ macro.label }} progress unknown"{% endif %}><span aria-hidden="true">{% if macro.percent is not None %}{{ macro.percent }}%{% else %}—{% endif %}</span></div>
|
||||
{% include 'food/partials/progress_ring.html' with ring=macro %}
|
||||
<div><h3 id="food-goal-{{ macro.slug }}">{{ macro.label }}</h3>
|
||||
<p>{% 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 %}</p>
|
||||
{% if macro.incomplete %}<p><span class="food-warning-mark" aria-hidden="true">!</span> {% if macro.goal is not None %}Remaining unknown{% else %}Nutrition incomplete · No target{% endif %}</p>{% elif macro.goal is not None %}<p>{% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}</p>{% else %}<p>No target</p>{% endif %}
|
||||
{% if macro.percent > 200 %}<p class="food-ring-laps">{{ macro.full_laps }} full laps{% if macro.current_lap < 100 %} + {{ macro.current_lap|floatformat:0 }}% of next{% endif %}</p>{% endif %}
|
||||
</div>
|
||||
<div class="food-help-popover" id="food-help-{{ macro.slug }}" role="region" aria-labelledby="food-help-title-{{ macro.slug }}" hidden>
|
||||
<div class="food-help-heading"><h4 id="food-help-title-{{ macro.slug }}">{{ macro.guidance.title }}</h4><button type="button" class="food-help-close" data-food-help-close aria-label="{% if help_language|slice:':2' == 'nl' %}Sluiten{% else %}Close{% endif %}">×</button></div>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<div class="food-ring" role="img" aria-label="{{ ring.label }}: {% if ring.percent is not None %}{{ ring.percent }}% of target; {% if ring.incomplete %}at least {% endif %}{{ ring.eaten|floatformat:1 }} g of {{ ring.goal|floatformat:1 }} g{% if ring.incomplete %}; total incomplete, remaining unknown{% elif ring.remaining < 0 %}; {{ ring.remaining|floatformat:1|cut:'-' }} g over target{% else %}; {{ ring.remaining|floatformat:1 }} g remaining{% endif %}{% if ring.percent > 200 %}; {{ ring.full_laps }} full laps{% endif %}{% else %}progress unknown{% endif %}">
|
||||
<svg viewBox="0 0 54 54" aria-hidden="true" focusable="false">
|
||||
<circle class="food-ring__track" cx="27" cy="27" r="22" pathLength="100" />
|
||||
{% if ring.percent is not None %}
|
||||
<circle class="food-ring__base" cx="27" cy="27" r="22" pathLength="100" stroke-dasharray="{{ ring.base_lap }} 100" />
|
||||
{% if ring.percent > 100 %}<circle class="food-ring__extra" cx="27" cy="27" r="15" pathLength="100" stroke-dasharray="{{ ring.extra_lap }} 100" />{% endif %}
|
||||
{% endif %}
|
||||
</svg>
|
||||
<span aria-hidden="true">{% if ring.percent is not None %}{{ ring.percent }}%{% else %}—{% endif %}</span>
|
||||
</div>
|
||||
@@ -4,7 +4,7 @@
|
||||
<section class="settings-page">
|
||||
<p class="eyebrow">Personal preferences</p>
|
||||
<h1>API tokens</h1>
|
||||
<p>Give an app access to your food log and kitchen inventory. Keep tokens private.</p>
|
||||
<p>Give an app access to your food log, kitchen inventory, or private stress and dream journals. Keep tokens private.</p>
|
||||
{% if new_token %}
|
||||
<section class="settings-card" role="status">
|
||||
<h2>New token</h2>
|
||||
@@ -32,7 +32,7 @@
|
||||
</section>
|
||||
<section class="settings-card mcp-helper" data-mcp-helper>
|
||||
<h2>Connect an AI assistant</h2>
|
||||
<p>Compatible assistants can use your Food and Kitchen data through MCP. Access is limited to the permissions you grant.</p>
|
||||
<p>Compatible assistants can use your Food, Kitchen, Stress Journal, and Dream Journal data through MCP. Access is limited to the permissions you grant.</p>
|
||||
<div class="form-field">
|
||||
<label for="mcp-server-url">MCP server URL</label>
|
||||
<input id="mcp-server-url" type="url" readonly data-mcp-url>
|
||||
@@ -49,7 +49,7 @@
|
||||
<p data-mcp-status role="status" aria-live="polite"></p>
|
||||
<p class="mcp-helper__hint">Treat this token like a password. TaskNest does not save the token you paste here. You can revoke access from your API tokens.</p>
|
||||
<div class="mcp-helper__clients">
|
||||
<section><h3>ChatGPT</h3><p>Add a custom MCP app in ChatGPT and enter the MCP server URL. Select OAuth authentication, then sign in to TaskNest and approve the requested permissions. ChatGPT does not use the pasted token field.</p></section>
|
||||
<section><h3>ChatGPT</h3><p>Add a custom MCP app in ChatGPT and enter the MCP server URL. Select OAuth authentication, then sign in to TaskNest and review the requested permissions. For dream and stress tools, select the optional private journal permission on the TaskNest consent page. If reconnecting skips consent, revoke the old ChatGPT authorization above and reconnect once. ChatGPT does not use the pasted token field.</p></section>
|
||||
<section><h3>Open WebUI</h3><p>In Admin Settings → Integrations → External Tool Servers, add an MCP (Streamable HTTP) connection. Use the URL above, choose Bearer authentication, and paste your token into its Key field.</p></section>
|
||||
<section><h3>Generic MCP client</h3><p>Use Streamable HTTP at the URL above and send <code>Authorization: Bearer <your token></code> as a separate header. Never put the token in the URL.</p></section>
|
||||
</div>
|
||||
|
||||
+3
-1
@@ -9,11 +9,13 @@
|
||||
{% else %}
|
||||
<section class="settings-card">
|
||||
<h2>Allow {{ application.name }}?</h2>
|
||||
<p>This assistant is requesting access to your TaskNest account. It can only use the permissions listed here.</p>
|
||||
<p>Allow access grants the permissions listed here{% if offer_journal_scopes %} and any optional permissions you select below{% endif %}.</p>
|
||||
<ul>{% for scope in scopes_descriptions %}<li>{{ scope }}</li>{% endfor %}</ul>
|
||||
{% if offer_journal_scopes %}<p>This connection did not request the newer private journal permissions. You can explicitly add them here for dream and stress tools.</p>{% endif %}
|
||||
<form method="post" id="authorizationForm">
|
||||
{% csrf_token %}
|
||||
{% for field in form %}{% if field.is_hidden %}{{ field }}{% endif %}{% endfor %}
|
||||
{% if offer_journal_scopes %}<input type="hidden" name="journal_scope_offer" value="{{ journal_scope_offer }}"><label class="checkbox-field"><input type="checkbox" name="grant_journal_scopes" value="on"> Also allow reading and changing my private dream and stress journals</label>{% endif %}
|
||||
{{ form.non_field_errors }}
|
||||
<button class="button" type="submit" name="allow" value="Authorize">Allow access</button>
|
||||
<button class="button button--secondary" type="submit" value="Cancel">Cancel</button>
|
||||
+137
-1
@@ -4,14 +4,150 @@ from unittest.mock import patch
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
from django.test import TestCase, override_settings
|
||||
from oauth2_provider.models import Application, AccessToken
|
||||
|
||||
from .cimd import CompatibleCIMDFetcher
|
||||
from .models import PersonalAccessToken
|
||||
from .oauth_authorize import CHATGPT_CLIENT_ID
|
||||
|
||||
|
||||
class McpOAuthTests(TestCase):
|
||||
def test_chatgpt_reconnect_without_resource_offers_journal_access(self):
|
||||
user = get_user_model().objects.create_user('chatgpt-journal-reconnect', password='test')
|
||||
Application.objects.create(user=user, name='ChatGPT', client_id=CHATGPT_CLIENT_ID,
|
||||
client_type=Application.CLIENT_PUBLIC,
|
||||
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
|
||||
redirect_uris='https://chatgpt.com/connector_platform_oauth_redirect')
|
||||
self.client.force_login(user)
|
||||
verifier = 'v' * 64
|
||||
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
|
||||
consent = self.client.get('/o/authorize/', {
|
||||
'response_type': 'code', 'client_id': CHATGPT_CLIENT_ID,
|
||||
'redirect_uri': 'https://chatgpt.com/connector_platform_oauth_redirect',
|
||||
'scope': 'food:read food:write inventory:read inventory:write',
|
||||
'state': 'chatgpt-reconnect', 'code_challenge': challenge,
|
||||
'code_challenge_method': 'S256',
|
||||
}, HTTP_HOST='tasksnest.jorendegraaf.eu', secure=True)
|
||||
self.assertEqual(consent.status_code, 200)
|
||||
self.assertContains(consent, 'grant_journal_scopes')
|
||||
form = consent.context['form']
|
||||
self.assertFalse(form['resource'].value())
|
||||
payload = {field.name: field.value() for field in form
|
||||
if field.field.widget.is_hidden and field.value() is not None}
|
||||
payload.update(allow='Authorize', grant_journal_scopes='on',
|
||||
journal_scope_offer=consent.context['journal_scope_offer'])
|
||||
redirect = self.client.post('/o/authorize/', payload,
|
||||
HTTP_HOST='tasksnest.jorendegraaf.eu', secure=True)
|
||||
self.assertEqual(redirect.status_code, 302, redirect.content[:200])
|
||||
code = parse_qs(urlparse(redirect['Location']).query)['code'][0]
|
||||
token = self.client.post('/o/token/', {'grant_type': 'authorization_code', 'code': code,
|
||||
'redirect_uri': 'https://chatgpt.com/connector_platform_oauth_redirect',
|
||||
'client_id': CHATGPT_CLIENT_ID, 'code_verifier': verifier},
|
||||
HTTP_HOST='tasksnest.jorendegraaf.eu', secure=True)
|
||||
self.assertEqual(token.status_code, 200, token.content[:200])
|
||||
self.assertEqual(set(token.json()['scope'].split()),
|
||||
{'food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal:write'})
|
||||
|
||||
@override_settings(TASKNEST_MCP_PUBLIC_URL='http://localhost:8002/mcp')
|
||||
def test_existing_client_can_explicitly_add_journal_scopes_on_reconnect(self):
|
||||
user = get_user_model().objects.create_user('journal-upgrade', password='test')
|
||||
application = Application.objects.create(user=user, name='Existing assistant',
|
||||
client_type=Application.CLIENT_PUBLIC,
|
||||
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
|
||||
redirect_uris='http://localhost:9876/callback')
|
||||
self.client.force_login(user)
|
||||
verifier = 'v' * 64
|
||||
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
|
||||
old_scopes = 'food:read food:write inventory:read inventory:write'
|
||||
metadata = self.client.get('/.well-known/oauth-authorization-server', HTTP_HOST='localhost').json()
|
||||
self.assertTrue({'journal:read', 'journal:write'} <= set(metadata['scopes_supported']))
|
||||
|
||||
def connect(state, add_journal=False):
|
||||
params = {'response_type': 'code', 'client_id': application.client_id,
|
||||
'redirect_uri': 'http://localhost:9876/callback', 'scope': old_scopes,
|
||||
'state': state, 'code_challenge': challenge, 'code_challenge_method': 'S256',
|
||||
'resource': 'http://localhost:8002/mcp'}
|
||||
consent = self.client.get('/o/authorize/', params, HTTP_HOST='localhost')
|
||||
self.assertEqual(consent.status_code, 200)
|
||||
self.assertContains(consent, 'grant_journal_scopes')
|
||||
form = consent.context['form']
|
||||
payload = {field.name: field.value() for field in form
|
||||
if field.field.widget.is_hidden and field.value() is not None}
|
||||
payload['allow'] = 'Authorize'
|
||||
if add_journal:
|
||||
payload['grant_journal_scopes'] = 'on'
|
||||
payload['journal_scope_offer'] = consent.context['journal_scope_offer']
|
||||
redirect = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
|
||||
self.assertEqual(redirect.status_code, 302, redirect.content[:200])
|
||||
code = parse_qs(urlparse(redirect['Location']).query)['code'][0]
|
||||
token_response = self.client.post('/o/token/', {
|
||||
'grant_type': 'authorization_code', 'code': code,
|
||||
'redirect_uri': 'http://localhost:9876/callback',
|
||||
'client_id': application.client_id, 'code_verifier': verifier,
|
||||
'resource': 'http://localhost:8002/mcp'}, HTTP_HOST='localhost')
|
||||
self.assertEqual(token_response.status_code, 200, token_response.content[:200])
|
||||
return token_response.json()
|
||||
|
||||
original = connect('old-grant')
|
||||
old_scope_set = set(original['scope'].split())
|
||||
self.assertEqual(old_scope_set, set(old_scopes.split()))
|
||||
self.assertEqual(self.client.get('/api/v1/dreams/',
|
||||
HTTP_AUTHORIZATION=f"Bearer {original['access_token']}", HTTP_HOST='localhost').status_code, 403)
|
||||
old_refresh = self.client.post('/o/token/', {'grant_type': 'refresh_token',
|
||||
'refresh_token': original['refresh_token'], 'client_id': application.client_id,
|
||||
'resource': 'http://localhost:8002/mcp'}, HTTP_HOST='localhost')
|
||||
self.assertEqual(old_refresh.status_code, 200)
|
||||
self.assertEqual(set(old_refresh.json()['scope'].split()), old_scope_set)
|
||||
|
||||
upgraded = connect('upgraded-grant', add_journal=True)
|
||||
expected = set(old_scopes.split()) | {'journal:read', 'journal:write'}
|
||||
self.assertEqual(set(upgraded['scope'].split()), expected)
|
||||
self.assertEqual(self.client.get('/api/v1/dreams/',
|
||||
HTTP_AUTHORIZATION=f"Bearer {upgraded['access_token']}", HTTP_HOST='localhost').status_code, 200)
|
||||
dream = self.client.post('/api/v1/dreams/',
|
||||
data='{"wake_up_date":"2026-10-18","title":"Test","narrative":"User supplied."}',
|
||||
content_type='application/json', HTTP_AUTHORIZATION=f"Bearer {upgraded['access_token']}",
|
||||
HTTP_HOST='localhost')
|
||||
self.assertEqual(dream.status_code, 201, dream.content[:200])
|
||||
self.assertEqual(self.client.get('/api/v1/stress/',
|
||||
HTTP_AUTHORIZATION=f"Bearer {upgraded['access_token']}", HTTP_HOST='localhost').status_code, 200)
|
||||
self.assertEqual(self.client.get('/api/v1/food/today/',
|
||||
HTTP_AUTHORIZATION=f"Bearer {upgraded['access_token']}", HTTP_HOST='localhost').status_code, 200)
|
||||
refreshed = self.client.post('/o/token/', {'grant_type': 'refresh_token',
|
||||
'refresh_token': upgraded['refresh_token'], 'client_id': application.client_id,
|
||||
'resource': 'http://localhost:8002/mcp'}, HTTP_HOST='localhost')
|
||||
self.assertEqual(refreshed.status_code, 200)
|
||||
self.assertEqual(set(refreshed.json()['scope'].split()), expected)
|
||||
|
||||
@override_settings(TASKNEST_MCP_PUBLIC_URL='http://localhost:8002/mcp')
|
||||
def test_journal_upgrade_rejects_missing_or_changed_offer(self):
|
||||
user = get_user_model().objects.create_user('journal-offer', password='test')
|
||||
application = Application.objects.create(user=user, name='Offer test',
|
||||
client_type=Application.CLIENT_PUBLIC,
|
||||
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
|
||||
redirect_uris='http://localhost:9876/callback')
|
||||
self.client.force_login(user)
|
||||
verifier = 'v' * 64
|
||||
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
|
||||
consent = self.client.get('/o/authorize/', {'response_type': 'code',
|
||||
'client_id': application.client_id, 'redirect_uri': 'http://localhost:9876/callback',
|
||||
'scope': 'food:read', 'state': 'offer-test', 'code_challenge': challenge,
|
||||
'code_challenge_method': 'S256', 'resource': 'http://localhost:8002/mcp'},
|
||||
HTTP_HOST='localhost')
|
||||
form = consent.context['form']
|
||||
payload = {field.name: field.value() for field in form
|
||||
if field.field.widget.is_hidden and field.value() is not None}
|
||||
payload.update(allow='Authorize', grant_journal_scopes='on')
|
||||
response = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, 'Journal permission offer expired')
|
||||
payload['journal_scope_offer'] = consent.context['journal_scope_offer']
|
||||
payload['scope'] = 'food:write'
|
||||
response = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, 'Journal permission offer changed')
|
||||
|
||||
def test_cimd_requires_explicit_public_client_support(self):
|
||||
metadata = {'token_endpoint_auth_method': 'private_key_jwt',
|
||||
'token_endpoint_auth_methods_supported': ['private_key_jwt']}
|
||||
|
||||
+27
-2
@@ -10,7 +10,7 @@ from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
from planner.models import UserSettings
|
||||
|
||||
from .services.diary import diary_context
|
||||
from .services.diary import diary_context, ring_progress
|
||||
|
||||
from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit, InventoryLocation, KitchenInventoryItem, InventoryConsumption
|
||||
|
||||
@@ -81,12 +81,37 @@ class FoodFoundationTests(TestCase):
|
||||
context = diary_context(self.user, date(2026, 10, 3))
|
||||
self.assertEqual(context['totals']['fibre_g'], Decimal('45'))
|
||||
fibre = context['macros'][3]
|
||||
self.assertEqual(fibre['percent'], 100)
|
||||
self.assertEqual(fibre['percent'], 113)
|
||||
self.assertEqual(fibre['remaining'], Decimal('-5'))
|
||||
self.assertFalse(fibre['incomplete'])
|
||||
self.client.force_login(self.user)
|
||||
self.assertContains(self.client.get(reverse('food:diary'), {'date': '2026-10-03'}), '5.0 g over target')
|
||||
|
||||
def test_ring_laps_and_over_target_accessible_text(self):
|
||||
for amount, percent, base, extra, laps in (
|
||||
('0', 0, '0.00', '0.00', 0),
|
||||
('36', 75, '75.00', '0.00', 0),
|
||||
('48', 100, '100.00', '0.00', 1),
|
||||
('60', 125, '100.00', '25.00', 1),
|
||||
('80.4', 168, '100.00', '67.50', 1),
|
||||
('96', 200, '100.00', '100.00', 2),
|
||||
('108', 225, '100.00', '25.00', 2),
|
||||
):
|
||||
with self.subTest(amount=amount):
|
||||
ring = ring_progress(Decimal(amount), Decimal('48'))
|
||||
self.assertEqual((ring['percent'], ring['base_lap'], ring['extra_lap'], ring['full_laps']),
|
||||
(percent, base, extra, laps))
|
||||
|
||||
UserSettings.objects.create(user=self.user, fat_goal_g=Decimal('48'))
|
||||
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.SNACKS,
|
||||
product_name_snapshot='Known fat', amount=Decimal('100'), unit=Unit.GRAM,
|
||||
fat_g=Decimal('80.4'))
|
||||
self.client.force_login(self.user)
|
||||
response = self.client.get(reverse('food:diary'), {'date': '2026-10-03'})
|
||||
self.assertContains(response, '168%')
|
||||
self.assertContains(response, '32.4 g over target')
|
||||
self.assertContains(response, 'stroke-dasharray="67.50 100"')
|
||||
|
||||
def test_favourite_and_portion_uniqueness(self):
|
||||
FoodFavourite.objects.create(user=self.user, product=self.product)
|
||||
FoodPortion.objects.create(user=self.user, product=self.product, label='My bowl', amount=Decimal('300'), unit=Unit.GRAM)
|
||||
|
||||
+112
-2
@@ -23,7 +23,7 @@ API_BASE = os.environ.get('TASKNEST_API_BASE_URL', 'http://127.0.0.1:1234/api/v1
|
||||
MCP_PUBLIC_URL = os.environ.get('TASKNEST_MCP_PUBLIC_URL', 'https://tasksnest.jorendegraaf.eu/mcp')
|
||||
OAUTH_ISSUER_URL = os.environ.get('TASKNEST_OAUTH_ISSUER_URL', 'https://tasksnest.jorendegraaf.eu/')
|
||||
MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
||||
SUPPORTED_SCOPES = ['food:read', 'food:write', 'inventory:read', 'inventory:write']
|
||||
SUPPORTED_SCOPES = ['food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal:write']
|
||||
FILE_HOSTS = tuple(host.strip().lower().lstrip('.') for host in
|
||||
os.environ.get('TASKNEST_MCP_FILE_HOSTS', 'openai.com,oaiusercontent.com,chatgpt.com').split(',') if host.strip())
|
||||
CHATGPT_BLOB_HOST = 'oaisdmntprukwest.blob.core.windows.net'
|
||||
@@ -196,6 +196,52 @@ class RecipeAnalysisInput(BaseModel):
|
||||
substitutions: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class StressInput(BaseModel):
|
||||
score: int = Field(ge=0, le=10)
|
||||
recorded_at: str | None = None
|
||||
timing: Literal['anytime', 'before_sleep', 'after_waking'] = 'anytime'
|
||||
note: str = ''
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
symptoms: list[Literal['tension', 'headache', 'fatigue', 'restlessness']] = Field(default_factory=list)
|
||||
|
||||
|
||||
class StressChanges(BaseModel):
|
||||
score: int | None = Field(default=None, ge=0, le=10)
|
||||
recorded_at: str | None = None
|
||||
timing: Literal['anytime', 'before_sleep', 'after_waking'] | None = None
|
||||
note: str | None = None
|
||||
tags: list[str] | None = None
|
||||
symptoms: list[Literal['tension', 'headache', 'fatigue', 'restlessness']] | None = None
|
||||
|
||||
|
||||
class DreamInput(BaseModel):
|
||||
wake_up_date: str
|
||||
title: str
|
||||
narrative: str
|
||||
dreamed_at: str | None = None
|
||||
interpretation: str = ''
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
emotions: list[str] = Field(default_factory=list)
|
||||
vividness: int | None = Field(default=None, ge=0, le=10)
|
||||
is_nightmare: bool = False
|
||||
after_waking_notes: str = ''
|
||||
|
||||
|
||||
class DreamChanges(BaseModel):
|
||||
wake_up_date: str | None = None
|
||||
title: str | None = None
|
||||
narrative: str | None = None
|
||||
dreamed_at: str | None = None
|
||||
interpretation: str | None = None
|
||||
tags: list[str] | None = None
|
||||
emotions: list[str] | None = None
|
||||
vividness: int | None = Field(default=None, ge=0, le=10)
|
||||
is_nightmare: bool | None = None
|
||||
after_waking_notes: str | None = None
|
||||
append_narrative: str | None = None
|
||||
append_after_waking_notes: str | None = None
|
||||
|
||||
|
||||
def _token() -> str:
|
||||
access = get_access_token()
|
||||
if access is None:
|
||||
@@ -330,7 +376,7 @@ async def _attach(entry_id, image_base64, image_file, mime_type, filename, capti
|
||||
|
||||
|
||||
def create_server() -> MCPServer:
|
||||
server = MCPServer('TaskNest', description='Food diary and kitchen inventory for the authenticated TaskNest user.',
|
||||
server = MCPServer('TaskNest', description='Food, kitchen, and private stress and dream journals for the authenticated TaskNest user.',
|
||||
token_verifier=ApiTokenVerifier(), auth=AuthSettings(
|
||||
issuer_url=AnyHttpUrl(OAUTH_ISSUER_URL), resource_server_url=AnyHttpUrl(MCP_PUBLIC_URL),
|
||||
required_scopes=[], validate_token_resource=False))
|
||||
@@ -665,6 +711,70 @@ def create_server() -> MCPServer:
|
||||
payload=payload, idempotency_key=key)
|
||||
return {**data, 'idempotency_key': key}
|
||||
|
||||
@server.tool(structured_output=True, description='Search or list your private stress check-ins. Optional date is a local YYYY-MM-DD day; timing distinguishes before sleep from after waking. Read only.')
|
||||
async def stress_search(query: str = '', date: str | None = None,
|
||||
timing: Literal['anytime', 'before_sleep', 'after_waking'] | None = None,
|
||||
limit: int = 30, offset: int = 0) -> dict[str, Any]:
|
||||
params = {'query': query, 'limit': min(max(limit, 1), 100), 'offset': max(offset, 0)}
|
||||
if date is not None:
|
||||
params['date'] = date
|
||||
if timing is not None:
|
||||
params['timing'] = timing
|
||||
return await api_request('GET', 'stress/', params=params)
|
||||
|
||||
@server.tool(structured_output=True, description='Read one stress check-in owned by the authenticated user using its ID. Read only.')
|
||||
async def stress_get(entry_id: str) -> dict[str, Any]:
|
||||
return await api_request('GET', f'stress/{entry_id}/')
|
||||
|
||||
@server.tool(structured_output=True, description='Create a private 0–10 stress check-in. Use before_sleep for stress before sleeping and after_waking for stress noticed after waking; do not conflate the two. Reuse idempotency_key on retries and update the returned ID for follow-up details.')
|
||||
async def stress_create(entry: StressInput, idempotency_key: str | None = None) -> dict[str, Any]:
|
||||
key = _key(idempotency_key)
|
||||
data = await api_request('POST', 'stress/', payload=entry.model_dump(mode='json', exclude_none=True),
|
||||
idempotency_key=key)
|
||||
return {**data, 'idempotency_key': key}
|
||||
|
||||
@server.tool(structured_output=True, description='Update only supplied fields of one owned stress check-in. Use for conversational corrections or adding details to the existing ID instead of creating a duplicate.')
|
||||
async def stress_update(entry_id: str, changes: StressChanges) -> dict[str, Any]:
|
||||
return await api_request('PATCH', f'stress/{entry_id}/',
|
||||
payload=changes.model_dump(mode='json', exclude_unset=True))
|
||||
|
||||
@server.tool(structured_output=True, description='Permanently delete one owned stress check-in. Require the user’s clear intent.')
|
||||
async def stress_delete(entry_id: str) -> dict[str, Any]:
|
||||
return await api_request('DELETE', f'stress/{entry_id}/')
|
||||
|
||||
@server.tool(structured_output=True, description='List or search your private dreams by keywords, tag, wake-up date or date range. Dates are local YYYY-MM-DD wake-up dates matching Health > Sleep. Read only.')
|
||||
async def dream_search(query: str = '', tag: str = '', date: str | None = None,
|
||||
date_from: str | None = None, date_to: str | None = None,
|
||||
limit: int = 30, offset: int = 0) -> dict[str, Any]:
|
||||
params = {'query': query, 'tag': tag, 'limit': min(max(limit, 1), 100), 'offset': max(offset, 0)}
|
||||
for key, value in [('date', date), ('date_from', date_from), ('date_to', date_to)]:
|
||||
if value is not None:
|
||||
params[key] = value
|
||||
return await api_request('GET', 'dreams/', params=params)
|
||||
|
||||
@server.tool(structured_output=True, description='Read one private dream entry by ID, including its original narrative and separately stored interpretation. Read only.')
|
||||
async def dream_get(entry_id: str) -> dict[str, Any]:
|
||||
return await api_request('GET', f'dreams/{entry_id}/')
|
||||
|
||||
@server.tool(structured_output=True, description='Create a private dream for its wake-up date. Record only details supplied by the user; do not invent or interpret. Use the returned ID for follow-ups and reuse idempotency_key on retries.')
|
||||
async def dream_create(entry: DreamInput, idempotency_key: str | None = None) -> dict[str, Any]:
|
||||
key = _key(idempotency_key)
|
||||
data = await api_request('POST', 'dreams/', payload=entry.model_dump(mode='json', exclude_none=True),
|
||||
idempotency_key=key)
|
||||
return {**data, 'idempotency_key': key}
|
||||
|
||||
@server.tool(structured_output=True, description='Update or append user-supplied corrections to an existing owned dream ID. For append fields, reuse idempotency_key on retries; follow-ups must not create duplicate dreams.')
|
||||
async def dream_update(entry_id: str, changes: DreamChanges,
|
||||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||||
payload = changes.model_dump(mode='json', exclude_unset=True)
|
||||
key = _key(idempotency_key) if any(name.startswith('append_') for name in payload) else idempotency_key
|
||||
data = await api_request('PATCH', f'dreams/{entry_id}/', payload=payload, idempotency_key=key)
|
||||
return {**data, **({'idempotency_key': key} if key else {})}
|
||||
|
||||
@server.tool(structured_output=True, description='Permanently delete an owned dream entry by ID. Require the user’s clear intent.')
|
||||
async def dream_delete(entry_id: str) -> dict[str, Any]:
|
||||
return await api_request('DELETE', f'dreams/{entry_id}/')
|
||||
|
||||
return server
|
||||
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ import httpx2
|
||||
from PIL import Image
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import LiveServerTestCase, SimpleTestCase
|
||||
from django.test import LiveServerTestCase, SimpleTestCase, override_settings
|
||||
from django.utils import timezone
|
||||
from mcp import Client
|
||||
from mcp.client.streamable_http import streamable_http_client
|
||||
@@ -78,7 +78,7 @@ class McpHttpTests(LiveServerTestCase):
|
||||
response = httpx2.get(f'http://127.0.0.1:{self.port}/.well-known/oauth-protected-resource/mcp', timeout=1)
|
||||
if response.status_code == 200:
|
||||
self.assertEqual(response.json()['scopes_supported'],
|
||||
['food:read', 'food:write', 'inventory:read', 'inventory:write'])
|
||||
['food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal:write'])
|
||||
break
|
||||
except httpx2.RequestError:
|
||||
pass
|
||||
@@ -142,6 +142,51 @@ class McpHttpTests(LiveServerTestCase):
|
||||
|
||||
asyncio.run(self._client(self.secret, check))
|
||||
|
||||
def test_stress_tools_support_incremental_updates(self):
|
||||
_, journal_secret = create_token(self.a, 'Journal MCP test', ['journal:read', 'journal:write'])
|
||||
|
||||
async def check(client):
|
||||
names = {tool.name for tool in (await client.list_tools()).tools}
|
||||
self.assertTrue({'stress_create', 'stress_search', 'stress_get', 'stress_update', 'stress_delete'} <= names)
|
||||
payload = {'entry': {'score': 7, 'timing': 'before_sleep', 'note': 'Work', 'tags': ['work']},
|
||||
'idempotency_key': 'mcp-stress-test-1'}
|
||||
created = (await client.call_tool('stress_create', payload)).structured_content
|
||||
entry_id = created['id']
|
||||
self.assertEqual((await client.call_tool('stress_create', payload)).structured_content['id'], entry_id)
|
||||
updated = (await client.call_tool('stress_update', {'entry_id': entry_id,
|
||||
'changes': {'note': 'Work and noise'}})).structured_content
|
||||
self.assertEqual(updated['score'], 7)
|
||||
self.assertEqual(updated['note'], 'Work and noise')
|
||||
self.assertEqual((await client.call_tool('stress_get', {'entry_id': entry_id})).structured_content['note'], 'Work and noise')
|
||||
self.assertEqual((await client.call_tool('stress_search', {'query': 'noise'})).structured_content['total'], 1)
|
||||
self.assertFalse((await client.call_tool('stress_delete', {'entry_id': entry_id})).is_error)
|
||||
self.assertEqual((await client.call_tool('stress_search')).structured_content['total'], 0)
|
||||
|
||||
asyncio.run(self._client(journal_secret, check))
|
||||
|
||||
def test_dream_tools_create_and_append_without_duplicates(self):
|
||||
_, journal_secret = create_token(self.a, 'Dream MCP test', ['journal:read', 'journal:write'])
|
||||
|
||||
async def check(client):
|
||||
names = {tool.name for tool in (await client.list_tools()).tools}
|
||||
self.assertTrue({'dream_create', 'dream_search', 'dream_get', 'dream_update', 'dream_delete'} <= names)
|
||||
payload = {'entry': {'wake_up_date': '2026-10-18', 'title': 'A house',
|
||||
'narrative': 'First memory.', 'tags': ['house']},
|
||||
'idempotency_key': 'mcp-dream-create-1'}
|
||||
created = (await client.call_tool('dream_create', payload)).structured_content
|
||||
entry_id = created['id']
|
||||
self.assertEqual((await client.call_tool('dream_create', payload)).structured_content['id'], entry_id)
|
||||
append = {'entry_id': entry_id, 'changes': {'append_narrative': 'Second memory.'},
|
||||
'idempotency_key': 'mcp-dream-append-1'}
|
||||
self.assertFalse((await client.call_tool('dream_update', append)).is_error)
|
||||
self.assertFalse((await client.call_tool('dream_update', append)).is_error)
|
||||
entry = (await client.call_tool('dream_get', {'entry_id': entry_id})).structured_content
|
||||
self.assertEqual(entry['narrative'], 'First memory.\n\nSecond memory.')
|
||||
self.assertEqual((await client.call_tool('dream_search', {'tag': 'house'})).structured_content['total'], 1)
|
||||
self.assertFalse((await client.call_tool('dream_delete', {'entry_id': entry_id})).is_error)
|
||||
|
||||
asyncio.run(self._client(journal_secret, check))
|
||||
|
||||
def test_inventory_update_partial_quantity_and_structured_validation(self):
|
||||
product = FoodProduct.objects.create(owner=self.a, product_name='Meatballs',
|
||||
package_amount=Decimal('400'), package_unit='g')
|
||||
@@ -200,7 +245,7 @@ class McpHttpTests(LiveServerTestCase):
|
||||
asyncio.run(self._client(self.secret, check))
|
||||
self.assertEqual(KitchenInventoryItem.objects.filter(pk__in=[item.pk for item in items], archived_at__isnull=False).count(), 2)
|
||||
|
||||
def test_oauth_issued_pat_authenticates_mcp(self):
|
||||
def test_oauth_issued_pat_authenticates_mcp_with_journal_upgrade(self):
|
||||
application = Application.objects.create(user=self.a, name='Test ChatGPT style client',
|
||||
client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
|
||||
redirect_uris='http://localhost:9876/callback')
|
||||
@@ -208,24 +253,44 @@ class McpHttpTests(LiveServerTestCase):
|
||||
verifier = 'v' * 64
|
||||
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
|
||||
params = {'response_type': 'code', 'client_id': application.client_id,
|
||||
'redirect_uri': 'http://localhost:9876/callback', 'scope': 'food:read',
|
||||
'redirect_uri': 'http://localhost:9876/callback',
|
||||
'scope': 'food:read food:write inventory:read inventory:write',
|
||||
'state': 'mcp-oauth-test', 'code_challenge': challenge, 'code_challenge_method': 'S256',
|
||||
'resource': self.mcp_url}
|
||||
response = self.client.get('/o/authorize/', params, HTTP_HOST='localhost')
|
||||
with override_settings(TASKNEST_MCP_PUBLIC_URL=self.mcp_url):
|
||||
response = self.client.get('/o/authorize/', params, HTTP_HOST='localhost')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, 'grant_journal_scopes')
|
||||
form = response.context['form']
|
||||
payload = {field.name: field.value() for field in form if field.field.widget.is_hidden and field.value() is not None}
|
||||
payload['allow'] = 'Authorize'
|
||||
redirect = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
|
||||
payload['grant_journal_scopes'] = 'on'
|
||||
payload['journal_scope_offer'] = response.context['journal_scope_offer']
|
||||
with override_settings(TASKNEST_MCP_PUBLIC_URL=self.mcp_url):
|
||||
redirect = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
|
||||
code = parse_qs(urlparse(redirect['Location']).query)['code'][0]
|
||||
response = self.client.post('/o/token/', {'grant_type': 'authorization_code', 'code': code,
|
||||
'redirect_uri': 'http://localhost:9876/callback', 'client_id': application.client_id,
|
||||
'code_verifier': verifier, 'resource': self.mcp_url}, HTTP_HOST='localhost')
|
||||
self.assertEqual(response.status_code, 200, response.content[:200])
|
||||
secret = response.json()['access_token']
|
||||
self.assertEqual(set(response.json()['scope'].split()),
|
||||
{'food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal:write'})
|
||||
async def check(client):
|
||||
self.assertFalse((await client.call_tool('food_get_today')).is_error)
|
||||
self.assertTrue((await client.call_tool('inventory_list')).is_error)
|
||||
self.assertFalse((await client.call_tool('inventory_list')).is_error)
|
||||
dream = await client.call_tool('dream_create', {'entry': {'wake_up_date': '2026-10-18',
|
||||
'title': 'User supplied', 'narrative': 'A room.'}, 'idempotency_key': 'oauth-dream-1'})
|
||||
self.assertFalse(dream.is_error, dream)
|
||||
dream_id = dream.structured_content['id']
|
||||
self.assertEqual((await client.call_tool('dream_search', {'query': 'room'})).structured_content['total'], 1)
|
||||
changed = await client.call_tool('dream_update', {'entry_id': dream_id,
|
||||
'changes': {'append_narrative': 'A door.'}, 'idempotency_key': 'oauth-dream-append-1'})
|
||||
self.assertFalse(changed.is_error, changed)
|
||||
stress = await client.call_tool('stress_create', {'entry': {'score': 5},
|
||||
'idempotency_key': 'oauth-stress-1'})
|
||||
self.assertFalse(stress.is_error, stress)
|
||||
self.assertEqual((await client.call_tool('stress_search')).structured_content['total'], 1)
|
||||
asyncio.run(self._client(secret, check))
|
||||
|
||||
def test_food_inventory_tools_and_user_isolation(self):
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
/* Keep the expanded navigation inside tablet widths as sections are added. */
|
||||
@media (min-width: 701px) and (max-width: 960px) {
|
||||
.primary-nav { gap: 8px; font-size: .82rem; }
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
{% load vite %}
|
||||
{% load vite static %}
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
@@ -7,6 +7,7 @@
|
||||
<meta name="description" content="A calm, focused personal task planner.">
|
||||
<title>{% block title %}Tasknest{% endblock %}</title>
|
||||
{% vite_asset 'src/main.js' %}
|
||||
<link rel="stylesheet" href="{% static 'planner/nav_spacing.css' %}?v=1">
|
||||
</head>
|
||||
<body data-theme="{{ user_appearance }}">
|
||||
<div class="app-shell">
|
||||
@@ -23,6 +24,8 @@
|
||||
<a href="{% url 'planner:task-list' %}">My tasks</a>
|
||||
<a id="daily-planner-nav" class="{% if onboarding_tour.target == 'daily-planner' %}onboarding-highlight{% endif %}" href="{% url 'planner:daily-planner' %}">Daily planner</a>
|
||||
<a id="health-nav" class="{% if onboarding_tour.target == 'wellbeing' %}onboarding-highlight{% endif %}" href="{% url 'planner:health' %}">Health</a>
|
||||
<a href="{% url 'stress:journal' %}"{% if request.resolver_match.namespace == 'stress' %} aria-current="page"{% endif %}>Stress</a>
|
||||
<a href="{% url 'dreams:journal' %}"{% if request.resolver_match.namespace == 'dreams' %} aria-current="page"{% endif %}>Dreams</a>
|
||||
<a href="{% url 'food:diary' %}">Food</a>
|
||||
<a href="{% url 'recipes:list' %}"{% if request.resolver_match.namespace == 'recipes' %} aria-current="page"{% endif %}>Recipes</a>
|
||||
<a href="{% url 'food:inventory' %}">Kitchen Inventory</a>
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'planner/checkin_sections.css' %}?v=2">
|
||||
<link rel="stylesheet" href="{% static 'planner/severity_scale.css' %}?v=1">
|
||||
<link rel="stylesheet" href="{% static 'stress/widget.css' %}?v=3">
|
||||
<section class="hero" aria-labelledby="health-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Personal health tracking</p>
|
||||
@@ -18,6 +19,7 @@
|
||||
{% include 'planner/partials/bowel_health_checkin.html' %}
|
||||
</div>
|
||||
<aside class="health-layout__sidebar" aria-label="Health routines">
|
||||
{% include 'stress/_daily_widget.html' with widget_id='health-stress-widget' return_to='health' %}
|
||||
{% include 'planner/partials/fasting_widget.html' %}
|
||||
{% include 'planner/partials/hydration_widget.html' %}
|
||||
</aside>
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
<form class="checkin-form checkin-form--sleep" method="post" action="{% url 'planner:sleep-checkin-save' %}" hx-post="{% url 'planner:sleep-checkin-save' %}" hx-target="#neck-headache-checkin" hx-swap="outerHTML" novalidate>
|
||||
{% csrf_token %}
|
||||
<h3 class="checkin-form__heading">Sleep</h3>
|
||||
<p class="sleep-dream-link">{% if selected_dream %}<a href="{% url 'dreams:detail' selected_dream.pk %}">Dream logged · {{ selected_dream.title }}</a>{% else %}<a href="{% url 'dreams:journal' %}?date={{ check_in_selected_date|date:'Y-m-d' }}">Log a dream for {{ check_in_selected_date|date:'j M Y' }}</a>{% endif %}</p>
|
||||
{% if sleep_check_in_form.non_field_errors %}<div class="form-errors">{{ sleep_check_in_form.non_field_errors }}</div>{% endif %}
|
||||
<div class="field{% if sleep_check_in_form.wake_up_date.errors %} field--error{% endif %}">{{ sleep_check_in_form.wake_up_date.label_tag }}{{ sleep_check_in_form.wake_up_date }}{% for error in sleep_check_in_form.wake_up_date.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
|
||||
<details class="checkin-score-details checkin-score-details--sleep" data-checkin-summary-panel data-checkin-kind="sleep"{% if sleep_check_in_form.rested_score.errors or sleep_check_in_form.watch_sleep_score.errors or sleep_check_in_form.note.errors %} open{% endif %}><summary><span class="checkin-score-details__title">Sleep scores</span><span class="checkin-score-details__summary" data-checkin-summary>No scores recorded</span></summary><div class="checkin-score-details__sleep-fields">
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
{% extends 'planner/base.html' %}
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
|
||||
{% block title %}My tasks · Tasknest{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'planner/severity_scale.css' %}?v=1">
|
||||
<link rel="stylesheet" href="{% static 'stress/widget.css' %}?v=3">
|
||||
<section class="hero" aria-labelledby="tasks-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Personal planning</p>
|
||||
@@ -13,7 +15,7 @@
|
||||
|
||||
{% if onboarding_tour %}{% include 'planner/partials/onboarding_tour.html' %}{% endif %}
|
||||
|
||||
{% if user.is_authenticated %}<div class="mobile-weather-slot">{% include 'planner/partials/weather_widget.html' with weather_heading_id='mobile-weather-heading' %}</div>{% endif %}
|
||||
{% if user.is_authenticated %}<div class="mobile-weather-slot">{% include 'planner/partials/weather_widget.html' with weather_heading_id='mobile-weather-heading' %}{% include 'stress/_daily_widget.html' with widget_id='mobile-stress-widget' return_to='mobile' %}</div>{% endif %}
|
||||
|
||||
<div class="home-layout">
|
||||
<div class="home-main">
|
||||
@@ -49,11 +51,12 @@
|
||||
</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>
|
||||
<div class="desktop-weather-slot">{% include 'planner/partials/weather_widget.html' %}{% include 'stress/_daily_widget.html' with widget_id='desktop-stress-widget' return_to='home' %}</div>
|
||||
{% include 'planner/partials/tooth_brushing_widget.html' %}
|
||||
{% include 'planner/partials/hydration_widget.html' %}
|
||||
{% include 'planner/partials/fasting_widget.html' %}
|
||||
</aside>
|
||||
{% endif %}
|
||||
</div>
|
||||
<script src="{% static 'planner/severity_scale.js' %}?v=2" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -24,6 +24,8 @@ from .forms import (
|
||||
)
|
||||
from .models import BowelHealthCheckIn, FastingPeriod, FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, ToothBrushing, UserSettings, Workout, WaterIntakeEntry
|
||||
from .services.hydration import hydration_context
|
||||
from stress.services import daily_widget_context
|
||||
from dreams.models import DreamEntry
|
||||
from .services.gitea_activity import activity_context
|
||||
from .services.notifications import NotificationError, send_ntfy_notification
|
||||
from .services.checkins import (
|
||||
@@ -191,6 +193,7 @@ def check_in_context(user, selected_date=None, form=None, sleep_form=None, activ
|
||||
sleep_check_in_by_date = {check_in.wake_up_date: check_in for check_in in sleep_check_ins}
|
||||
selected_check_in = check_in_by_date.get(selected_date)
|
||||
selected_sleep_check_in = sleep_check_in_by_date.get(selected_date)
|
||||
selected_dream = DreamEntry.objects.filter(user=user, wake_up_date=selected_date).first()
|
||||
|
||||
if form is None:
|
||||
form = NeckHeadacheCheckInForm(
|
||||
@@ -248,6 +251,7 @@ def check_in_context(user, selected_date=None, form=None, sleep_form=None, activ
|
||||
return {
|
||||
'check_in_form': form,
|
||||
'sleep_check_in_form': sleep_form,
|
||||
'selected_dream': selected_dream,
|
||||
'check_in_selected_date': selected_date,
|
||||
'check_in_today': today,
|
||||
'check_in_calendar_weeks': calendar_weeks,
|
||||
@@ -521,6 +525,7 @@ class TaskListView(LoginRequiredMixin, ListView):
|
||||
context.update(workout_context(self.request.user))
|
||||
context.update(brushing_context(self.request.user))
|
||||
context.update(hydration_context(self.request.user))
|
||||
context.update(daily_widget_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)
|
||||
@@ -547,6 +552,7 @@ class HealthView(LoginRequiredMixin, TemplateView):
|
||||
))
|
||||
context.update(fasting_widget_context(self.request.user))
|
||||
context.update(hydration_context(self.request.user))
|
||||
context.update(daily_widget_context(self.request.user))
|
||||
return context
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Owner-scoped stress journal API used by the MCP adapter."""
|
||||
from datetime import datetime, timedelta, time
|
||||
|
||||
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_symptoms, normalize_tags
|
||||
from .models import StressEntry
|
||||
|
||||
FIELDS = {'recorded_at', 'timing', 'score', 'note', 'tags', 'symptoms'}
|
||||
|
||||
|
||||
def serialize(entry):
|
||||
return {'id': str(entry.pk), 'recorded_at': entry.recorded_at.isoformat(),
|
||||
'timing': entry.timing, 'score': entry.score, 'note': entry.note,
|
||||
'tags': entry.tags, 'symptoms': entry.symptoms,
|
||||
'created_at': entry.created_at.isoformat(), 'updated_at': entry.updated_at.isoformat()}
|
||||
|
||||
|
||||
def validate(data, user):
|
||||
if unknown := set(data) - FIELDS:
|
||||
raise ValueError('Unknown fields: ' + ', '.join(sorted(unknown)))
|
||||
cleaned = {}
|
||||
if 'recorded_at' in data:
|
||||
value = parse_datetime(data['recorded_at']) if isinstance(data['recorded_at'], str) else None
|
||||
if value is None:
|
||||
raise ValueError('Use an ISO date and time for recorded_at.')
|
||||
if timezone.is_naive(value):
|
||||
value = timezone.make_aware(value, timezone_for_user(user))
|
||||
cleaned['recorded_at'] = value
|
||||
if 'timing' in data:
|
||||
if data['timing'] not in StressEntry.Timing.values:
|
||||
raise ValueError('Invalid timing.')
|
||||
cleaned['timing'] = data['timing']
|
||||
if 'score' in data:
|
||||
if isinstance(data['score'], bool) or not isinstance(data['score'], int) or not 0 <= data['score'] <= 10:
|
||||
raise ValueError('Score must be an integer from 0 to 10.')
|
||||
cleaned['score'] = data['score']
|
||||
if 'note' in data:
|
||||
if not isinstance(data['note'], str) or len(data['note']) > 2000:
|
||||
raise ValueError('Note must be text up to 2000 characters.')
|
||||
cleaned['note'] = data['note']
|
||||
if 'tags' in data:
|
||||
cleaned['tags'] = normalize_tags(data['tags'])
|
||||
if 'symptoms' in data:
|
||||
cleaned['symptoms'] = normalize_symptoms(data['symptoms'])
|
||||
return cleaned
|
||||
|
||||
|
||||
@api_view({'GET': 'journal:read', 'POST': 'journal:write'}, ('GET', 'POST'))
|
||||
def collection(request):
|
||||
if request.method == 'GET':
|
||||
entries = StressEntry.objects.filter(user=request.api_user)
|
||||
query = request.GET.get('query', '').strip()[:100]
|
||||
if query:
|
||||
entries = entries.filter(Q(note__icontains=query) | Q(tags__icontains=query))
|
||||
timing = request.GET.get('timing')
|
||||
if timing:
|
||||
if timing not in StressEntry.Timing.values:
|
||||
return error('invalid_timing', 'Invalid timing.')
|
||||
entries = entries.filter(timing=timing)
|
||||
date_text = request.GET.get('date')
|
||||
if date_text:
|
||||
day = parse_date(date_text)
|
||||
if day is None or day.isoformat() != date_text:
|
||||
return error('invalid_date', 'Use YYYY-MM-DD.')
|
||||
zone = timezone_for_user(request.api_user)
|
||||
start = timezone.make_aware(datetime.combine(day, time.min), zone)
|
||||
end = timezone.make_aware(datetime.combine(day + timedelta(days=1), time.min), zone)
|
||||
entries = entries.filter(recorded_at__gte=start, recorded_at__lt=end)
|
||||
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)
|
||||
if 'score' not in data:
|
||||
return error('missing_score', 'Score is required.')
|
||||
cleaned = validate(data, request.api_user)
|
||||
|
||||
def action():
|
||||
entry = StressEntry(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 = StressEntry.objects.filter(pk=identifier, user=request.api_user).first()
|
||||
if entry is None:
|
||||
return error('not_found', 'Stress entry not found.', 404)
|
||||
if request.method == 'GET':
|
||||
return JsonResponse(serialize(entry))
|
||||
if request.method == 'DELETE':
|
||||
entry.delete()
|
||||
return JsonResponse({'deleted': True})
|
||||
data = validate(_json(request), request.api_user)
|
||||
previous_score = entry.score
|
||||
for name, value in data.items():
|
||||
setattr(entry, name, value)
|
||||
if 'score' in data and entry.daily_date is not None:
|
||||
entry.record_score(data['score'], previous_score=previous_score)
|
||||
entry.full_clean()
|
||||
entry.save()
|
||||
return JsonResponse(serialize(entry))
|
||||
@@ -0,0 +1,78 @@
|
||||
from django import forms
|
||||
from django.utils import timezone
|
||||
|
||||
from .models import StressEntry
|
||||
|
||||
SYMPTOMS = (
|
||||
('tension', 'Tension'), ('headache', 'Headache'),
|
||||
('fatigue', 'Fatigue'), ('restlessness', 'Restlessness'),
|
||||
)
|
||||
|
||||
|
||||
def normalize_tags(value):
|
||||
if not isinstance(value, list) or len(value) > 12:
|
||||
raise forms.ValidationError('Use up to 12 tags.')
|
||||
tags = []
|
||||
for tag in value:
|
||||
if not isinstance(tag, str) or not tag.strip() or len(tag.strip()) > 40:
|
||||
raise forms.ValidationError('Each tag must be 1–40 characters.')
|
||||
name = tag.strip()
|
||||
if name.casefold() not in {item.casefold() for item in tags}:
|
||||
tags.append(name)
|
||||
return tags
|
||||
|
||||
|
||||
def normalize_symptoms(value):
|
||||
allowed = {key for key, _ in SYMPTOMS}
|
||||
if not isinstance(value, list) or any(item not in allowed for item in value):
|
||||
raise forms.ValidationError('Choose known symptoms.')
|
||||
return list(dict.fromkeys(value))
|
||||
|
||||
|
||||
class StressEntryForm(forms.ModelForm):
|
||||
recorded_at = forms.DateTimeField(
|
||||
label='When', 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='Stressors', max_length=500,
|
||||
help_text='Separate tags with commas, for example work, sensory overload.')
|
||||
symptoms = forms.MultipleChoiceField(required=False, choices=SYMPTOMS,
|
||||
widget=forms.CheckboxSelectMultiple, label='Physical symptoms')
|
||||
|
||||
class Meta:
|
||||
model = StressEntry
|
||||
fields = ('recorded_at', 'timing', 'score', 'note', 'symptoms')
|
||||
widgets = {
|
||||
'score': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}),
|
||||
'note': forms.Textarea(attrs={'rows': 3, 'placeholder': 'Optional note'}),
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['score'].label = 'Stress (0–10)'
|
||||
self.fields['timing'].label = 'When relative to sleep'
|
||||
if self.instance.pk:
|
||||
self.fields['recorded_at'].initial = timezone.localtime(self.instance.recorded_at)
|
||||
self.fields['tags_text'].initial = ', '.join(self.instance.tags)
|
||||
self.fields['symptoms'].initial = self.instance.symptoms
|
||||
elif not self.is_bound:
|
||||
self.fields['recorded_at'].initial = timezone.localtime(timezone.now())
|
||||
|
||||
def clean_tags_text(self):
|
||||
raw = self.cleaned_data['tags_text']
|
||||
return normalize_tags([part.strip() for part in raw.split(',') if part.strip()])
|
||||
|
||||
def clean_symptoms(self):
|
||||
return normalize_symptoms(self.cleaned_data['symptoms'])
|
||||
|
||||
def save(self, commit=True):
|
||||
previous_score = None
|
||||
if self.instance.pk and self.instance.daily_date is not None:
|
||||
previous_score = StressEntry.objects.only('score').get(pk=self.instance.pk).score
|
||||
entry = super().save(commit=False)
|
||||
if entry.daily_date is not None:
|
||||
entry.record_score(self.cleaned_data['score'], previous_score=previous_score)
|
||||
entry.tags = self.cleaned_data['tags_text']
|
||||
entry.symptoms = self.cleaned_data['symptoms']
|
||||
if commit:
|
||||
entry.save()
|
||||
return entry
|
||||
@@ -0,0 +1,39 @@
|
||||
# Generated by Django 6.1.1 on 2026-10-18 09:50
|
||||
|
||||
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='StressEntry',
|
||||
fields=[
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
||||
('recorded_at', models.DateTimeField(db_index=True, default=django.utils.timezone.now)),
|
||||
('timing', models.CharField(choices=[('anytime', 'Anytime'), ('before_sleep', 'Before sleep'), ('after_waking', 'After waking')], default='anytime', max_length=20)),
|
||||
('score', models.PositiveSmallIntegerField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)])),
|
||||
('note', models.TextField(blank=True, max_length=2000)),
|
||||
('tags', models.JSONField(blank=True, default=list)),
|
||||
('symptoms', models.JSONField(blank=True, default=list)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='stress_entries', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ('-recorded_at', '-created_at'),
|
||||
'indexes': [models.Index(fields=['user', '-recorded_at'], name='stress_stre_user_id_ff2c04_idx')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,29 @@
|
||||
# Generated by Django 6.1.1 on 2026-10-18 10:06
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('stress', '0001_initial'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='stressentry',
|
||||
name='daily_date',
|
||||
field=models.DateField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='stressentry',
|
||||
name='revisions',
|
||||
field=models.JSONField(blank=True, default=list),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='stressentry',
|
||||
constraint=models.UniqueConstraint(condition=models.Q(('daily_date__isnull', False)), fields=('user', 'daily_date'), name='stress_unique_daily_widget_entry'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,45 @@
|
||||
import uuid
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
from django.db import models
|
||||
from django.db.models import Q
|
||||
from django.utils import timezone
|
||||
|
||||
|
||||
class StressEntry(models.Model):
|
||||
class Timing(models.TextChoices):
|
||||
ANYTIME = 'anytime', 'Anytime'
|
||||
BEFORE_SLEEP = 'before_sleep', 'Before sleep'
|
||||
AFTER_WAKING = 'after_waking', 'After waking'
|
||||
|
||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='stress_entries')
|
||||
recorded_at = models.DateTimeField(default=timezone.now, db_index=True)
|
||||
timing = models.CharField(max_length=20, choices=Timing.choices, default=Timing.ANYTIME)
|
||||
score = models.PositiveSmallIntegerField(validators=[MinValueValidator(0), MaxValueValidator(10)])
|
||||
note = models.TextField(blank=True, max_length=2000)
|
||||
tags = models.JSONField(default=list, blank=True)
|
||||
symptoms = models.JSONField(default=list, blank=True)
|
||||
daily_date = models.DateField(null=True, blank=True)
|
||||
revisions = models.JSONField(default=list, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ('-recorded_at', '-created_at')
|
||||
indexes = [models.Index(fields=('user', '-recorded_at'))]
|
||||
constraints = [models.UniqueConstraint(fields=('user', 'daily_date'),
|
||||
condition=Q(daily_date__isnull=False), name='stress_unique_daily_widget_entry')]
|
||||
|
||||
def record_score(self, score, *, at=None, previous_score=None):
|
||||
"""Keep a compact, chronological score history for the daily widget row."""
|
||||
old_score = self.score if previous_score is None else previous_score
|
||||
if self.daily_date is not None and (not self.revisions or old_score != score):
|
||||
moment = at or timezone.now()
|
||||
self.revisions = [*self.revisions, {'score': score, 'time': moment.isoformat()}]
|
||||
self.recorded_at = moment
|
||||
self.score = score
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.score}/10 stress on {self.recorded_at:%Y-%m-%d %H:%M}'
|
||||
@@ -0,0 +1,47 @@
|
||||
"""One revisable daily stress score alongside freeform journal check-ins."""
|
||||
from datetime import datetime
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
|
||||
from planner.timezones import localdate_for_user, timezone_for_user
|
||||
from .models import StressEntry
|
||||
|
||||
|
||||
def daily_widget_context(user):
|
||||
day = localdate_for_user(user)
|
||||
entry = StressEntry.objects.filter(user=user, daily_date=day).first()
|
||||
revisions = []
|
||||
if entry:
|
||||
for revision in entry.revisions[-5:]:
|
||||
revisions.append({'score': revision['score'],
|
||||
'time': timezone.localtime(datetime.fromisoformat(revision['time']),
|
||||
timezone_for_user(user))})
|
||||
return {'stress_daily_date': day,
|
||||
'stress_daily_entry': entry, 'stress_daily_revisions': revisions}
|
||||
|
||||
|
||||
def save_daily_entry(user, *, score, timing='anytime', note='', stressor=''):
|
||||
if isinstance(score, bool) or not isinstance(score, int) or not 0 <= score <= 10:
|
||||
raise ValidationError('Choose a stress score from 0 to 10.')
|
||||
if timing not in StressEntry.Timing.values:
|
||||
raise ValidationError('Choose when the stress was felt.')
|
||||
if not isinstance(note, str) or len(note) > 200:
|
||||
raise ValidationError('Keep the note under 200 characters.')
|
||||
if not isinstance(stressor, str) or len(stressor.strip()) > 40:
|
||||
raise ValidationError('Keep the stressor under 40 characters.')
|
||||
day = localdate_for_user(user)
|
||||
moment = timezone.now()
|
||||
with transaction.atomic():
|
||||
get_user_model().objects.select_for_update().get(pk=user.pk)
|
||||
entry, _ = StressEntry.objects.select_for_update().get_or_create(
|
||||
user=user, daily_date=day,
|
||||
defaults={'score': score, 'recorded_at': moment})
|
||||
entry.record_score(score, at=moment)
|
||||
entry.timing = timing
|
||||
entry.note = note.strip()
|
||||
entry.tags = [stressor.strip()] if stressor.strip() else []
|
||||
entry.full_clean()
|
||||
entry.save()
|
||||
return entry
|
||||
@@ -0,0 +1,8 @@
|
||||
.stress-page{max-width:1200px;margin:0 auto;padding:1.5rem 0 4rem;color:var(--stress-ink)}
|
||||
body[data-theme=light]{--stress-surface:#fff;--stress-border:#dfe4dc;--stress-ink:#25292e;--stress-muted:#626a70;--stress-soft:#edf4ef;--stress-accent:#276a53}
|
||||
body[data-theme=dark]{--stress-surface:#202923;--stress-border:#3b473f;--stress-ink:#edf5ef;--stress-muted:#b8c3bb;--stress-soft:#2a3b31;--stress-accent:#8bd1a4}
|
||||
.stress-header{margin-bottom:1.5rem}.stress-header h1{font-size:clamp(2rem,4vw,3rem);margin:.2rem 0}.stress-header p:last-child{max-width:65ch;color:var(--stress-muted)}
|
||||
.stress-layout{display:grid;grid-template-columns:minmax(0,1fr) minmax(270px,330px);gap:1.3rem;align-items:start}.stress-main,.stress-side{min-width:0}.stress-panel{background:var(--stress-surface);border:1px solid var(--stress-border);border-radius:1.2rem;padding:1.2rem;margin-bottom:1rem}.stress-panel h2{margin:0 0 .5rem;font-size:1.3rem}.stress-muted{color:var(--stress-muted);font-size:.9rem;line-height:1.45}.stress-form-grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin:1rem 0}.stress-field{min-width:0}.stress-field--wide{grid-column:1/-1}.stress-field>label{display:block;font-weight:650;margin-bottom:.3rem}.stress-field input:not([type=checkbox]),.stress-field select,.stress-field textarea,.stress-filter input,.stress-filter select{width:100%;max-width:100%;min-height:44px;padding:.55rem;border:1px solid var(--stress-border);border-radius:.55rem;background:var(--stress-surface);color:var(--stress-ink);font:inherit}.stress-field textarea{resize:vertical}.stress-field small{display:block;color:var(--stress-muted);margin-top:.25rem}.stress-field fieldset{border:0;padding:0;margin:0}.stress-field legend{font-weight:650;margin-bottom:.35rem}.stress-field fieldset>div{display:flex;flex-wrap:wrap;gap:.5rem 1rem}.stress-field fieldset label{display:inline-flex;align-items:center;gap:.35rem;min-height:44px}.stress-errors{color:#a83127;margin:.3rem 0}.stress-filter{display:flex;flex-wrap:wrap;align-items:end;gap:.6rem;margin:1rem 0}.stress-filter label{flex:1;min-width:150px;font-size:.85rem;font-weight:650}.stress-filter a{align-self:center}.stress-entries{list-style:none;margin:0;padding:0;display:grid;gap:.7rem}.stress-entry{border:1px solid var(--stress-border);border-radius:.8rem;padding:.8rem;overflow-wrap:anywhere}.stress-entry__top{display:flex;align-items:center;gap:.8rem}.stress-entry__top>div{flex:1}.stress-entry__top time{display:block;color:var(--stress-muted);font-size:.82rem}.stress-score{display:grid;place-items:center;align-content:center;flex:none;width:54px;height:54px;border-radius:50%;background:var(--stress-soft);color:var(--stress-accent);font-size:1.25rem;line-height:1}.stress-score small{font-size:.65rem}.stress-entry p{margin:.65rem 0 0}.stress-chips{display:flex;gap:.3rem;flex-wrap:wrap}.stress-chips span{padding:.2rem .55rem;border-radius:999px;background:var(--stress-soft);font-size:.75rem}.stress-empty{color:var(--stress-muted);padding:1rem;border:1px dashed var(--stress-border);border-radius:.8rem}.stress-stats{display:grid;gap:.8rem}.stress-stats>div{padding:.75rem;background:var(--stress-soft);border-radius:.7rem}.stress-stats p{margin:.3rem 0}.stress-calendar{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));gap:.3rem}.stress-calendar a{display:grid;place-items:center;align-content:center;aspect-ratio:1;text-decoration:none;color:var(--stress-ink);border:1px solid var(--stress-border);border-radius:.45rem;font-size:.78rem}.stress-calendar a.has-entry{background:var(--stress-soft);border-color:var(--stress-accent)}.stress-calendar a.is-selected{outline:2px solid var(--stress-accent)}.stress-calendar small{font-size:.6rem}.stress-edit{max-width:700px}.stress-edit>a{display:inline-block;margin-bottom:1rem}.stress-delete{border-color:#b46b64}.stress-page :is(a,button,input,select,textarea):focus-visible{outline:2px solid var(--stress-accent);outline-offset:2px}
|
||||
@media(max-width:800px){.stress-layout{grid-template-columns:1fr}.stress-side{display:grid;grid-template-columns:1fr 1fr;gap:1rem}.stress-side .stress-panel{margin:0}}
|
||||
@media(max-width:600px){.stress-page{padding-top:.5rem}.stress-side{grid-template-columns:1fr}.stress-form-grid{grid-template-columns:1fr}.stress-field--wide{grid-column:auto}.stress-panel{padding:1rem}.stress-entry__top{align-items:flex-start}.stress-filter label{min-width:100%}}
|
||||
.stress-comparison-list{max-height:22rem;overflow:auto}.stress-comparison-list p{border-top:1px solid var(--stress-border);padding:.65rem 0;margin:0;overflow-wrap:anywhere}.stress-comparison-list small{color:var(--stress-muted)}.sleep-dream-link{margin:.35rem 0 1rem}
|
||||
@@ -0,0 +1,30 @@
|
||||
.stress-widget{margin-bottom:16px;min-width:0}
|
||||
.stress-widget__heading{display:flex;justify-content:space-between;align-items:baseline;gap:.5rem}
|
||||
.stress-widget__heading h2{margin:0}
|
||||
.stress-widget__heading a{color:#b8e2c4;font-size:.82rem;font-weight:700}
|
||||
.stress-widget__date,.stress-widget__saved{color:#b8cbbd;font-size:.78rem;margin:.25rem 0 .8rem}
|
||||
.stress-widget__saved{margin:.8rem 0 0}
|
||||
.stress-widget form{display:grid;gap:.65rem}
|
||||
.stress-widget__score label,.stress-widget__field{display:block;color:#edf5ef;font-size:.82rem;font-weight:650}
|
||||
.stress-widget__field span{font-weight:400;color:#b8cbbd}
|
||||
.stress-widget__field input,.stress-widget__field select,.stress-widget__score input:not([type=hidden]){display:block;width:100%;min-height:40px;margin-top:.2rem;padding:.4rem .55rem;border:1px solid #587063;border-radius:.55rem;background:#27382e;color:#edf5ef;font:inherit}
|
||||
.stress-widget .severity-scale{margin:.2rem 0 0}
|
||||
.stress-widget .severity-scale__value{color:#edf5ef}
|
||||
.stress-widget .severity-scale--unset .severity-scale__value,.stress-widget .severity-scale__ends{color:#b8cbbd}
|
||||
.stress-widget .button{justify-self:start;min-height:40px}
|
||||
.stress-widget__optional{color:#cddbd0;font-size:.82rem}
|
||||
.stress-widget__optional summary{cursor:pointer;font-weight:650;min-height:32px;align-content:center}
|
||||
.stress-widget__optional summary span{font-weight:400;color:#b8cbbd}
|
||||
.stress-widget__optional .stress-widget__field{margin-top:.55rem}
|
||||
.stress-widget__history{border-top:1px solid #4a5e50;margin-top:.75rem;padding-top:.65rem;color:#cddbd0;font-size:.78rem}
|
||||
.stress-widget__history summary{cursor:pointer;font-weight:650}
|
||||
.stress-widget__history ol{margin:.4rem 0 0;padding-left:1.4rem}
|
||||
.stress-widget__field :is(input,select):focus-visible,.stress-widget a:focus-visible,.stress-widget button:focus-visible{outline:2px solid #b8e2c4;outline-offset:2px}
|
||||
body[data-theme=light] .stress-widget__heading a{color:#276a46}
|
||||
body[data-theme=light] .stress-widget__date,body[data-theme=light] .stress-widget__saved,body[data-theme=light] .stress-widget__field span,body[data-theme=light] .stress-widget__optional summary span{color:#526758}
|
||||
body[data-theme=light] .stress-widget__score label,body[data-theme=light] .stress-widget__field,body[data-theme=light] .stress-widget__optional{color:#253a2d}
|
||||
body[data-theme=light] .stress-widget__field input,body[data-theme=light] .stress-widget__field select,body[data-theme=light] .stress-widget__score input:not([type=hidden]){border-color:#abc5af;background:#fff;color:#213a2b}
|
||||
body[data-theme=light] .stress-widget .severity-scale__value{color:#263b30}
|
||||
body[data-theme=light] .stress-widget .severity-scale--unset .severity-scale__value,body[data-theme=light] .stress-widget .severity-scale__ends{color:#58675e}
|
||||
body[data-theme=light] .stress-widget__history{border-color:#d2e2d4;color:#526758}
|
||||
body[data-theme=light] .stress-widget__field :is(input,select):focus-visible,body[data-theme=light] .stress-widget a:focus-visible,body[data-theme=light] .stress-widget button:focus-visible{outline-color:#376e49}
|
||||
@@ -0,0 +1,17 @@
|
||||
<article id="{{ widget_id }}" class="hydration-widget stress-widget" aria-labelledby="{{ widget_id }}-heading">
|
||||
<p class="eyebrow">Daily check-in</p>
|
||||
<div class="stress-widget__heading"><h2 id="{{ widget_id }}-heading">Stress</h2><a href="{% url 'stress:journal' %}">Journal</a></div>
|
||||
<p class="stress-widget__date">{{ stress_daily_date|date:'l, j F' }}</p>
|
||||
<form method="post" action="{% url 'stress:daily-save' %}">
|
||||
{% csrf_token %}<input type="hidden" name="return_to" value="{{ return_to }}">
|
||||
<div class="field stress-widget__score"><label for="{{ widget_id }}-score">How stressed? (0–10)</label><input id="{{ widget_id }}-score" name="score" type="number" min="0" max="10" step="1" inputmode="numeric" data-severity-scale="symptom" {% if stress_daily_entry %}value="{{ stress_daily_entry.score }}"{% endif %} required></div>
|
||||
<label class="stress-widget__field" for="{{ widget_id }}-timing">When relative to sleep<select id="{{ widget_id }}-timing" name="timing"><option value="anytime"{% if not stress_daily_entry or stress_daily_entry.timing == 'anytime' %} selected{% endif %}>Anytime</option><option value="before_sleep"{% if stress_daily_entry.timing == 'before_sleep' %} selected{% endif %}>Before sleep</option><option value="after_waking"{% if stress_daily_entry.timing == 'after_waking' %} selected{% endif %}>After waking</option></select></label>
|
||||
<details class="stress-widget__optional"><summary>{% if stress_daily_entry.note or stress_daily_entry.tags %}Edit context{% else %}Add context{% endif %} <span>(optional)</span></summary>
|
||||
<label class="stress-widget__field" for="{{ widget_id }}-stressor">Stressor<input id="{{ widget_id }}-stressor" name="stressor" maxlength="40" value="{{ stress_daily_entry.tags|first|default:'' }}" placeholder="e.g. work"></label>
|
||||
<label class="stress-widget__field" for="{{ widget_id }}-note">Brief note<input id="{{ widget_id }}-note" name="note" maxlength="200" value="{{ stress_daily_entry.note|default:'' }}" placeholder="What is on your mind?"></label>
|
||||
</details>
|
||||
<button class="button button--compact" type="submit">{% if stress_daily_entry %}Update today{% else %}Save today{% endif %}</button>
|
||||
</form>
|
||||
{% if stress_daily_entry %}<p class="stress-widget__saved">Latest score: <strong>{{ stress_daily_entry.score }}/10</strong> · updated {{ stress_daily_entry.recorded_at|date:'H:i' }}</p>{% else %}<p class="stress-widget__saved">No score logged today.</p>{% endif %}
|
||||
{% if stress_daily_revisions|length > 1 %}<details class="stress-widget__history"><summary>Score changes today</summary><ol>{% for revision in stress_daily_revisions %}<li>{{ revision.score }}/10 at {{ revision.time|date:'H:i' }}</li>{% endfor %}</ol></details>{% endif %}
|
||||
</article>
|
||||
@@ -0,0 +1,12 @@
|
||||
{% csrf_token %}
|
||||
{% if form.non_field_errors %}<div class="stress-errors" role="alert">{{ form.non_field_errors }}</div>{% endif %}
|
||||
<div class="stress-form-grid">
|
||||
{% for field in form %}
|
||||
<div class="stress-field{% if field.name == 'note' or field.name == 'tags_text' or field.name == 'symptoms' %} stress-field--wide{% endif %}">
|
||||
{% if field.name == 'symptoms' %}<fieldset><legend>{{ field.label }}</legend>{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}</fieldset>
|
||||
{% else %}{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{% endif %}
|
||||
{% if field.errors %}<div class="stress-errors" role="alert">{{ field.errors }}</div>{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<button class="button" type="submit">{{ submit_label }}</button>
|
||||
@@ -0,0 +1,10 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Edit stress check-in · Tasknest{% endblock %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'stress/stress.css' %}?v=1">
|
||||
<div class="stress-page stress-edit">
|
||||
<a href="{% url 'stress:journal' %}">← Stress journal</a>
|
||||
<section class="stress-panel"><h1>Edit check-in</h1><form method="post">{% include 'stress/_form.html' with submit_label='Save changes' %}</form></section>
|
||||
<section class="stress-panel stress-delete"><h2>Delete check-in</h2><p>This permanently removes this check-in.</p><form method="post" action="{% url 'stress:delete' entry.pk %}" onsubmit="return confirm('Delete this stress check-in?')">{% csrf_token %}<button class="button button--secondary" type="submit">Delete check-in</button></form></section>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,50 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Stress journal · Tasknest{% endblock %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'stress/stress.css' %}?v=1">
|
||||
<div class="stress-page">
|
||||
<header class="stress-header">
|
||||
<p class="eyebrow">Private check-ins</p>
|
||||
<h1>Stress journal</h1>
|
||||
<p>Capture how you feel when it happens. A before-sleep check-in is kept distinct from how you feel after waking.</p>
|
||||
</header>
|
||||
<div class="stress-layout">
|
||||
<div class="stress-main">
|
||||
<section class="stress-panel" aria-labelledby="stress-log-title">
|
||||
<h2 id="stress-log-title">Log stress</h2>
|
||||
<p class="stress-muted">More than one check-in per day is welcome. Notes, stressors, and symptoms are optional.</p>
|
||||
<form method="post">{% include 'stress/_form.html' with submit_label='Save check-in' %}</form>
|
||||
</section>
|
||||
<section class="stress-panel" aria-labelledby="stress-history-title">
|
||||
<div class="stress-section-head"><div><h2 id="stress-history-title">History</h2><p class="stress-muted">Your latest check-ins, newest first.</p></div></div>
|
||||
<form class="stress-filter" method="get" aria-label="Filter stress history">
|
||||
<label>Search notes or tags <input type="search" name="q" value="{{ query }}"></label>
|
||||
<label>Timing <select name="timing"><option value="">All times</option><option value="before_sleep"{% if timing == 'before_sleep' %} selected{% endif %}>Before sleep</option><option value="after_waking"{% if timing == 'after_waking' %} selected{% endif %}>After waking</option><option value="anytime"{% if timing == 'anytime' %} selected{% endif %}>Anytime</option></select></label>
|
||||
{% if selected_day %}<input type="hidden" name="date" value="{{ selected_day|date:'Y-m-d' }}">{% endif %}
|
||||
<button class="button button--secondary" type="submit">Filter</button>
|
||||
{% if query or timing or selected_day %}<a href="{% url 'stress:journal' %}">Clear filters</a>{% endif %}
|
||||
</form>
|
||||
{% if selected_day %}<p>Showing {{ selected_day|date:'j F Y' }}.</p>{% endif %}
|
||||
<ol class="stress-entries">
|
||||
{% for entry in entries %}
|
||||
<li class="stress-entry">
|
||||
<div class="stress-entry__top"><strong class="stress-score">{{ entry.score }}<small>/10</small></strong><div><strong>{{ entry.get_timing_display }}</strong><time datetime="{{ entry.recorded_at|date:'c' }}">{{ entry.recorded_at|date:'j M Y, H:i' }}</time></div><a href="{% url 'stress:edit' entry.pk %}">Edit</a></div>
|
||||
{% if entry.note %}<p>{{ entry.note|linebreaksbr }}</p>{% endif %}
|
||||
{% if entry.tags %}<p class="stress-chips" aria-label="Stressors">{% for tag in entry.tags %}<span>{{ tag }}</span>{% endfor %}</p>{% endif %}
|
||||
{% if entry.symptoms %}<p class="stress-muted">Symptoms: {{ entry.symptoms|join:', ' }}</p>{% endif %}
|
||||
</li>
|
||||
{% empty %}<li class="stress-empty">No check-ins match this view.</li>{% endfor %}
|
||||
</ol>
|
||||
</section>
|
||||
</div>
|
||||
<aside class="stress-side" aria-label="Stress patterns">
|
||||
<section class="stress-panel"><h2>Patterns</h2><p class="stress-muted">Descriptive averages only. Stress can change after a difficult dream; these numbers do not show cause and effect.</p>
|
||||
<div class="stress-stats"><div><strong>Past 7 days</strong><p>{{ week.count }} check-in{{ week.count|pluralize }}</p><p>Before sleep: {% if week.before_average is not None %}{{ week.before_average }}/10{% else %}—{% endif %}</p><p>After waking: {% if week.after_average is not None %}{{ week.after_average }}/10{% else %}—{% endif %}</p></div><div><strong>Past 30 days</strong><p>{{ month.count }} check-in{{ month.count|pluralize }}</p><p>Before sleep: {% if month.before_average is not None %}{{ month.before_average }}/10{% else %}—{% endif %}</p><p>After waking: {% if month.after_average is not None %}{{ month.after_average }}/10{% else %}—{% endif %}</p></div></div>
|
||||
<h3>Dreams and nearby stress</h3><p class="stress-muted">Dreams use their wake-up date. “Before sleep” is from the previous calendar day; “after waking” is from the wake-up day. These are nearby reports, not evidence of cause.</p>
|
||||
{% if dream_comparisons %}<div class="stress-comparison-list">{% for row in dream_comparisons %}<p><a href="{% url 'dreams:detail' row.dream.pk %}">{{ row.dream.wake_up_date|date:'j M' }} · {{ row.dream.title }}</a>{% if row.dream.is_nightmare %} · Nightmare{% endif %}{% if row.dream.vividness is not None %} · Vividness {{ row.dream.vividness }}/10{% endif %}<br><small>Before sleep: {% if row.before_score is not None %}{{ row.before_score }}/10{% else %}—{% endif %} · After waking: {% if row.after_score is not None %}{{ row.after_score }}/10{% else %}—{% endif %}</small></p>{% endfor %}</div>{% else %}<p class="stress-muted">No dreams logged in the past 30 days.</p>{% endif %}
|
||||
</section>
|
||||
<section class="stress-panel"><h2>Past 30 days</h2><p class="stress-muted">Choose a day to see its check-ins.</p><div class="stress-calendar">{% for day in calendar %}<a href="?date={{ day.date|date:'Y-m-d' }}#stress-history-title" aria-label="{{ day.date|date:'j F Y' }}: {{ day.count }} check-in{{ day.count|pluralize }}" class="{% if day.count %}has-entry{% endif %}{% if selected_day == day.date %} is-selected{% endif %}"><span>{{ day.date|date:'j' }}</span>{% if day.count %}<small>{{ day.count }}</small>{% endif %}</a>{% endfor %}</div></section>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,133 @@
|
||||
import json
|
||||
from datetime import datetime, timezone as datetime_timezone
|
||||
from unittest.mock import patch
|
||||
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 .services import save_daily_entry
|
||||
from .models import StressEntry
|
||||
|
||||
|
||||
class StressJournalTests(TestCase):
|
||||
def setUp(self):
|
||||
users = get_user_model()
|
||||
self.user = users.objects.create_user(username='stress-one', password='test-password')
|
||||
self.other = users.objects.create_user(username='stress-two', password='test-password')
|
||||
|
||||
def test_multiple_checkins_web_edit_and_owner_isolation(self):
|
||||
self.client.force_login(self.user)
|
||||
url = reverse('stress:journal')
|
||||
for score, timing in ((7, 'before_sleep'), (3, 'after_waking')):
|
||||
response = self.client.post(url, {
|
||||
'recorded_at': '2026-10-18T08:00', 'timing': timing, 'score': score,
|
||||
'note': 'Some stress', 'tags_text': 'work, sensory overload',
|
||||
'symptoms': ['tension'],
|
||||
})
|
||||
self.assertEqual(response.status_code, 302)
|
||||
self.assertEqual(StressEntry.objects.filter(user=self.user).count(), 2)
|
||||
entry = StressEntry.objects.filter(user=self.user, timing='before_sleep').get()
|
||||
self.assertEqual(entry.tags, ['work', 'sensory overload'])
|
||||
self.assertEqual(entry.symptoms, ['tension'])
|
||||
self.assertContains(self.client.get(url), 'Before sleep: 7/10')
|
||||
self.assertContains(self.client.get(url), 'After waking: 3/10')
|
||||
self.assertEqual(self.client.get(reverse('stress:edit', args=[entry.pk])).status_code, 200)
|
||||
self.client.force_login(self.other)
|
||||
self.assertEqual(self.client.get(reverse('stress:edit', args=[entry.pk])).status_code, 404)
|
||||
self.assertEqual(self.client.post(reverse('stress:delete', args=[entry.pk])).status_code, 404)
|
||||
self.assertNotContains(self.client.get(url), 'Some stress')
|
||||
|
||||
def test_api_scopes_idempotency_search_update_and_delete(self):
|
||||
_, secret = create_token(self.user, 'Stress test', ['journal:read', 'journal:write'])
|
||||
headers = {'HTTP_AUTHORIZATION': f'Bearer {secret}'}
|
||||
url = '/api/v1/stress/'
|
||||
payload = {'score': 8, 'timing': 'before_sleep', 'note': 'Work deadline',
|
||||
'recorded_at': '2026-10-17T22:30:00', 'tags': ['work'], 'symptoms': ['tension']}
|
||||
options = {**headers, 'HTTP_IDEMPOTENCY_KEY': 'stress-test-1', 'content_type': 'application/json'}
|
||||
created = self.client.post(url, data=json.dumps(payload), **options)
|
||||
self.assertEqual(created.status_code, 201)
|
||||
entry_id = created.json()['id']
|
||||
self.assertEqual(self.client.post(url, data=json.dumps(payload), **options).json()['id'], entry_id)
|
||||
self.assertEqual(StressEntry.objects.count(), 1)
|
||||
self.assertEqual(self.client.post(url, data=json.dumps({**payload, 'score': 9}), **options).status_code, 409)
|
||||
self.assertEqual(self.client.get(url, {'date': '2026-10-17', 'timing': 'before_sleep'}, **headers).json()['total'], 1)
|
||||
detail = f'{url}{entry_id}/'
|
||||
changed = self.client.patch(detail, data=json.dumps({'note': 'Deadline moved'}),
|
||||
content_type='application/json', **headers)
|
||||
self.assertEqual(changed.status_code, 200)
|
||||
self.assertEqual(changed.json()['score'], 8)
|
||||
self.assertEqual(changed.json()['note'], 'Deadline moved')
|
||||
_, other_secret = create_token(self.other, 'Stress test', ['journal:read', 'journal:write'])
|
||||
other_headers = {'HTTP_AUTHORIZATION': f'Bearer {other_secret}'}
|
||||
self.assertEqual(self.client.get(detail, **other_headers).status_code, 404)
|
||||
self.assertEqual(self.client.delete(detail, **other_headers).status_code, 404)
|
||||
self.assertEqual(self.client.get(url, **other_headers).json()['total'], 0)
|
||||
self.assertEqual(self.client.delete(detail, **headers).status_code, 200)
|
||||
self.assertEqual(StressEntry.objects.count(), 0)
|
||||
|
||||
def test_api_rejects_invalid_score_and_read_only_token(self):
|
||||
_, secret = create_token(self.user, 'Read only', ['journal:read'])
|
||||
headers = {'HTTP_AUTHORIZATION': f'Bearer {secret}'}
|
||||
self.assertEqual(self.client.post('/api/v1/stress/', data=json.dumps({'score': 7}),
|
||||
content_type='application/json', **headers).status_code, 403)
|
||||
_, write_secret = create_token(self.user, 'Write', ['journal:write'])
|
||||
write_headers = {'HTTP_AUTHORIZATION': f'Bearer {write_secret}'}
|
||||
self.assertEqual(self.client.post('/api/v1/stress/', data=json.dumps({'score': 11}),
|
||||
content_type='application/json', **write_headers).status_code, 400)
|
||||
self.assertEqual(self.client.get('/api/v1/stress/', **write_headers).status_code, 403)
|
||||
|
||||
def test_daily_widget_revises_one_row_without_duplicate_scores(self):
|
||||
UserSettings.objects.create(user=self.user, time_zone='Europe/Amsterdam')
|
||||
first = datetime(2026, 10, 18, 19, 30, tzinfo=datetime_timezone.utc)
|
||||
second = datetime(2026, 10, 18, 20, 10, tzinfo=datetime_timezone.utc)
|
||||
next_day = datetime(2026, 10, 18, 22, 30, tzinfo=datetime_timezone.utc)
|
||||
with patch('stress.services.timezone.now', return_value=first):
|
||||
entry = save_daily_entry(self.user, score=4, timing='before_sleep', note='Busy day', stressor='work')
|
||||
with patch('stress.services.timezone.now', return_value=second):
|
||||
updated = save_daily_entry(self.user, score=6, timing='before_sleep', note='A bit calmer', stressor='work')
|
||||
save_daily_entry(self.user, score=6, timing='before_sleep', note='Same score', stressor='work')
|
||||
updated.refresh_from_db()
|
||||
self.assertEqual(updated.pk, entry.pk)
|
||||
self.assertEqual(updated.daily_date.isoformat(), '2026-10-18')
|
||||
self.assertEqual([revision['score'] for revision in updated.revisions], [4, 6])
|
||||
self.assertEqual(updated.revisions[0]['time'], first.isoformat())
|
||||
self.assertEqual(updated.revisions[1]['time'], second.isoformat())
|
||||
self.assertEqual(updated.note, 'Same score')
|
||||
with patch('stress.services.timezone.now', return_value=next_day):
|
||||
tomorrow = save_daily_entry(self.user, score=3)
|
||||
self.assertNotEqual(tomorrow.pk, entry.pk)
|
||||
self.assertEqual(tomorrow.daily_date.isoformat(), '2026-10-19')
|
||||
self.assertEqual(StressEntry.objects.filter(user=self.user, daily_date__isnull=False).count(), 2)
|
||||
|
||||
def test_daily_widget_post_and_health_access(self):
|
||||
self.client.force_login(self.user)
|
||||
home = self.client.get(reverse('planner:task-list'))
|
||||
self.assertContains(home, 'desktop-stress-widget')
|
||||
self.assertContains(home, 'mobile-stress-widget')
|
||||
self.assertContains(self.client.get(reverse('planner:health')), 'health-stress-widget')
|
||||
response = self.client.post(reverse('stress:daily-save'), {
|
||||
'score': '0', 'timing': 'after_waking', 'note': 'Quiet', 'stressor': 'sleep', 'return_to': 'home'})
|
||||
self.assertEqual(response.status_code, 302)
|
||||
entry = StressEntry.objects.get(user=self.user, daily_date__isnull=False)
|
||||
self.assertEqual(entry.score, 0)
|
||||
self.assertEqual(entry.revisions[0]['score'], 0)
|
||||
self.client.post(reverse('stress:daily-save'), {
|
||||
'score': '2', 'timing': 'after_waking', 'note': 'Later', 'return_to': 'health'})
|
||||
entry.refresh_from_db()
|
||||
self.assertEqual(entry.score, 2)
|
||||
self.assertEqual(len(entry.revisions), 2)
|
||||
self.assertEqual(StressEntry.objects.filter(user=self.user).count(), 1)
|
||||
self.assertEqual(self.client.post(reverse('stress:daily-save'), {'score': '11'}).status_code, 302)
|
||||
self.assertEqual(StressEntry.objects.filter(user=self.user).count(), 1)
|
||||
|
||||
def test_api_change_to_daily_score_keeps_revision_history(self):
|
||||
entry = save_daily_entry(self.user, score=4)
|
||||
_, secret = create_token(self.user, 'Journal write', ['journal:write'])
|
||||
response = self.client.patch(f'/api/v1/stress/{entry.pk}/', data=json.dumps({'score': 7}),
|
||||
content_type='application/json', HTTP_AUTHORIZATION=f'Bearer {secret}')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
entry.refresh_from_db()
|
||||
self.assertEqual(entry.score, 7)
|
||||
self.assertEqual([item['score'] for item in entry.revisions], [4, 7])
|
||||
@@ -0,0 +1,11 @@
|
||||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
|
||||
app_name = 'stress'
|
||||
urlpatterns = [
|
||||
path('', views.journal, name='journal'),
|
||||
path('daily/save/', views.daily_save, name='daily-save'),
|
||||
path('<uuid:identifier>/edit/', views.edit, name='edit'),
|
||||
path('<uuid:identifier>/delete/', views.delete, name='delete'),
|
||||
]
|
||||
@@ -0,0 +1,139 @@
|
||||
from datetime import datetime, timedelta, time
|
||||
from statistics import mean
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.contrib import messages
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db.models import Q
|
||||
from django.http import Http404
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
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, timezone_for_user
|
||||
from dreams.models import DreamEntry
|
||||
from .forms import StressEntryForm
|
||||
from .models import StressEntry
|
||||
from .services import save_daily_entry
|
||||
|
||||
|
||||
def _local_bounds(day, user):
|
||||
zone = timezone_for_user(user)
|
||||
return (timezone.make_aware(datetime.combine(day, time.min), zone),
|
||||
timezone.make_aware(datetime.combine(day + timedelta(days=1), time.min), zone))
|
||||
|
||||
|
||||
def _summary(entries, days):
|
||||
recent = [entry for entry in entries if entry.recorded_at >= days]
|
||||
before = [entry.score for entry in recent if entry.timing == StressEntry.Timing.BEFORE_SLEEP]
|
||||
after = [entry.score for entry in recent if entry.timing == StressEntry.Timing.AFTER_WAKING]
|
||||
return {'count': len(recent), 'before_average': round(mean(before), 1) if before else None,
|
||||
'after_average': round(mean(after), 1) if after else None}
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def journal(request):
|
||||
if request.method == 'POST':
|
||||
form = StressEntryForm(request.POST)
|
||||
if form.is_valid():
|
||||
entry = form.save(commit=False)
|
||||
entry.user = request.user
|
||||
entry.save()
|
||||
return redirect('stress:journal')
|
||||
else:
|
||||
form = StressEntryForm()
|
||||
|
||||
today = localdate_for_user(request.user)
|
||||
period_start, _ = _local_bounds(today - timedelta(days=29), request.user)
|
||||
_, period_end = _local_bounds(today, request.user)
|
||||
all_recent = list(StressEntry.objects.filter(user=request.user, recorded_at__gte=period_start,
|
||||
recorded_at__lt=period_end))
|
||||
week_start, _ = _local_bounds(today - timedelta(days=6), request.user)
|
||||
query = request.GET.get('q', '').strip()[:100]
|
||||
timing = request.GET.get('timing', '')
|
||||
day_text = request.GET.get('date', '')
|
||||
selected_day = parse_date(day_text) if day_text else None
|
||||
if day_text and (selected_day is None or selected_day.isoformat() != day_text):
|
||||
raise Http404('Invalid date')
|
||||
entries = StressEntry.objects.filter(user=request.user)
|
||||
if query:
|
||||
entries = entries.filter(Q(note__icontains=query) | Q(tags__icontains=query))
|
||||
if timing in StressEntry.Timing.values:
|
||||
entries = entries.filter(timing=timing)
|
||||
if selected_day:
|
||||
start, end = _local_bounds(selected_day, request.user)
|
||||
entries = entries.filter(recorded_at__gte=start, recorded_at__lt=end)
|
||||
entries = list(entries[:80])
|
||||
counts = {}
|
||||
for entry in all_recent:
|
||||
date = timezone.localtime(entry.recorded_at, timezone_for_user(request.user)).date()
|
||||
counts[date] = counts.get(date, 0) + 1
|
||||
calendar = [{'date': today - timedelta(days=offset),
|
||||
'count': counts.get(today - timedelta(days=offset), 0)}
|
||||
for offset in range(29, -1, -1)]
|
||||
dreams = list(DreamEntry.objects.filter(user=request.user,
|
||||
wake_up_date__range=(today - timedelta(days=29), today))[:30])
|
||||
comparison_start, _ = _local_bounds(today - timedelta(days=30), request.user)
|
||||
nearby_stress = StressEntry.objects.filter(user=request.user, recorded_at__gte=comparison_start,
|
||||
recorded_at__lt=period_end)
|
||||
stress_by_day = {}
|
||||
for entry in nearby_stress:
|
||||
day = timezone.localtime(entry.recorded_at, timezone_for_user(request.user)).date()
|
||||
stress_by_day.setdefault(day, []).append(entry)
|
||||
dream_comparisons = []
|
||||
for dream in dreams:
|
||||
prior_day = dream.wake_up_date - timedelta(days=1)
|
||||
evening = [entry.score for entry in stress_by_day.get(prior_day, [])
|
||||
if entry.timing == StressEntry.Timing.BEFORE_SLEEP]
|
||||
after = [entry.score for entry in stress_by_day.get(dream.wake_up_date, [])
|
||||
if entry.timing == StressEntry.Timing.AFTER_WAKING]
|
||||
dream_comparisons.append({'dream': dream, 'before_score': evening[0] if evening else None,
|
||||
'after_score': after[0] if after else None})
|
||||
return render(request, 'stress/journal.html', {
|
||||
'form': form, 'entries': entries, 'calendar': calendar,
|
||||
'week': _summary(all_recent, week_start), 'month': _summary(all_recent, period_start),
|
||||
'query': query, 'timing': timing, 'selected_day': selected_day,
|
||||
'dream_comparisons': dream_comparisons,
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def edit(request, identifier):
|
||||
entry = get_object_or_404(StressEntry, pk=identifier, user=request.user)
|
||||
form = StressEntryForm(request.POST or None, instance=entry)
|
||||
if request.method == 'POST' and form.is_valid():
|
||||
form.save()
|
||||
return redirect('stress:journal')
|
||||
return render(request, 'stress/edit.html', {'form': form, 'entry': entry})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def delete(request, identifier):
|
||||
entry = get_object_or_404(StressEntry, pk=identifier, user=request.user)
|
||||
entry.delete()
|
||||
return redirect('stress:journal')
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def daily_save(request):
|
||||
raw_score = request.POST.get('score', '')
|
||||
destination = request.POST.get('return_to', 'home')
|
||||
if destination not in {'home', 'mobile', 'health'}:
|
||||
destination = 'home'
|
||||
try:
|
||||
score = int(raw_score) if raw_score.isascii() and raw_score.isdigit() else None
|
||||
save_daily_entry(request.user, score=score, timing=request.POST.get('timing', 'anytime'),
|
||||
note=request.POST.get('note', ''), stressor=request.POST.get('stressor', ''))
|
||||
messages.success(request, 'Today’s stress score saved.')
|
||||
except ValidationError as exc:
|
||||
messages.error(request, exc.messages[0])
|
||||
if destination == 'health':
|
||||
return redirect(reverse('planner:health') + '#health-stress-widget')
|
||||
anchor = 'mobile-stress-widget' if destination == 'mobile' else 'desktop-stress-widget'
|
||||
return redirect(reverse('planner:task-list') + '#' + anchor)
|
||||
@@ -45,6 +45,8 @@ INSTALLED_APPS = [
|
||||
'planner',
|
||||
'food.apps.FoodConfig',
|
||||
'recipes',
|
||||
'stress',
|
||||
'dreams',
|
||||
]
|
||||
|
||||
# Published recipes owned by this account may appear in the optional matching demo.
|
||||
@@ -72,6 +74,8 @@ OAUTH2_PROVIDER = {
|
||||
'food:write': 'Create, change, and delete food diary entries and images',
|
||||
'inventory:read': 'Read your kitchen inventory',
|
||||
'inventory:write': 'Create, change, and remove kitchen inventory items',
|
||||
'journal:read': 'Read your private stress and dream journals',
|
||||
'journal:write': 'Create, change, and delete stress and dream entries',
|
||||
},
|
||||
'ACCESS_TOKEN_GENERATOR': 'food.oauth_pat.oauth_access_token',
|
||||
'ACCESS_TOKEN_EXPIRE_SECONDS': 3600,
|
||||
|
||||
@@ -17,13 +17,17 @@ Including another URLconf
|
||||
from django.contrib import admin
|
||||
from django.urls import include, path
|
||||
from oauth2_provider.urls import metadata_urlpatterns
|
||||
from food.oauth_authorize import JournalAuthorizationView
|
||||
|
||||
urlpatterns = [
|
||||
path('', include(metadata_urlpatterns)),
|
||||
path('o/authorize/', JournalAuthorizationView.as_view()),
|
||||
path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
|
||||
path('api/v1/', include('food.api_urls')),
|
||||
path('admin/', admin.site.urls),
|
||||
path('food/', include('food.urls', namespace='food')),
|
||||
path('recipes/', include('recipes.urls', namespace='recipes')),
|
||||
path('stress/', include('stress.urls', namespace='stress')),
|
||||
path('dreams/', include('dreams.urls', namespace='dreams')),
|
||||
path('', include('planner.urls')),
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user