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}'