Files
Django_TasksApp/main/planner/management/commands/seed_demo.py
T
2026-10-22 10:32:41 +02:00

341 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Reset a safe, self-contained demo account with representative Tasknest data."""
from datetime import datetime, time, timedelta
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.contrib.sessions.models import Session
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.utils import timezone
from food.models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit
from food.models import (FoodLogAttachment, InventoryCategory, InventoryConsumption,
InventoryLocation, KitchenInventoryItem, PersonalAccessToken)
from recipes.models import Recipe, RecipeSelection, CookLater, RecipeUse, RecipeCookingRun
from stress.models import StressEntry
from dreams.models import DreamEntry
from oauth2_provider.models import get_access_token_model, get_grant_model, get_refresh_token_model
from planner.models import (
BowelHealthCheckIn,
FastingPause,
FastingPeriod,
FastingSettings,
NeckHeadacheCheckIn,
SickDaySettings,
SleepCheckIn,
Task,
ToothBrushing,
UserSettings,
WaterIntakeEntry,
Workout,
WorkoutCompletion,
)
from planner.services.fasting import synchronize_fasting_periods
from planner.timezones import DEFAULT_TIME_ZONE, localdate_for_user, timezone_for_user
def _seed_food(user, today):
"""Create local demo foods without network calls or third-party assets."""
product_data = (
('Greek yoghurt', 'Demo dairy', Unit.GRAM, '73', '4', '8', '2', '0'),
('Banana', '', Unit.GRAM, '89', '22.8', '1.1', '0.3', '2.6'),
('Wholegrain sandwich', 'Demo bakery', Unit.GRAM, '250', '42', '10', '4', '6'),
('Tomato soup', 'Home made', Unit.MILLILITRE, '35', '5', '1.2', '1', None),
('Pasta with vegetables', 'Home made', Unit.GRAM, '145', '23', '5', '3', '2.5'),
('Almonds', '', Unit.GRAM, '579', '10', '21', '50', '12.5'),
)
products = {}
for name, brand, unit, kcal, carbs, protein, fat, fibre in product_data:
products[name] = FoodProduct.objects.create(
owner=user, product_name=name, brand=brand, base_unit=unit,
energy_kcal_100=Decimal(kcal), carbohydrates_100=Decimal(carbs),
protein_100=Decimal(protein), fat_100=Decimal(fat),
fibre_100=Decimal(fibre) if fibre is not None else None,
source=FoodProduct.Source.MANUAL,
)
yoghurt = products['Greek yoghurt']
soup = products['Tomato soup']
for product in (yoghurt, soup):
FoodFavourite.objects.create(user=user, product=product)
FoodPortion.objects.create(user=user, product=yoghurt, label='My bowl',
amount=Decimal('250'), unit=Unit.GRAM, is_default=True)
FoodPortion.objects.create(user=user, product=soup, label='One mug',
amount=Decimal('250'), unit=Unit.MILLILITRE)
def log(days_ago, meal, name, amount, label=''):
product = products[name]
amount = Decimal(str(amount))
factor = amount / Decimal('100')
def consumed(value):
return (value * factor).quantize(Decimal('0.001')) if value is not None else None
FoodLogEntry.objects.create(
user=user, date=today - timedelta(days=days_ago), meal=meal, product=product,
product_name_snapshot=product.product_name, brand_snapshot=product.brand,
portion_label_snapshot=label, amount=amount, unit=product.base_unit,
calories_kcal=consumed(product.energy_kcal_100),
carbohydrates_g=consumed(product.carbohydrates_100),
protein_g=consumed(product.protein_100), fat_g=consumed(product.fat_100),
fibre_g=consumed(product.fibre_100), source=product.source,
)
for days_ago, meal, name, amount, label in (
(0, MealType.BREAKFAST, 'Greek yoghurt', 250, 'My bowl'),
(0, MealType.BREAKFAST, 'Banana', 120, ''),
(0, MealType.LUNCH, 'Wholegrain sandwich', 100, ''),
(0, MealType.LUNCH, 'Tomato soup', 250, 'One mug'),
(0, MealType.DINNER, 'Pasta with vegetables', 180, ''),
(0, MealType.SNACKS, 'Almonds', 30, ''),
(1, MealType.BREAKFAST, 'Greek yoghurt', 200, ''),
(1, MealType.DINNER, 'Pasta with vegetables', 200, ''),
(2, MealType.LUNCH, 'Wholegrain sandwich', 100, ''),
(5, MealType.SNACKS, 'Banana', 100, ''),
):
log(days_ago, meal, name, amount, label)
return len(products), 10
class Command(BaseCommand):
help = 'Reset a demo account with safe, representative sample data.'
def add_arguments(self, parser):
parser.add_argument('--username', default='demo', help='Demo username (default: demo).')
parser.add_argument('--password', help='Initial or replacement demo password; prefer TASKNEST_DEMO_PASSWORD.')
@transaction.atomic
def handle(self, *args, **options):
username = options['username']
password = options['password'] or settings.TASKNEST_DEMO_PASSWORD
user_model = get_user_model()
user = user_model.objects.filter(username=username).first()
created = user is None
if created and not password:
raise CommandError('Set TASKNEST_DEMO_PASSWORD before creating a demo account.')
if created:
user = user_model(username=username)
if not created and (user.is_staff or user.is_superuser or
UserSettings.objects.filter(user=user).exclude(is_demo=True).exists()):
raise CommandError('Refusing to reset an account that is not marked as a demo account.')
if password:
user.set_password(password)
user.is_active = True
user.save()
profile, _ = UserSettings.objects.get_or_create(user=user)
profile.is_demo = True
profile.time_zone = DEFAULT_TIME_ZONE
profile.appearance = UserSettings.Appearance.LIGHT
profile.latitude = '52.367600'
profile.longitude = '4.904100'
profile.onboarding_enabled = False
profile.onboarding_step = 0
profile.daily_water_goal_ml = 2000
profile.auto_count_food_drinks = True
profile.include_liquid_foods = False
profile.show_hydration_breakdown = True
profile.allow_manual_hydration_adjustments = True
profile.hydration_beverage_rules = {}
profile.daily_calorie_goal = 2000
profile.carbohydrate_goal_g = Decimal('250.0')
profile.protein_goal_g = Decimal('100.0')
profile.fat_goal_g = Decimal('70.0')
profile.fibre_goal_g = Decimal('40.0')
profile.ntfy_url = ''
profile.ntfy_enabled = False
profile.ntfy_last_tested_at = None
profile.save()
SickDaySettings.objects.update_or_create(user=user, defaults={'enabled': False, 'recovery_date': None})
# Reset only demo-owned records. Cascades remove task weather shifts and workout completions.
Task.objects.filter(owner=user).delete()
Workout.objects.filter(owner=user).delete()
NeckHeadacheCheckIn.objects.filter(user=user).delete()
SleepCheckIn.objects.filter(user=user).delete()
FastingPause.objects.filter(user=user).delete()
FastingPeriod.objects.filter(user=user).delete()
WaterIntakeEntry.objects.filter(user=user).delete()
ToothBrushing.objects.filter(user=user).delete()
BowelHealthCheckIn.objects.filter(user=user).delete()
for attachment in FoodLogAttachment.objects.filter(log_entry__user=user):
storage, name = attachment.image.storage, attachment.image.name
transaction.on_commit(lambda storage=storage, name=name: storage.delete(name))
FoodLogEntry.objects.filter(user=user).delete()
StressEntry.objects.filter(user=user).delete()
DreamEntry.objects.filter(user=user).delete()
RecipeSelection.objects.filter(user=user).delete()
CookLater.objects.filter(user=user).delete()
RecipeUse.objects.filter(user=user).delete()
RecipeCookingRun.objects.filter(user=user).delete()
demo_drafts = Recipe.objects.filter(owner=user, status=Recipe.Status.DRAFT)
for recipe in demo_drafts.exclude(photo=''):
storage, name = recipe.photo.storage, recipe.photo.name
transaction.on_commit(lambda storage=storage, name=name: storage.delete(name))
demo_drafts.delete()
KitchenInventoryItem.objects.filter(user=user).delete()
InventoryConsumption.objects.filter(user=user).delete()
InventoryLocation.objects.filter(user=user).delete()
InventoryCategory.objects.filter(user=user).delete()
get_refresh_token_model().objects.filter(user=user).delete()
get_grant_model().objects.filter(user=user).delete()
get_access_token_model().objects.filter(user=user).delete()
PersonalAccessToken.objects.filter(user=user).delete()
for session in Session.objects.filter(expire_date__gt=timezone.now()).iterator():
if session.get_decoded().get('_auth_user_id') == str(user.pk):
session.delete()
FoodFavourite.objects.filter(user=user).delete()
FoodPortion.objects.filter(user=user).delete()
FoodProduct.objects.filter(owner=user).delete()
now = timezone.now()
today = localdate_for_user(user, now)
StressEntry.objects.create(user=user, score=3, daily_date=today,
note='A manageable day after a short walk.')
DreamEntry.objects.create(user=user, wake_up_date=today - timedelta(days=1),
title='The quiet garden',
narrative='I walked through a calm garden and found a familiar path home.')
ToothBrushing.objects.create(user=user, date=today - timedelta(days=1), morning=True, evening=True)
ToothBrushing.objects.create(user=user, date=today, morning=True, evening=False)
for days_ago, severity, note in (
(2, 3, 'A slightly unsettled day.'),
(1, 1, 'Feeling better after lunch.'),
(0, 0, 'Feeling well today.'),
):
BowelHealthCheckIn.objects.create(
user=user, check_in_date=today - timedelta(days=days_ago),
morning_severity=severity, morning_note=note,
afternoon_severity=max(0, severity - 1),
evening_severity=max(0, severity - 1),
)
yesterday = today - timedelta(days=1)
local_zone = timezone_for_user(user)
for hour, amount in ((9, 350), (12, 500), (16, 400)):
WaterIntakeEntry.objects.create(user=user, amount_ml=amount,
recorded_at=timezone.make_aware(datetime.combine(yesterday, time(hour, 0)), local_zone))
WaterIntakeEntry.objects.create(user=user, amount_ml=350, recorded_at=now)
laundry = Task.objects.create(
owner=user,
title='Run the washing machine',
description='A simple parent task to demonstrate dependencies.',
category='Home',
priority=Task.Priority.HIGH,
estimated_duration_minutes=10,
scheduled_for=today,
)
Task.objects.create(
owner=user,
title='Fold the clothes',
description='This appears after the washing-machine task is complete.',
category='Home',
priority=Task.Priority.MEDIUM,
estimated_duration_minutes=15,
scheduled_for=today,
parent_task=laundry,
)
finished_parent = Task.objects.create(
owner=user,
title='Plan this week',
category='Planning',
priority=Task.Priority.MEDIUM,
estimated_duration_minutes=20,
scheduled_for=today,
is_completed=True,
)
Task.objects.create(
owner=user,
title='Choose tomorrow’s priority',
category='Planning',
priority=Task.Priority.HIGH,
estimated_duration_minutes=5,
scheduled_for=today,
parent_task=finished_parent,
)
Task.objects.create(
owner=user,
title='Take a neighbourhood walk',
description='An outdoor task with a weather preference.',
category='Health',
priority=Task.Priority.LOW,
estimated_duration_minutes=30,
scheduled_for=today,
is_outdoor=True,
weather_profile=Task.WeatherProfile.DRY,
)
daily_stretch = Workout.objects.create(
owner=user,
name='Morning stretch',
scheduled_for=today - timedelta(days=7),
is_daily_recurring=True,
duration_minutes=10,
calories_burned=35,
)
WorkoutCompletion.objects.create(workout=daily_stretch, completed_on=today)
Workout.objects.create(
owner=user,
name='Easy cycle',
scheduled_for=today,
is_completed=False,
duration_minutes=30,
calories_burned=180,
)
for days_ago, neck, headache, physiotherapy, note in (
(3, 3, 1, False, 'A little stiff after desk work.'),
(2, 1, 0, True, 'Physiotherapy session.'),
(1, 2, 1, False, ''),
(0, 1, 0, False, 'Feeling better today.'),
):
NeckHeadacheCheckIn.objects.create(
user=user,
check_in_date=today - timedelta(days=days_ago),
morning_neck_pain_severity=neck,
morning_headache_severity=headache,
morning_note=note,
afternoon_neck_pain_severity=max(0, neck - 1),
afternoon_headache_severity=headache,
afternoon_note='Symptoms after lunch.',
evening_neck_pain_severity=max(0, neck - 1),
evening_headache_severity=max(0, headache - 1),
evening_note='Evening check-in.',
had_physiotherapy=physiotherapy,
)
for days_ago, rested, watch_score, note in (
(3, 5, 68, 'Late evening.'),
(2, 7, 82, 'Good recovery.'),
(1, 6, None, ''),
(0, 8, 88, 'Rested this morning.'),
):
SleepCheckIn.objects.create(
user=user,
wake_up_date=today - timedelta(days=days_ago),
rested_score=rested,
watch_sleep_score=watch_score,
note=note,
)
fasting, _ = FastingSettings.objects.update_or_create(
user=user,
defaults={
'enabled': True,
'fasting_start_time': time(20, 0),
'fasting_duration_minutes': 16 * 60,
'tracking_started_at': now - timedelta(days=3),
'last_phase_notification_at': None,
},
)
synchronize_fasting_periods(fasting, now)
food_products, food_entries = _seed_food(user, today)
verb = 'Created' if created else 'Reset'
self.stdout.write(self.style.SUCCESS(
f'{verb} demo user {username!r}: 5 tasks, 2 workouts, 4 pain check-ins, '
f'4 sleep check-ins, 3 bowel check-ins, 4 water entries, '
f'{food_products} foods, and {food_entries} food logs.'
))