latest changes

This commit is contained in:
Joren de Graaf
2026-10-22 10:32:41 +02:00
parent 5799b542c8
commit 5b986134be
63 changed files with 2412 additions and 77 deletions
@@ -0,0 +1,29 @@
- generic [ref=f11e2]:
- banner [ref=f11e3]:
- generic [ref=f11e4]:
- link "Tasknest home" [ref=f11e5] [cursor=pointer]:
- /url: /
- generic [aria-hidden] [ref=f11e6]: ✓
- generic [ref=f11e7]: tasknest
- navigation "Primary navigation" [ref=f11e8]:
- link "Log in" [ref=f11e9] [cursor=pointer]:
- /url: /login/
- link "Create account" [ref=f11e10] [cursor=pointer]:
- /url: /register/
- main [ref=f11e11]:
- generic [ref=f11e12]:
- paragraph [ref=f11e13]: Welcome back
- heading "Log in to Tasknest" [level=1] [ref=f11e14]
- generic [ref=f11e15]:
- generic [ref=f11e16]:
- generic [ref=f11e17]: "Username:"
- textbox "Username:" [active] [ref=f11e18]
- generic [ref=f11e19]:
- generic [ref=f11e20]: "Password:"
- textbox "Password:" [ref=f11e21]
- button "Log in" [ref=f11e22] [cursor=pointer]
- paragraph [ref=f11e23]:
- text: New here?
- link "Create an account" [ref=f11e24] [cursor=pointer]:
- /url: /register/
- text: .
@@ -0,0 +1,681 @@
- generic [ref=f12e2]:
- banner [ref=f12e3]:
- generic [ref=f12e4]:
- link "Tasknest home" [ref=f12e5] [cursor=pointer]:
- /url: /
- generic [aria-hidden] [ref=f12e6]: ✓
- generic [ref=f12e7]: tasknest
- navigation "Primary navigation" [ref=f12e8]:
- link "My tasks" [ref=f12e9] [cursor=pointer]:
- /url: /
- link "Daily planner" [ref=f12e10] [cursor=pointer]:
- /url: /daily/
- link "Health" [ref=f12e11] [cursor=pointer]:
- /url: /health/
- link "Stress" [ref=f12e12] [cursor=pointer]:
- /url: /stress/
- link "Dreams" [ref=f12e13] [cursor=pointer]:
- /url: /dreams/
- link "Food" [ref=f12e14] [cursor=pointer]:
- /url: /food/
- link "Recipes" [ref=f12e15] [cursor=pointer]:
- /url: /recipes/
- link "Kitchen Inventory" [ref=f12e16] [cursor=pointer]:
- /url: /food/inventory/
- link "Settings" [ref=f12e17] [cursor=pointer]:
- /url: /settings/
- button "Use light mode" [ref=f12e19] [cursor=pointer]:
- generic [aria-hidden] [ref=f12e20]: ☀
- button "Log out" [ref=f12e23] [cursor=pointer]
- main [ref=f12e24]:
- note [ref=f12e25]: "Shared demo account: other visitors can see edits you make here. Please do not enter personal information. Demo changes reset at midnight Amsterdam time."
- region [ref=f12e26]:
- generic [ref=f12e27]:
- paragraph [ref=f12e28]: Personal planning
- heading "Make space for what matters." [level=1] [ref=f12e29]
- paragraph [ref=f12e30]: A focused view of your tasks, plans, and next steps.
- generic [ref=f12e31]:
- generic [ref=f12e32]:
- region "Task list" [ref=f12e33]:
- generic [ref=f12e34]:
- generic [ref=f12e35]:
- generic [ref=f12e36]: Show
- combobox "Show" [ref=f12e37]:
- option "Active tasks" [selected]
- option "All tasks"
- option "Past tasks"
- generic [ref=f12e38]:
- button "Apply filter" [ref=f12e39] [cursor=pointer]
- link "New task" [ref=f12e40] [cursor=pointer]:
- /url: /tasks/new/
- generic [aria-hidden] [ref=f12e41]: +
- text: New task
- generic [ref=f12e43]:
- article [ref=f12e44]:
- generic [ref=f12e45]:
- generic [ref=f12e46]: High
- time [ref=f12e47]: Sat, 3 Oct
- heading [level=2] [ref=f12e48]:
- link "Run the washing machine" [ref=f12e49] [cursor=pointer]:
- /url: /tasks/22/
- paragraph [ref=f12e50]: A simple parent task to demonstrate dependencies.
- generic [ref=f12e51]:
- generic [ref=f12e52]: Home
- generic [ref=f12e53]: 10 min
- paragraph [ref=f12e54]: ↳ 1 subtask — complete this task to unlock
- generic [ref=f12e55]:
- button "Mark complete" [ref=f12e57] [cursor=pointer]
- button "Mark Run the washing machine as inactive" [ref=f12e59] [cursor=pointer]: Active
- link "Edit" [ref=f12e60] [cursor=pointer]:
- /url: /tasks/22/edit/
- article [ref=f12e61]:
- generic [ref=f12e62]:
- generic [ref=f12e63]: Low
- time [ref=f12e64]: Sat, 3 Oct
- heading [level=2] [ref=f12e65]:
- link "Take a neighbourhood walk" [ref=f12e66] [cursor=pointer]:
- /url: /tasks/26/
- paragraph [ref=f12e67]: An outdoor task with a weather preference.
- generic [ref=f12e68]:
- generic [ref=f12e69]: Health
- generic [ref=f12e70]: 30 min
- generic [ref=f12e71]: ☀ Dry
- generic [ref=f12e72]:
- button "Mark complete" [ref=f12e74] [cursor=pointer]
- button "Mark Take a neighbourhood walk as inactive" [ref=f12e76] [cursor=pointer]: Active
- link "Edit" [ref=f12e77] [cursor=pointer]:
- /url: /tasks/26/edit/
- region [ref=f12e78]:
- generic [ref=f12e79]:
- generic [ref=f12e80]:
- paragraph [ref=f12e81]: Daily movement
- heading "Daily Workout" [level=2] [ref=f12e82]
- paragraph [ref=f12e83]: Today, Monday, 19 October
- generic [ref=f12e84]:
- strong [ref=f12e85]: —
- generic [ref=f12e86]: No calorie data yet
- link "+ Add workout" [ref=f12e87] [cursor=pointer]:
- /url: /workouts/new/
- article [ref=f12e89]:
- generic [ref=f12e90]:
- heading "Morning stretch" [level=3] [ref=f12e91]
- paragraph [ref=f12e92]: Daily routine · 10 min · 35 kcal
- generic [ref=f12e93]:
- button "Mark complete" [ref=f12e95] [cursor=pointer]
- link "Edit" [ref=f12e96] [cursor=pointer]:
- /url: /workouts/10/edit/
- button "Remove" [ref=f12e98] [cursor=pointer]
- region [ref=f12e99]:
- generic [ref=f12e100]:
- generic [ref=f12e101]:
- paragraph [ref=f12e102]: Code garden
- heading "Gitea activity" [level=2] [ref=f12e103]
- link "View profile on Gitea" [ref=f12e104] [cursor=pointer]:
- /url: https://git.jorendegraaf.eu/jorenmartijn
- text: View profile
- generic [ref=f12e105]: on Gitea
- paragraph [ref=f12e106]:
- strong [ref=f12e107]: "39"
- text: contributions in the last year
- 'img "Gitea contribution calendar: 39 contributions in the last year" [ref=f12e109]':
- generic [aria-hidden] [ref=f12e110]:
- generic [ref=f12e112]: Mon
- generic [ref=f12e114]: Wed
- generic [ref=f12e116]: Fri
- generic [aria-hidden] [ref=f12e118]:
- generic [ref=f12e119]: Oct
- time [ref=f12e120]
- time [ref=f12e121]
- time [ref=f12e122]
- time [ref=f12e123]
- time [ref=f12e124]
- time [ref=f12e125]
- time [ref=f12e126]
- generic [aria-hidden] [ref=f12e127]:
- time [ref=f12e129]
- time [ref=f12e130]
- time [ref=f12e131]
- time [ref=f12e132]
- time [ref=f12e133]
- time [ref=f12e134]
- time [ref=f12e135]
- generic [aria-hidden] [ref=f12e136]:
- generic [ref=f12e137]: Nov
- time [ref=f12e138]
- time [ref=f12e139]
- time [ref=f12e140]
- time [ref=f12e141]
- time [ref=f12e142]
- time [ref=f12e143]
- time [ref=f12e144]
- generic [aria-hidden] [ref=f12e145]:
- time [ref=f12e147]
- time [ref=f12e148]
- time [ref=f12e149]
- time [ref=f12e150]
- time [ref=f12e151]
- time [ref=f12e152]
- time [ref=f12e153]
- generic [aria-hidden] [ref=f12e154]:
- time [ref=f12e156]
- time [ref=f12e157]
- time [ref=f12e158]
- time [ref=f12e159]
- time [ref=f12e160]
- time [ref=f12e161]
- time [ref=f12e162]
- generic [aria-hidden] [ref=f12e163]:
- time [ref=f12e165]
- time [ref=f12e166]
- time [ref=f12e167]
- time [ref=f12e168]
- time [ref=f12e169]
- time [ref=f12e170]
- time [ref=f12e171]
- generic [aria-hidden] [ref=f12e172]:
- time [ref=f12e174]
- time [ref=f12e175]
- time [ref=f12e176]
- time [ref=f12e177]
- time [ref=f12e178]
- time [ref=f12e179]
- time [ref=f12e180]
- generic [aria-hidden] [ref=f12e181]:
- generic [ref=f12e182]: Dec
- time [ref=f12e183]
- time [ref=f12e184]
- time [ref=f12e185]
- time [ref=f12e186]
- time [ref=f12e187]
- time [ref=f12e188]
- time [ref=f12e189]
- generic [aria-hidden] [ref=f12e190]:
- time [ref=f12e192]
- time [ref=f12e193]
- time [ref=f12e194]
- time [ref=f12e195]
- time [ref=f12e196]
- time [ref=f12e197]
- time [ref=f12e198]
- generic [aria-hidden] [ref=f12e199]:
- time [ref=f12e201]
- time [ref=f12e202]
- time [ref=f12e203]
- time [ref=f12e204]
- time [ref=f12e205]
- time [ref=f12e206]
- time [ref=f12e207]
- generic [aria-hidden] [ref=f12e208]:
- time [ref=f12e210]
- time [ref=f12e211]
- time [ref=f12e212]
- time [ref=f12e213]
- time [ref=f12e214]
- time [ref=f12e215]
- time [ref=f12e216]
- generic [aria-hidden] [ref=f12e217]:
- generic [ref=f12e218]: Jan
- time [ref=f12e219]
- time [ref=f12e220]
- time [ref=f12e221]
- time [ref=f12e222]
- time [ref=f12e223]
- time [ref=f12e224]
- time [ref=f12e225]
- generic [aria-hidden] [ref=f12e226]:
- time [ref=f12e228]
- time [ref=f12e229]
- time [ref=f12e230]
- time [ref=f12e231]
- time [ref=f12e232]
- time [ref=f12e233]
- time [ref=f12e234]
- generic [aria-hidden] [ref=f12e235]:
- time [ref=f12e237]
- time [ref=f12e238]
- time [ref=f12e239]
- time [ref=f12e240]
- time [ref=f12e241]
- time [ref=f12e242]
- time [ref=f12e243]
- generic [aria-hidden] [ref=f12e244]:
- time [ref=f12e246]
- time [ref=f12e247]
- time [ref=f12e248]
- time [ref=f12e249]
- time [ref=f12e250]
- time [ref=f12e251]
- time [ref=f12e252]
- generic [aria-hidden] [ref=f12e253]:
- generic [ref=f12e254]: Feb
- time [ref=f12e255]
- time [ref=f12e256]
- time [ref=f12e257]
- time [ref=f12e258]
- time [ref=f12e259]
- time [ref=f12e260]
- time [ref=f12e261]
- generic [aria-hidden] [ref=f12e262]:
- time [ref=f12e264]
- time [ref=f12e265]
- time [ref=f12e266]
- time [ref=f12e267]
- time [ref=f12e268]
- time [ref=f12e269]
- time [ref=f12e270]
- generic [aria-hidden] [ref=f12e271]:
- time [ref=f12e273]
- time [ref=f12e274]
- time [ref=f12e275]
- time [ref=f12e276]
- time [ref=f12e277]
- time [ref=f12e278]
- time [ref=f12e279]
- generic [aria-hidden] [ref=f12e280]:
- time [ref=f12e282]
- time [ref=f12e283]
- time [ref=f12e284]
- time [ref=f12e285]
- time [ref=f12e286]
- time [ref=f12e287]
- time [ref=f12e288]
- generic [aria-hidden] [ref=f12e289]:
- generic [ref=f12e290]: Mar
- time [ref=f12e291]
- time [ref=f12e292]
- time [ref=f12e293]
- time [ref=f12e294]
- time [ref=f12e295]
- time [ref=f12e296]
- time [ref=f12e297]
- generic [aria-hidden] [ref=f12e298]:
- time [ref=f12e300]
- time [ref=f12e301]
- time [ref=f12e302]
- time [ref=f12e303]
- time [ref=f12e304]
- time [ref=f12e305]
- time [ref=f12e306]
- generic [aria-hidden] [ref=f12e307]:
- time [ref=f12e309]
- time [ref=f12e310]
- time [ref=f12e311]
- time [ref=f12e312]
- time [ref=f12e313]
- time [ref=f12e314]
- time [ref=f12e315]
- generic [aria-hidden] [ref=f12e316]:
- time [ref=f12e318]
- time [ref=f12e319]
- time [ref=f12e320]
- time [ref=f12e321]
- time [ref=f12e322]
- time [ref=f12e323]
- time [ref=f12e324]
- generic [aria-hidden] [ref=f12e325]:
- time [ref=f12e327]
- time [ref=f12e328]
- time [ref=f12e329]
- time [ref=f12e330]
- time [ref=f12e331]
- time [ref=f12e332]
- time [ref=f12e333]
- generic [aria-hidden] [ref=f12e334]:
- generic [ref=f12e335]: Apr
- time [ref=f12e336]
- time [ref=f12e337]
- time [ref=f12e338]
- time [ref=f12e339]
- time [ref=f12e340]
- time [ref=f12e341]
- time [ref=f12e342]
- generic [aria-hidden] [ref=f12e343]:
- time [ref=f12e345]
- time [ref=f12e346]
- time [ref=f12e347]
- time [ref=f12e348]
- time [ref=f12e349]
- time [ref=f12e350]
- time [ref=f12e351]
- generic [aria-hidden] [ref=f12e352]:
- time [ref=f12e354]
- time [ref=f12e355]
- time [ref=f12e356]
- time [ref=f12e357]
- time [ref=f12e358]
- time [ref=f12e359]
- time [ref=f12e360]
- generic [aria-hidden] [ref=f12e361]:
- time [ref=f12e363]
- time [ref=f12e364]
- time [ref=f12e365]
- time [ref=f12e366]
- time [ref=f12e367]
- time [ref=f12e368]
- time [ref=f12e369]
- generic [aria-hidden] [ref=f12e370]:
- generic [ref=f12e371]: May
- time [ref=f12e372]
- time [ref=f12e373]
- time [ref=f12e374]
- time [ref=f12e375]
- time [ref=f12e376]
- time [ref=f12e377]
- time [ref=f12e378]
- generic [aria-hidden] [ref=f12e379]:
- time [ref=f12e381]
- time [ref=f12e382]
- time [ref=f12e383]
- time [ref=f12e384]
- time [ref=f12e385]
- time [ref=f12e386]
- time [ref=f12e387]
- generic [aria-hidden] [ref=f12e388]:
- time [ref=f12e390]
- time [ref=f12e391]
- time [ref=f12e392]
- time [ref=f12e393]
- time [ref=f12e394]
- time [ref=f12e395]
- time [ref=f12e396]
- generic [aria-hidden] [ref=f12e397]:
- time [ref=f12e399]
- time [ref=f12e400]
- time [ref=f12e401]
- time [ref=f12e402]
- time [ref=f12e403]
- time [ref=f12e404]
- time [ref=f12e405]
- generic [aria-hidden] [ref=f12e406]:
- time [ref=f12e408]
- time [ref=f12e409]
- time [ref=f12e410]
- time [ref=f12e411]
- time [ref=f12e412]
- time [ref=f12e413]
- time [ref=f12e414]
- generic [aria-hidden] [ref=f12e415]:
- generic [ref=f12e416]: Jun
- time [ref=f12e417]
- time [ref=f12e418]
- time [ref=f12e419]
- time [ref=f12e420]
- time [ref=f12e421]
- time [ref=f12e422]
- time [ref=f12e423]
- generic [aria-hidden] [ref=f12e424]:
- time [ref=f12e426]
- time [ref=f12e427]
- time [ref=f12e428]
- time [ref=f12e429]
- time [ref=f12e430]
- time [ref=f12e431]
- time [ref=f12e432]
- generic [aria-hidden] [ref=f12e433]:
- time [ref=f12e435]
- time [ref=f12e436]
- time [ref=f12e437]
- time [ref=f12e438]
- time [ref=f12e439]
- time [ref=f12e440]
- time [ref=f12e441]
- generic [aria-hidden] [ref=f12e442]:
- time [ref=f12e444]
- time [ref=f12e445]
- time [ref=f12e446]
- time [ref=f12e447]
- time [ref=f12e448]
- time [ref=f12e449]
- time [ref=f12e450]
- generic [aria-hidden] [ref=f12e451]:
- generic [ref=f12e452]: Jul
- time [ref=f12e453]
- time [ref=f12e454]
- time [ref=f12e455]
- time [ref=f12e456]
- time [ref=f12e457]
- time [ref=f12e458]
- time [ref=f12e459]
- generic [aria-hidden] [ref=f12e460]:
- time [ref=f12e462]
- time [ref=f12e463]
- time [ref=f12e464]
- time [ref=f12e465]
- time [ref=f12e466]
- time [ref=f12e467]
- time [ref=f12e468]
- generic [aria-hidden] [ref=f12e469]:
- time [ref=f12e471]
- time [ref=f12e472]
- time [ref=f12e473]
- time [ref=f12e474]
- time [ref=f12e475]
- time [ref=f12e476]
- time [ref=f12e477]
- generic [aria-hidden] [ref=f12e478]:
- time [ref=f12e480]
- time [ref=f12e481]
- time [ref=f12e482]
- time [ref=f12e483]
- time [ref=f12e484]
- time [ref=f12e485]
- time [ref=f12e486]
- generic [aria-hidden] [ref=f12e487]:
- generic [ref=f12e488]: Aug
- time [ref=f12e489]
- time [ref=f12e490]
- time [ref=f12e491]
- time [ref=f12e492]
- time [ref=f12e493]
- time [ref=f12e494]
- time [ref=f12e495]
- generic [aria-hidden] [ref=f12e496]:
- time [ref=f12e498]
- time [ref=f12e499]
- time [ref=f12e500]
- time [ref=f12e501]
- time [ref=f12e502]
- time [ref=f12e503]
- time [ref=f12e504]
- generic [aria-hidden] [ref=f12e505]:
- time [ref=f12e507]
- time [ref=f12e508]
- time [ref=f12e509]
- time [ref=f12e510]
- time [ref=f12e511]
- time [ref=f12e512]
- time [ref=f12e513]
- generic [aria-hidden] [ref=f12e514]:
- time [ref=f12e516]
- time [ref=f12e517]
- time [ref=f12e518]
- time [ref=f12e519]
- time [ref=f12e520]
- time [ref=f12e521]
- time [ref=f12e522]
- generic [aria-hidden] [ref=f12e523]:
- time [ref=f12e525]
- time [ref=f12e526]
- time [ref=f12e527]
- time [ref=f12e528]
- time [ref=f12e529]
- time [ref=f12e530]
- time [ref=f12e531]
- generic [aria-hidden] [ref=f12e532]:
- generic [ref=f12e533]: Sep
- time [ref=f12e534]
- time [ref=f12e535]
- time [ref=f12e536]
- time [ref=f12e537]
- time [ref=f12e538]
- time [ref=f12e539]
- time [ref=f12e540]
- generic [aria-hidden] [ref=f12e541]:
- time [ref=f12e543]
- time [ref=f12e544]
- time [ref=f12e545]
- time [ref=f12e546]
- time [ref=f12e547]
- time [ref=f12e548]
- time [ref=f12e549]
- generic [aria-hidden] [ref=f12e550]:
- time [ref=f12e552]
- time [ref=f12e553]
- time [ref=f12e554]
- time [ref=f12e555]
- time [ref=f12e556]
- time [ref=f12e557]
- time [ref=f12e558]
- generic [aria-hidden] [ref=f12e559]:
- time [ref=f12e561]
- time [ref=f12e562]
- time [ref=f12e563]
- time [ref=f12e564]
- time [ref=f12e565]
- time [ref=f12e566]
- time [ref=f12e567]
- generic [aria-hidden] [ref=f12e568]:
- generic [ref=f12e569]: Oct
- time [ref=f12e570]
- time [ref=f12e571]
- time [ref=f12e572]
- time [ref=f12e573]
- time [ref=f12e574]
- time [ref=f12e575]
- time [ref=f12e576]
- generic [aria-hidden] [ref=f12e577]:
- time [ref=f12e579]
- time [ref=f12e580]
- time [ref=f12e581]
- time [ref=f12e582]
- time [ref=f12e583]
- time [ref=f12e584]
- time [ref=f12e585]
- generic [aria-hidden] [ref=f12e586]:
- time [ref=f12e588]
- time [ref=f12e589]
- time [ref=f12e590]
- time [ref=f12e591]
- time [ref=f12e592]
- time [ref=f12e593]
- time [ref=f12e594]
- generic [aria-hidden] [ref=f12e595]:
- generic [ref=f12e596]: Less
- generic [ref=f12e602]: More
- complementary "Personal routines" [ref=f12e603]:
- generic [ref=f12e604]:
- region [ref=f12e605]:
- generic [ref=f12e607]:
- paragraph [ref=f12e608]: Your forecast
- heading "Weather" [level=2] [ref=f12e609]
- paragraph [ref=f12e610]: Forecast temporarily unavailable. Your tasks will continue as normal.
- article [ref=f12e611]:
- paragraph [ref=f12e612]: Daily check-in
- generic [ref=f12e613]:
- heading "Stress" [level=2] [ref=f12e614]
- link "Journal" [ref=f12e615] [cursor=pointer]:
- /url: /stress/
- paragraph [ref=f12e616]: Monday, 19 October
- generic [ref=f12e617]:
- generic [ref=f12e618]:
- generic [ref=f12e619]: How stressed? (0–10)
- generic [ref=f12e620]:
- status [ref=f12e622]: Not recorded
- slider "How stressed? (0–10)" [ref=f12e624] [cursor=pointer]: "0"
- generic [ref=f12e625]:
- generic [ref=f12e626]: "0"
- generic [ref=f12e627]: "10"
- generic [ref=f12e628]:
- text: When relative to sleep
- combobox "When relative to sleep" [ref=f12e629]:
- option "Anytime" [selected]
- option "Before sleep"
- option "After waking"
- group [ref=f12e630]:
- generic "Add context (optional)" [ref=f12e631] [cursor=pointer]
- button "Save today" [ref=f12e632] [cursor=pointer]
- paragraph [ref=f12e633]: No score logged today.
- article [ref=f12e634]:
- paragraph [ref=f12e635]: Daily routine
- heading "Teeth" [level=2] [ref=f12e636]
- generic [ref=f12e638]:
- time [ref=f12e639]: Monday
- generic [ref=f12e640]:
- button "Monday 19 October morning brushing, not done" [ref=f12e642] [cursor=pointer]: ○ Morning
- button "Monday 19 October evening brushing, not done" [ref=f12e644] [cursor=pointer]: ○ Evening
- article [ref=f12e645]:
- paragraph [ref=f12e646]: Daily hydration
- heading "Water" [level=2] [ref=f12e647]
- generic [ref=f12e648]:
- generic [ref=f12e649]:
- paragraph [ref=f12e650]: 0 / 2000 ml
- paragraph [ref=f12e651]: 0% of daily goal
- paragraph [ref=f12e652]: "Manual: 0 ml · Food Diary drinks: 0 ml"
- progressbar "Daily water goal" [ref=f12e653]
- img [aria-hidden] [ref=f12e654]:
- generic [ref=f12e661]: "2000"
- generic [ref=f12e662]: "1500"
- generic [ref=f12e663]: "1000"
- generic [ref=f12e664]: "500"
- generic [ref=f12e665]:
- generic [ref=f12e666]:
- button "+250 ml" [ref=f12e667] [cursor=pointer]
- button "+500 ml" [ref=f12e668] [cursor=pointer]
- group [ref=f12e669]:
- generic "Other" [ref=f12e670] [cursor=pointer]
- generic [ref=f12e671]: No manual water logged today
- generic [ref=f12e673]:
- paragraph [ref=f12e674]: This week
- generic [ref=f12e675]:
- 'generic "Monday: 0 ml, no water logged" [ref=f12e676]': M
- 'generic "Tuesday: 0 ml, no water logged" [ref=f12e677]': T
- 'generic "Wednesday: 0 ml, no water logged" [ref=f12e678]': W
- 'generic "Thursday: 0 ml, no water logged" [ref=f12e679]': T
- 'generic "Friday: 0 ml, no water logged" [ref=f12e680]': F
- 'generic "Saturday: 0 ml, no water logged" [ref=f12e681]': S
- 'generic "Sunday: 0 ml, no water logged" [ref=f12e682]': S
- article [ref=f12e683]:
- generic [ref=f12e684]:
- paragraph [ref=f12e685]: Intermittent fasting
- generic [ref=f12e686]: Eating
- heading "Eating window open" [level=2] [ref=f12e687]
- 'timer "eating progress: 75 percent" [ref=f12e688]':
- generic [ref=f12e692]:
- strong [ref=f12e693]: 06:00:19
- generic [ref=f12e694]: Eating elapsed
- generic [ref=f12e695]:
- generic [ref=f12e696]:
- term [ref=f12e697]: Eating window
- definition [ref=f12e698]:
- time [ref=f12e699]: Mon 19 Oct, 12:00
- text: →
- time [ref=f12e700]: Mon 19 Oct, 20:00
- generic [ref=f12e701]:
- term [ref=f12e702]: Next fasting window
- definition [ref=f12e703]:
- time [ref=f12e704]: Mon 19 Oct, 20:00
- text: →
- time [ref=f12e705]: Tue 20 Oct, 12:00
- generic [ref=f12e706]:
- generic [ref=f12e707]:
- term [ref=f12e708]: Daily fast
- definition [ref=f12e709]: 16 hours
- generic [ref=f12e710]:
- term [ref=f12e711]: Eating window
- definition [ref=f12e712]: 8 hours
- generic [ref=f12e713]:
- button "Pause tracking" [ref=f12e715] [cursor=pointer]
- link "Adjust" [ref=f12e716] [cursor=pointer]:
- /url: /fasting/configure/
- region [ref=f12e717]:
- heading "Recent completed fasts" [level=3] [ref=f12e718]
- list [ref=f12e719]:
- listitem [ref=f12e720]:
- time [ref=f12e721]: 18 Oct
- generic [ref=f12e722]: 20:00–12:00
- listitem [ref=f12e723]:
- time [ref=f12e724]: 17 Oct
- generic [ref=f12e725]: 20:00–12:00
- listitem [ref=f12e726]:
- time [ref=f12e727]: 16 Oct
- generic [ref=f12e728]: 20:00–12:00
+2
View File
@@ -10,6 +10,8 @@ In findings, distinguish observed visual problems, accessibility or functional p
Playwright may use the dedicated demo account to navigate authenticated pages and create, edit, or delete its own test data. Never modify another user's data. Reuse an authenticated Playwright session when available. Credentials may be supplied interactively; never commit passwords, cookies, session or CSRF tokens, or other credentials. Never put demo credentials in this file or source/configuration files. If browser authentication state is exported, store it in `playwright/.auth/` and keep that directory in `.gitignore`. Playwright may use the dedicated demo account to navigate authenticated pages and create, edit, or delete its own test data. Never modify another user's data. Reuse an authenticated Playwright session when available. Credentials may be supplied interactively; never commit passwords, cookies, session or CSRF tokens, or other credentials. Never put demo credentials in this file or source/configuration files. If browser authentication state is exported, store it in `playwright/.auth/` and keep that directory in `.gitignore`.
The shared demo account is identified by `UserSettings.is_demo`, not its username. Keep sensitive demo restrictions enforced on the server, including direct URLs and API token paths. Use synthetic accounts and a test database for reset and abuse tests; do not run `seed_demo` against the live shared account merely to verify a change. Published demo recipes are curated Recipe Match data and must survive the nightly reset.
## Browser testing behavior ## Browser testing behavior
Browser access is for verification and debugging, not permission for arbitrary changes. For an inspection-only request, reproduce and inspect the relevant state, take screenshots when useful, report findings, and leave project files untouched. For an implementation request, inspect the current rendered state when useful, make the requested change, reload and inspect the page, test relevant interactions, check browser errors, inspect relevant viewport sizes, and fix introduced problems. Prefer rendered observations over assumptions from templates or styles. Browser access is for verification and debugging, not permission for arbitrary changes. For an inspection-only request, reproduce and inspect the relevant state, take screenshots when useful, report findings, and leave project files untouched. For an implementation request, inspect the current rendered state when useful, make the requested change, reload and inspect the page, test relevant interactions, check browser errors, inspect relevant viewport sizes, and fix introduced problems. Prefer rendered observations over assumptions from templates or styles.
+2
View File
@@ -23,6 +23,8 @@ Set these variables in the MCP process for deployment:
Set `TASKNEST_MCP_PUBLIC_URL` and `TASKNEST_OAUTH_ISSUER_URL` in Django as well. Keep the issuer URL consistent between both processes. The checked-in defaults use `https://tasksnest.jorendegraaf.eu/`; override both variables with local URLs when testing local OAuth. Do not place personal access tokens in URLs or environment variables. Bind MCP to loopback only when Caddy runs on the **same host**. When Caddy runs on another host and proxies to the app host's Tailnet address, bind MCP to that Tailnet address instead. The MCP process should have the same restart and logging policy as the Django service. Set `TASKNEST_MCP_PUBLIC_URL` and `TASKNEST_OAUTH_ISSUER_URL` in Django as well. Keep the issuer URL consistent between both processes. The checked-in defaults use `https://tasksnest.jorendegraaf.eu/`; override both variables with local URLs when testing local OAuth. Do not place personal access tokens in URLs or environment variables. Bind MCP to loopback only when Caddy runs on the **same host**. When Caddy runs on another host and proxies to the app host's Tailnet address, bind MCP to that Tailnet address instead. The MCP process should have the same restart and logging policy as the Django service.
When `TASKNEST_API_BASE_URL` uses loopback HTTP, the MCP adapter marks that trusted local hop as HTTPS for Django's proxy security check. This keeps `SECURE_SSL_REDIRECT` enabled without redirecting API calls to a TLS listener on port 1234. Restart the MCP process after deploying adapter changes. A direct unauthenticated call to the loopback API without that header may return a 301 redirect; a public HTTPS API call should return a structured 401 instead.
The public `/mcp` path **must** reach the MCP process, not Django. For the site's Caddy proxy, route the exact MCP path and protected-resource metadata to the MCP listener, and let the existing Django route handle OAuth metadata and `/o/`: The public `/mcp` path **must** reach the MCP process, not Django. For the site's Caddy proxy, route the exact MCP path and protected-resource metadata to the MCP listener, and let the existing Django route handle OAuth metadata and `/o/`:
```caddyfile ```caddyfile
+30 -4
View File
@@ -29,13 +29,39 @@ Create or reset the public demonstration account and its dummy data with:
/home/jorenmartijn/django/tasksnest/bin/python /home/jorenmartijn/django/main/manage.py seed_demo /home/jorenmartijn/django/tasksnest/bin/python /home/jorenmartijn/django/main/manage.py seed_demo
``` ```
The command resets only the `demo` account (default password: `demo`). It creates The command resets only an account marked as a demo by `planner.UserSettings.is_demo`
(the migration marks the existing non-staff `demo` account once). It refuses to
reset an unmarked or privileged existing account. Existing credentials are
preserved unless `TASKNEST_DEMO_PASSWORD` or `--password` is supplied; creating
a new demo account requires one of these. It creates
sample parent/subtasks, workouts, pain, sleep, bowel, tooth-brushing and water sample parent/subtasks, workouts, pain, sleep, bowel, tooth-brushing and water
check-ins, a 16-hour fasting schedule, and a food diary with nutrition goals, check-ins, a 16-hour fasting schedule, and a food diary with nutrition goals,
six local foods, favourites, custom portions, and entries across several days. six local foods, favourites, custom portions, a sample stress check-in and dream,
and entries across several days.
Food seeding makes no external API requests. It is idempotent: running it again Food seeding makes no external API requests. It is idempotent: running it again
removes demo-only edits and restores the same baseline. Use `--username` and removes demo-only edits and restores the same baseline. Use `--username` and
`--password` to override the credentials. `--password` to rotate the credential explicitly. Do not put a password in a
systemd command line or committed file.
The reset also removes demo-owned dreams, stress entries, draft recipes,
inventory, tokens, OAuth grants, uploaded food/draft-recipe images, and active
Django sessions. Published demo recipes are curated Recipe Match catalogue data:
the reset preserves them and demo visitors cannot change them through recipe
write routes.
It keeps the demo account and its marker. Demo HTTP requests cannot issue tokens,
authorize OAuth clients, send ntfy tests, use external product lookups, or upload
recipe images. Demo writes are limited to 1 MiB, 60 requests per minute, and
500 requests per day per application cache instance.
All visitors currently share one demo account and can see each other's edits
until the reset; do not use the demo for private information. A future isolated
visitor session design should address that privacy limitation.
Before deploying, provision a unique `DJANGO_SECRET_KEY` of at least 50 random
characters in the process environment or the ignored repository-root `.env`, and
set `DJANGO_DEBUG=false`. The code refuses to start without the secret. Rotating
the old public development secret invalidates existing signed sessions. Run
`manage.py check --deploy` with the deployment environment and resolve any
remaining warnings before exposing the service. Do not commit `.env`.
A daily systemd timer template is provided in `main/deploy/systemd/`. Adjust the A daily systemd timer template is provided in `main/deploy/systemd/`. Adjust the
`User`, `WorkingDirectory`, and `ExecStart` paths in the service file if needed, `User`, `WorkingDirectory`, and `ExecStart` paths in the service file if needed,
@@ -49,7 +75,7 @@ sudo systemctl enable --now tasknest-demo-seed.timer
systemctl list-timers tasknest-demo-seed.timer systemctl list-timers tasknest-demo-seed.timer
``` ```
The supplied timer runs daily at 03:15 Europe/Amsterdam and catches up after a The supplied timer runs daily at 00:00 Europe/Amsterdam and catches up after a
missed scheduled run when the host comes back online. missed scheduled run when the host comes back online.
## Fasting phase notifications ## Fasting phase notifications
+1 -1
View File
@@ -2,7 +2,7 @@
Description=Run the Tasknest demo-data reset every day Description=Run the Tasknest demo-data reset every day
[Timer] [Timer]
OnCalendar=*-*-* 03:15:00 Europe/Amsterdam OnCalendar=*-*-* 00:00:00 Europe/Amsterdam
Persistent=true Persistent=true
Unit=tasknest-demo-seed.service Unit=tasknest-demo-seed.service
+5
View File
@@ -19,6 +19,7 @@ from django.utils.dateparse import parse_date, parse_time
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from planner.models import UserSettings, WaterIntakeEntry from planner.models import UserSettings, WaterIntakeEntry
from planner.demo_policy import is_demo_user
from planner.timezones import localdate_for_user, timezone_for_user from planner.timezones import localdate_for_user, timezone_for_user
from .models import (ApiIdempotencyRecord, FoodLogAttachment, FoodLogEntry, FoodProduct, from .models import (ApiIdempotencyRecord, FoodLogAttachment, FoodLogEntry, FoodProduct,
InventoryCategory, InventoryLocation, KitchenInventoryItem, InventoryCategory, InventoryLocation, KitchenInventoryItem,
@@ -52,6 +53,8 @@ def token_value():
def create_token(user, name, scopes, expires_at=None): def create_token(user, name, scopes, expires_at=None):
if is_demo_user(user):
raise ValueError('API tokens are unavailable for demo accounts.')
prefix, value = token_value() prefix, value = token_value()
token = PersonalAccessToken.objects.create(user=user, name=name, prefix=prefix, token = PersonalAccessToken.objects.create(user=user, name=name, prefix=prefix,
token_hash=hashlib.sha256(value.encode()).hexdigest(), scopes=sorted(set(scopes)), expires_at=expires_at) token_hash=hashlib.sha256(value.encode()).hexdigest(), scopes=sorted(set(scopes)), expires_at=expires_at)
@@ -74,6 +77,8 @@ def _authenticate(request):
return None, error('revoked_token', 'API token has been revoked.', 401) return None, error('revoked_token', 'API token has been revoked.', 401)
if token.expires_at and token.expires_at <= timezone.now(): if token.expires_at and token.expires_at <= timezone.now():
return None, error('expired_token', 'API token has expired.', 401) return None, error('expired_token', 'API token has expired.', 401)
if is_demo_user(token.user):
return None, error('demo_token_forbidden', 'Demo account tokens are disabled.', 403)
PersonalAccessToken.objects.filter(pk=token.pk).update(last_used_at=timezone.now()) PersonalAccessToken.objects.filter(pk=token.pk).update(last_used_at=timezone.now())
return token, None return token, None
+4
View File
@@ -3,6 +3,7 @@ from . import api, api_schema
from recipes import api as recipe_api from recipes import api as recipe_api
from stress import api as stress_api from stress import api as stress_api
from dreams import api as dream_api from dreams import api as dream_api
from groceries import api as grocery_api
urlpatterns = [ urlpatterns = [
path('auth/whoami/', api.whoami), path('auth/whoami/', api.whoami),
@@ -34,6 +35,9 @@ urlpatterns = [
path('hydration/manual/', api.hydration_log), path('hydration/manual/', api.hydration_log),
path('hydration/manual/<uuid:identifier>/', api.hydration_manual_entry), path('hydration/manual/<uuid:identifier>/', api.hydration_manual_entry),
path('hydration/settings/', api.hydration_settings), path('hydration/settings/', api.hydration_settings),
path('groceries/', grocery_api.collection),
path('groceries/<uuid:identifier>/', grocery_api.item),
path('groceries/recipe/<uuid:identifier>/', grocery_api.recipe_import),
path('recipes/', recipe_api.recipe_search), path('recipes/', recipe_api.recipe_search),
path('recipes/cook-later/', recipe_api.recipe_cook_later_collection), path('recipes/cook-later/', recipe_api.recipe_cook_later_collection),
path('recipes/cook-later/<uuid:identifier>/', recipe_api.recipe_cook_later_item), path('recipes/cook-later/<uuid:identifier>/', recipe_api.recipe_cook_later_item),
+28 -25
View File
@@ -7,15 +7,16 @@ from .models import FoodLogEntry, FoodPortion, FoodProduct, KitchenInventoryItem
class ManualFoodForm(forms.ModelForm): class ManualFoodForm(forms.ModelForm):
basis_amount = forms.DecimalField(min_value=Decimal('0.001'), max_digits=10, decimal_places=3, basis_amount = forms.DecimalField(min_value=Decimal('0.001'), max_digits=10, decimal_places=3,
initial=100, label='Nutrition basis amount') initial=100, required=False, label='Nutrition basis amount')
class Meta: class Meta:
model = FoodProduct model = FoodProduct
fields = ('product_name', 'brand', 'barcode', 'base_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'fibre_100', 'sugars_100', 'salt_100') fields = ('product_name', 'brand', 'barcode', 'base_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100')
labels = { labels = {
'energy_kcal_100': 'Calories for base quantity', 'energy_kcal_100': 'Calories for base quantity',
'carbohydrates_100': 'Carbohydrates for base quantity', 'carbohydrates_100': 'Carbohydrates for base quantity',
'protein_100': 'Protein for base quantity', 'protein_100': 'Protein for base quantity',
'fat_100': 'Fat for base quantity', 'fat_100': 'Fat for base quantity',
'saturated_fat_100': 'Saturated fat for base quantity (optional)',
'fibre_100': 'Fibre for base quantity (optional)', 'fibre_100': 'Fibre for base quantity (optional)',
'sugars_100': 'Sugars for base quantity (optional)', 'sugars_100': 'Sugars for base quantity (optional)',
'salt_100': 'Salt for base quantity (optional)', 'salt_100': 'Salt for base quantity (optional)',
@@ -25,14 +26,21 @@ class ManualFoodForm(forms.ModelForm):
self.user = kwargs.pop('user', None) self.user = kwargs.pop('user', None)
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.fields['barcode'].required = False self.fields['barcode'].required = False
for field in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100'): self.fields['base_unit'].required = False
self.fields[field].required = True if self.instance.pk:
self.fields['base_unit'].disabled = True
def clean_base_unit(self):
return self.cleaned_data['base_unit'] or self.instance.base_unit or 'g'
def clean_basis_amount(self):
return self.cleaned_data['basis_amount'] or Decimal('100')
def clean_barcode(self): def clean_barcode(self):
barcode = self.cleaned_data['barcode'].strip() barcode = self.cleaned_data['barcode'].strip()
if barcode and (not barcode.isascii() or not barcode.isdigit()): if barcode and (not barcode.isascii() or not barcode.isdigit()):
raise forms.ValidationError('Enter a numeric barcode.') raise forms.ValidationError('Enter a numeric barcode.')
if barcode and self.user and FoodProduct.objects.filter(owner=self.user, barcode=barcode).exists(): if barcode and self.user and FoodProduct.objects.filter(owner=self.user, barcode=barcode).exclude(pk=self.instance.pk).exists():
raise forms.ValidationError('This barcode is already saved in your foods.') raise forms.ValidationError('This barcode is already saved in your foods.')
return barcode return barcode
@@ -42,7 +50,7 @@ class ManualFoodForm(forms.ModelForm):
if basis: if basis:
factor = Decimal('100') / basis factor = Decimal('100') / basis
for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100',
'fibre_100', 'sugars_100', 'salt_100'): 'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100'):
value = data.get(name) value = data.get(name)
if value is not None and value * factor > Decimal('9999999.999'): if value is not None and value * factor > Decimal('9999999.999'):
self.add_error(name, 'This amount is too large for the chosen base quantity.') self.add_error(name, 'This amount is too large for the chosen base quantity.')
@@ -52,7 +60,7 @@ class ManualFoodForm(forms.ModelForm):
product = super().save(commit=False) product = super().save(commit=False)
factor = Decimal('100') / self.cleaned_data['basis_amount'] factor = Decimal('100') / self.cleaned_data['basis_amount']
for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100',
'fibre_100', 'sugars_100', 'salt_100'): 'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100'):
value = self.cleaned_data[name] value = self.cleaned_data[name]
setattr(product, name, (value * factor).quantize(Decimal('0.001')) if value is not None else None) setattr(product, name, (value * factor).quantize(Decimal('0.001')) if value is not None else None)
if commit: if commit:
@@ -162,9 +170,15 @@ class FoodLogForm(forms.ModelForm):
class FoodLogEditForm(FoodLogForm): class FoodLogEditForm(FoodLogForm):
edit_nutrition = forms.BooleanField(required=False, label='Use these nutrition values for this entry')
class Meta(FoodLogForm.Meta): class Meta(FoodLogForm.Meta):
fields = FoodLogForm.Meta.fields + ('quantity',) fields = FoodLogForm.Meta.fields + ('quantity', 'calories_kcal', 'carbohydrates_g',
labels = {**FoodLogForm.Meta.labels, 'quantity': 'Quantity (portions)'} 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')
labels = {**FoodLogForm.Meta.labels, 'quantity': 'Quantity (portions)',
'calories_kcal': 'Calories (kcal)', 'carbohydrates_g': 'Carbohydrates (g)',
'protein_g': 'Protein (g)', 'fat_g': 'Fat (g)', 'fibre_g': 'Fibre (g)',
'sugars_g': 'Sugars (g)', 'salt_g': 'Salt (g)'}
widgets = {**FoodLogForm.Meta.widgets, widgets = {**FoodLogForm.Meta.widgets,
'quantity': forms.NumberInput(attrs={'min': '0.01', 'step': '0.01'})} 'quantity': forms.NumberInput(attrs={'min': '0.01', 'step': '0.01'})}
@@ -234,19 +248,8 @@ class InventoryItemForm(forms.ModelForm):
return ' '.join(self.cleaned_data['category_name'].split()) return ' '.join(self.cleaned_data['category_name'].split())
class InventoryManualProductForm(forms.ModelForm): class InventoryManualProductForm(ManualFoodForm):
class Meta: class Meta(ManualFoodForm.Meta):
model = FoodProduct fields = ('product_name', 'brand', 'barcode', 'package_quantity', 'base_unit',
fields = ('product_name', 'brand', 'barcode', 'package_quantity') 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100',
'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100')
def __init__(self, *args, user=None, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
def clean_barcode(self):
barcode = self.cleaned_data['barcode'].strip()
if barcode and (not barcode.isascii() or not barcode.isdigit()):
raise forms.ValidationError('Enter a numeric barcode.')
if barcode and self.user and FoodProduct.objects.filter(owner=self.user, barcode=barcode).exists():
raise forms.ValidationError('This barcode is already saved in your products.')
return barcode
+1
View File
@@ -147,6 +147,7 @@ def cached_product(user, barcode, *, refresh=False):
raise ValueError('Enter a numeric barcode.') raise ValueError('Enter a numeric barcode.')
product = FoodProduct.objects.filter(owner=user, barcode=barcode).first() product = FoodProduct.objects.filter(owner=user, barcode=barcode).first()
if product and (product.source == FoodProduct.Source.MANUAL or if product and (product.source == FoodProduct.Source.MANUAL or
(isinstance(product.raw_data, dict) and product.raw_data.get('manual_nutrition_override')) or
(not refresh and product.fetched_at and product.fetched_at >= timezone.now() - timedelta(days=7))): (not refresh and product.fetched_at and product.fetched_at >= timezone.now() - timedelta(days=7))):
return product return product
if not settings.OPENFOODFACTS_ENABLED: if not settings.OPENFOODFACTS_ENABLED:
+3
View File
@@ -105,3 +105,6 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317}
.food-ring-laps{font-size:.7rem} .food-ring-laps{font-size:.7rem}
.food-macro--pink{--accent:#d45b8b} .food-macro--pink{--accent:#d45b8b}
.food-macro .food-ring{--accent:inherit} .food-macro .food-ring{--accent:inherit}
/* Shared product and entry nutrition forms. */
.product-form{display:grid;gap:1rem}.product-form .form-field,.entry-nutrition-fields .form-field{display:grid;gap:.3rem}.nutrition-fields{min-width:0;margin:0;padding:1rem;border:1px solid var(--food-border);border-radius:.9rem}.nutrition-fields legend{padding:0 .35rem;font-weight:700}.nutrition-fields p,.entry-nutrition-fields p{margin:.2rem 0 1rem;line-height:1.45;color:var(--food-muted)}.nutrition-fields>details,.entry-nutrition-fields{margin-top:1rem}.nutrition-fields summary,.entry-nutrition-fields summary{cursor:pointer;font-weight:700;min-height:44px;align-content:center}.nutrition-field-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.85rem}.nutrition-field-grid input{width:100%;min-width:0}.nutrition-fields .form-field{margin-bottom:.8rem}.entry-nutrition-fields{padding:1rem;border:1px solid var(--food-border);border-radius:.9rem}.entry-nutrition-fields .form-field:has(input[type=checkbox]){display:flex;flex-wrap:wrap;align-items:center;gap:.5rem}.entry-nutrition-fields .form-field:has(input[type=checkbox]) small{flex-basis:100%}@media(max-width:520px){.nutrition-field-grid{grid-template-columns:1fr}}
+1 -1
View File
@@ -1,6 +1,6 @@
{% extends 'planner/base.html' %}{% load static %} {% extends 'planner/base.html' %}{% load static %}
{% block title %}Edit food log · Tasknest{% endblock %} {% block title %}Edit food log · Tasknest{% endblock %}
{% block content %} {% block content %}
<link rel="stylesheet" href="{% static 'food/food.css' %}"> <link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261021-nutrition">
{% include 'food/partials/edit_content.html' %} {% include 'food/partials/edit_content.html' %}
{% endblock %} {% endblock %}
+1 -1
View File
@@ -3,7 +3,7 @@
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261012-actions"> {% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261012-actions">
<div class="food-form-page inventory-page"><a href="{% url 'food:inventory' %}">← Kitchen Inventory</a><h1>Add to inventory</h1> <div class="food-form-page inventory-page"><a href="{% url 'food:inventory' %}">← Kitchen Inventory</a><h1>Add to inventory</h1>
{% if product %} {% if product %}
<section class="food-card inventory-product">{% if product.image_url %}<img src="{{ product.image_url }}" alt="" loading="lazy">{% endif %}<div><h2>{{ product.product_name }}</h2>{% if product.brand %}<p>{{ product.brand }}</p>{% endif %}{% if product.package_quantity %}<p>{{ product.package_quantity }}</p>{% endif %}{% if off_categories %}<p><small>Open Food Facts: {{ off_categories }}</small></p>{% endif %}</div></section> <section class="food-card inventory-product">{% if product.image_url %}<img src="{{ product.image_url }}" alt="" loading="lazy">{% endif %}<div><h2>{{ product.product_name }}</h2>{% if product.brand %}<p>{{ product.brand }}</p>{% endif %}{% if product.package_quantity %}<p>{{ product.package_quantity }}</p>{% endif %}{% if off_categories %}<p><small>Open Food Facts: {{ off_categories }}</small></p>{% endif %}<p><a href="{% url 'food:product-edit' product.pk %}">View or edit product nutrition</a></p></div></section>
{% if existing %}<section class="food-card"><h2>Already in inventory</h2>{% for item in existing %}<div class="inventory-existing"><span>{{ item.location.name }} · Quantity {{ item.quantity }}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}</span><form method="post" action="{% url 'food:inventory-add-one' item.pk %}">{% csrf_token %}<button class="button button--secondary" type="submit">+1 existing item</button></form></div>{% endfor %}<p>Use the form below to add this product separately.</p></section>{% endif %} {% if existing %}<section class="food-card"><h2>Already in inventory</h2>{% for item in existing %}<div class="inventory-existing"><span>{{ item.location.name }} · Quantity {{ item.quantity }}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}</span><form method="post" action="{% url 'food:inventory-add-one' item.pk %}">{% csrf_token %}<button class="button button--secondary" type="submit">+1 existing item</button></form></div>{% endfor %}<p>Use the form below to add this product separately.</p></section>{% endif %}
<form class="food-card inventory-form" method="post">{% csrf_token %}<input type="hidden" name="product" value="{{ product.pk }}">{{ form.non_field_errors }} <form class="food-card inventory-form" method="post">{% csrf_token %}<input type="hidden" name="product" value="{{ product.pk }}">{{ form.non_field_errors }}
{% for field in form %}<div class="form-field">{{ field.label_tag }}{% if field.name == 'quantity' %}<div class="inventory-quantity" data-inventory-quantity><button type="button" data-inventory-step="-1" aria-label="Decrease quantity">−</button>{{ field }}<button type="button" data-inventory-step="1" aria-label="Increase quantity">+</button></div>{% else %}{{ field }}{% endif %}{{ field.errors }}</div>{% endfor %} {% for field in form %}<div class="form-field">{{ field.label_tag }}{% if field.name == 'quantity' %}<div class="inventory-quantity" data-inventory-quantity><button type="button" data-inventory-step="-1" aria-label="Decrease quantity">−</button>{{ field }}<button type="button" data-inventory-step="1" aria-label="Increase quantity">+</button></div>{% else %}{{ field }}{% endif %}{{ field.errors }}</div>{% endfor %}
+1 -1
View File
@@ -1,3 +1,3 @@
{% extends 'planner/base.html' %}{% load static %} {% extends 'planner/base.html' %}{% load static %}
{% block title %}Edit inventory item · Tasknest{% endblock %} {% block title %}Edit inventory item · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div class="food-form-page inventory-page"><a href="{% url 'food:inventory' %}">← Kitchen Inventory</a><h1>Edit {{ item.product.product_name }}</h1><form method="post" class="food-card inventory-form">{% csrf_token %}{{ form.non_field_errors }}{% for field in form %}<div class="form-field">{{ field.label_tag }}{% if field.name == 'quantity' %}<div class="inventory-quantity" data-inventory-quantity><button type="button" data-inventory-step="-1" aria-label="Decrease quantity">−</button>{{ field }}<button type="button" data-inventory-step="1" aria-label="Increase quantity">+</button></div>{% else %}{{ field }}{% endif %}{{ field.errors }}</div>{% endfor %}<datalist id="inventory-locations">{% for location in locations %}<option value="{{ location.name }}">{% endfor %}</datalist><datalist id="inventory-categories">{% for category in categories %}<option value="{{ category.name }}">{% endfor %}</datalist><button class="button" type="submit">Save changes</button></form></div><script src="{% static 'food/inventory.js' %}" defer></script>{% endblock %} {% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div class="food-form-page inventory-page"><a href="{% url 'food:inventory' %}">← Kitchen Inventory</a><h1>Edit {{ item.product.product_name }}</h1><p>This form changes stock for this package. <a href="{% url 'food:product-edit' item.product.pk %}">View or edit product nutrition</a> for future food logs.</p><form method="post" class="food-card inventory-form">{% csrf_token %}{{ form.non_field_errors }}{% for field in form %}<div class="form-field">{{ field.label_tag }}{% if field.name == 'quantity' %}<div class="inventory-quantity" data-inventory-quantity><button type="button" data-inventory-step="-1" aria-label="Decrease quantity">−</button>{{ field }}<button type="button" data-inventory-step="1" aria-label="Increase quantity">+</button></div>{% else %}{{ field }}{% endif %}{{ field.errors }}</div>{% endfor %}<datalist id="inventory-locations">{% for location in locations %}<option value="{{ location.name }}">{% endfor %}</datalist><datalist id="inventory-categories">{% for category in categories %}<option value="{{ category.name }}">{% endfor %}</datalist><button class="button" type="submit">Save changes</button></form></div><script src="{% static 'food/inventory.js' %}" defer></script>{% endblock %}
@@ -1,3 +1,5 @@
{% extends 'planner/base.html' %}{% load static %} {% extends 'planner/base.html' %}{% load static %}
{% block title %}Create inventory product · Tasknest{% endblock %} {% block title %}Create inventory product · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div class="food-form-page"><a href="{% url 'food:inventory-add' %}">← Add item</a><h1>Create product</h1><p>Save a product to the shared food catalogue. Nutrition can be added later.</p><form method="post" class="food-card inventory-form">{% csrf_token %}{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Continue to inventory</button></form></div>{% endblock %} {% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261021-nutrition"><div class="food-form-page"><a href="{% url 'food:inventory-add' %}">← Add item</a><h1>Create product</h1><p>Save a product for both Kitchen Inventory and Food Diary. Package size describes stock; nutrition is entered separately for the chosen basis.</p><form method="post" class="food-card product-form">{% csrf_token %}{{ form.non_field_errors }}
{% for field in form %}{% if field.name == 'product_name' or field.name == 'brand' or field.name == 'barcode' or field.name == 'package_quantity' %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endif %}{% endfor %}
{% include 'food/partials/product_nutrition_fields.html' %}<button class="button" type="submit">Continue to inventory</button></form></div>{% endblock %}
@@ -8,6 +8,7 @@
</form> </form>
{% for card in cards %}<article class="food-card inventory-product-card"> {% for card in cards %}<article class="food-card inventory-product-card">
<div class="inventory-product-heading">{% if card.product.image_url %}<img src="{{ card.product.image_url }}" alt="" loading="lazy">{% endif %}<div><h2>{{ card.product.product_name }}</h2>{% if card.product.brand %}<p>{{ card.product.brand }}</p>{% endif %}<p><strong>{{ card.total|floatformat:-3 }} {% if card.unit == "packs" and card.total == 1 %}pack{% else %}{{ card.unit }}{% endif %} remaining</strong> · {{ card.packages|length }} package{{ card.packages|length|pluralize }}</p></div></div> <div class="inventory-product-heading">{% if card.product.image_url %}<img src="{{ card.product.image_url }}" alt="" loading="lazy">{% endif %}<div><h2>{{ card.product.product_name }}</h2>{% if card.product.brand %}<p>{{ card.product.brand }}</p>{% endif %}<p><strong>{{ card.total|floatformat:-3 }} {% if card.unit == "packs" and card.total == 1 %}pack{% else %}{{ card.unit }}{% endif %} remaining</strong> · {{ card.packages|length }} package{{ card.packages|length|pluralize }}</p></div></div>
<p><a href="{% url 'food:product-edit' card.product.pk %}">View or edit product nutrition</a></p>
<details class="inventory-packages"><summary>View packages</summary><div class="inventory-package-list">{% for item in card.packages %}<div class="inventory-package"><div class="inventory-package-fill" role="img" aria-label="{{ item.percentage_remaining }}% remaining"><span style="height:{{ item.percentage_remaining }}%"></span></div><div><strong>Pack {{ forloop.counter }} · {{ item.package_status|title }}</strong><p>{% if item.original_amount %}{{ item.remaining_amount|floatformat:-3 }} / {{ item.original_amount|floatformat:-3 }} {{ item.inventory_unit }} · {{ item.percentage_remaining }}% remaining{% else %}{{ item.quantity }} pack{{ item.quantity|pluralize }} · size unknown{% endif %}</p><small>{{ item.location.name }}{% if item.category %} · {{ item.category.name }}{% endif %}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}</small><div><a href="{% url 'food:inventory-edit' item.pk %}">Edit package</a></div></div></div>{% endfor %}</div></details> <details class="inventory-packages"><summary>View packages</summary><div class="inventory-package-list">{% for item in card.packages %}<div class="inventory-package"><div class="inventory-package-fill" role="img" aria-label="{{ item.percentage_remaining }}% remaining"><span style="height:{{ item.percentage_remaining }}%"></span></div><div><strong>Pack {{ forloop.counter }} · {{ item.package_status|title }}</strong><p>{% if item.original_amount %}{{ item.remaining_amount|floatformat:-3 }} / {{ item.original_amount|floatformat:-3 }} {{ item.inventory_unit }} · {{ item.percentage_remaining }}% remaining{% else %}{{ item.quantity }} pack{{ item.quantity|pluralize }} · size unknown{% endif %}</p><small>{{ item.location.name }}{% if item.category %} · {{ item.category.name }}{% endif %}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}</small><div><a href="{% url 'food:inventory-edit' item.pk %}">Edit package</a></div></div></div>{% endfor %}</div></details>
<details class="inventory-use"><summary>Use amount</summary><form method="post" action="{% url 'food:inventory-preview' card.product.pk %}" hx-post="{% url 'food:inventory-preview' card.product.pk %}" hx-target="#inventory-preview-{{ card.product.pk }}-{{ card.unit }}" hx-swap="innerHTML" class="inventory-use-form">{% csrf_token %}<label>Amount<input type="number" name="amount" min="{% if card.count_unit %}1{% else %}0.001{% endif %}" step="{% if card.count_unit %}1{% else %}0.001{% endif %}" required inputmode="decimal"></label><label>Unit<select name="unit">{% for unit in card.units %}<option value="{{ unit }}" {% if unit == card.unit %}selected{% endif %}>{{ unit }}</option>{% endfor %}</select></label><label>Package (optional)<select name="package_id"><option value="">Automatic selection</option>{% for item in card.packages %}<option value="{{ item.api_id }}">Pack {{ forloop.counter }} · {% if item.remaining_amount is not None %}{{ item.remaining_amount|floatformat:-3 }} {{ item.inventory_unit }}{% else %}{{ item.quantity }} pack{{ item.quantity|pluralize }}{% endif %}</option>{% endfor %}</select></label><button class="button button--secondary" type="submit">Preview</button></form><div id="inventory-preview-{{ card.product.pk }}-{{ card.unit }}" aria-live="polite"></div></details> <details class="inventory-use"><summary>Use amount</summary><form method="post" action="{% url 'food:inventory-preview' card.product.pk %}" hx-post="{% url 'food:inventory-preview' card.product.pk %}" hx-target="#inventory-preview-{{ card.product.pk }}-{{ card.unit }}" hx-swap="innerHTML" class="inventory-use-form">{% csrf_token %}<label>Amount<input type="number" name="amount" min="{% if card.count_unit %}1{% else %}0.001{% endif %}" step="{% if card.count_unit %}1{% else %}0.001{% endif %}" required inputmode="decimal"></label><label>Unit<select name="unit">{% for unit in card.units %}<option value="{{ unit }}" {% if unit == card.unit %}selected{% endif %}>{{ unit }}</option>{% endfor %}</select></label><label>Package (optional)<select name="package_id"><option value="">Automatic selection</option>{% for item in card.packages %}<option value="{{ item.api_id }}">Pack {{ forloop.counter }} · {% if item.remaining_amount is not None %}{{ item.remaining_amount|floatformat:-3 }} {{ item.inventory_unit }}{% else %}{{ item.quantity }} pack{{ item.quantity|pluralize }}{% endif %}</option>{% endfor %}</select></label><button class="button button--secondary" type="submit">Preview</button></form><div id="inventory-preview-{{ card.product.pk }}-{{ card.unit }}" aria-live="polite"></div></details>
</article>{% empty %}<section class="food-card"><p>No inventory items found.</p><a class="button" href="{% url 'food:inventory-add' %}">Add your first item</a></section>{% endfor %} </article>{% empty %}<section class="food-card"><p>No inventory items found.</p><a class="button" href="{% url 'food:inventory-add' %}">Add your first item</a></section>{% endfor %}
+3 -1
View File
@@ -1,3 +1,5 @@
{% extends 'planner/base.html' %}{% load static %} {% extends 'planner/base.html' %}{% load static %}
{% block title %}Create food · Tasknest{% endblock %} {% block title %}Create food · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div class="food-form-page"><a href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">← Back to foods</a><h1>Create a food</h1><p>Enter nutrition for the base quantity and unit you choose. Missing optional values stay unknown.</p><form method="post" class="food-card">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}">{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save food</button></form></div>{% endblock %} {% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261021-nutrition"><div class="food-form-page"><a href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">← Back to foods</a><h1>Create a food</h1><p>Save nutrition once, then choose how much to log. You can correct this product later; existing diary entries keep their recorded values.</p><form method="post" class="food-card product-form">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}">{{ form.non_field_errors }}
{% for field in form %}{% if field.name == 'product_name' or field.name == 'brand' or field.name == 'barcode' %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endif %}{% endfor %}
{% include 'food/partials/product_nutrition_fields.html' %}<button class="button" type="submit">Save food</button></form></div>{% endblock %}
@@ -12,11 +12,13 @@
<dt>Carbohydrates</dt><dd>{{ product.carbohydrates_100|default_if_none:'—' }} g</dd> <dt>Carbohydrates</dt><dd>{{ product.carbohydrates_100|default_if_none:'—' }} g</dd>
<dt>Protein</dt><dd>{{ product.protein_100|default_if_none:'—' }} g</dd> <dt>Protein</dt><dd>{{ product.protein_100|default_if_none:'—' }} g</dd>
<dt>Fat</dt><dd>{{ product.fat_100|default_if_none:'—' }} g</dd> <dt>Fat</dt><dd>{{ product.fat_100|default_if_none:'—' }} g</dd>
<dt>Saturated fat</dt><dd>{{ product.saturated_fat_100|default_if_none:'—' }} g</dd>
<dt>Sugars</dt><dd>{{ product.sugars_100|default_if_none:'—' }} g</dd> <dt>Sugars</dt><dd>{{ product.sugars_100|default_if_none:'—' }} g</dd>
<dt>Fibre</dt><dd>{{ product.fibre_100|default_if_none:'—' }} g</dd> <dt>Fibre</dt><dd>{{ product.fibre_100|default_if_none:'—' }} g</dd>
<dt>Salt</dt><dd>{{ product.salt_100|default_if_none:'—' }} g</dd> <dt>Salt</dt><dd>{{ product.salt_100|default_if_none:'—' }} g</dd>
</dl></details> </dl></details>
{% if product.source == 'openfoodfacts' %}<p class="food-attribution">Product data from <a href="https://world.openfoodfacts.org/product/{{ product.barcode }}" rel="noopener noreferrer">Open Food Facts</a>.</p>{% endif %} {% if product.source == 'openfoodfacts' %}<p class="food-attribution">Product data from <a href="https://world.openfoodfacts.org/product/{{ product.barcode }}" rel="noopener noreferrer">Open Food Facts</a>.</p>{% endif %}
<p><a href="{% url 'food:product-edit' product.pk %}">Edit product nutrition</a></p>
</section> </section>
<form method="post" class="food-card" hx-post="{% url 'food:add' %}" hx-target="#food-workspace" hx-swap="outerHTML"> <form method="post" class="food-card" hx-post="{% url 'food:add' %}" hx-target="#food-workspace" hx-swap="outerHTML">
{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="product" value="{{ product.pk }}"><input type="hidden" name="submission_id" value="{{ submission_id }}"> {% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="product" value="{{ product.pk }}"><input type="hidden" name="submission_id" value="{{ submission_id }}">
@@ -50,11 +52,11 @@
<div id="food-recents-list"><h2>Recent</h2>{% include 'food/partials/product_list.html' with products=recents %}</div> <div id="food-recents-list"><h2>Recent</h2>{% include 'food/partials/product_list.html' with products=recents %}</div>
{% else %}{% include 'food/partials/product_list.html' with products=products %}{% endif %} {% else %}{% include 'food/partials/product_list.html' with products=products %}{% endif %}
<div class="food-actions"><a class="button" href="{% url 'food:manual' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Create a food manually</a> <div class="food-actions"><a class="button" href="{% url 'food:manual' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Create a food manually</a>
<a class="button" href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Scan barcode</a> {% if not is_demo_account %}<a class="button" href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Scan barcode</a>
<a class="button button--secondary" href="{% url 'food:external-search' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;q={{ query|urlencode }}">Search Open Food Facts</a></div> <a class="button button--secondary" href="{% url 'food:external-search' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;q={{ query|urlencode }}">Search Open Food Facts</a>{% endif %}</div>
<form method="post" action="{% url 'food:import-product' %}" class="food-barcode-form">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}"><label for="food-barcode">Barcode</label><input id="food-barcode" name="barcode" inputmode="numeric" pattern="[0-9]+" required><button class="button button--secondary" type="submit">Look up barcode</button></form> {% if not is_demo_account %}<form method="post" action="{% url 'food:import-product' %}" class="food-barcode-form">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}"><label for="food-barcode">Barcode</label><input id="food-barcode" name="barcode" inputmode="numeric" pattern="[0-9]+" required><button class="button button--secondary" type="submit">Look up barcode</button></form>{% endif %}
<p class="food-attribution">External product data from <a href="https://world.openfoodfacts.org/" rel="noopener noreferrer">Open Food Facts</a>.</p> {% if not is_demo_account %}<p class="food-attribution">External product data from <a href="https://world.openfoodfacts.org/" rel="noopener noreferrer">Open Food Facts</a>.</p>{% endif %}
{% endif %} {% endif %}
</div> </div>
{% if product %}<script src="{% static 'food/portions.js' %}" defer></script>{% endif %} {% if product %}<script src="{% static 'food/portions.js' %}" defer></script>{% endif %}
{% if not product %}<nav class="food-mobile-switch" aria-label="Add food method"><span aria-current="page">Search</span><a href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Barcode</a></nav>{% endif %} {% if not product and not is_demo_account %}<nav class="food-mobile-switch" aria-label="Add food method"><span aria-current="page">Search</span><a href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Barcode</a></nav>{% endif %}
@@ -9,6 +9,21 @@
<form method="post" class="food-card food-entry-form" hx-post="{% url 'food:edit' entry.pk %}" hx-target="#food-workspace" hx-swap="outerHTML">{% csrf_token %} <form method="post" class="food-card food-entry-form" hx-post="{% url 'food:edit' entry.pk %}" hx-target="#food-workspace" hx-swap="outerHTML">{% csrf_token %}
{% include 'food/partials/portion_fields.html' %} {% include 'food/partials/portion_fields.html' %}
<div class="form-field">{{ form.quantity.label_tag }}{{ form.quantity }}{{ form.quantity.errors }}<small>Multiplies the selected portion. For example, 2 means two of that portion.</small></div> <div class="form-field">{{ form.quantity.label_tag }}{{ form.quantity }}{{ form.quantity.errors }}<small>Multiplies the selected portion. For example, 2 means two of that portion.</small></div>
<details class="entry-nutrition-fields" {% if form.edit_nutrition.value or form.calories_kcal.errors or form.carbohydrates_g.errors or form.protein_g.errors or form.fat_g.errors or form.fibre_g.errors or form.sugars_g.errors or form.salt_g.errors %}open{% endif %}>
<summary>Correct nutrition for this entry</summary>
<p>Values are for one logged portion ({{ entry.amount|floatformat:-3 }} {{ entry.unit }}), before the quantity multiplier. Leave a value blank if unknown. This does not change the saved product.</p>
<div class="form-field">{{ form.edit_nutrition.label_tag }}{{ form.edit_nutrition }}{{ form.edit_nutrition.errors }}<small>Without this selection, nutrition scales automatically when the portion amount changes.</small></div>
<div class="nutrition-field-grid">
<div class="form-field">{{ form.calories_kcal.label_tag }}{{ form.calories_kcal }}{{ form.calories_kcal.errors }}</div>
<div class="form-field">{{ form.carbohydrates_g.label_tag }}{{ form.carbohydrates_g }}{{ form.carbohydrates_g.errors }}</div>
<div class="form-field">{{ form.protein_g.label_tag }}{{ form.protein_g }}{{ form.protein_g.errors }}</div>
<div class="form-field">{{ form.fat_g.label_tag }}{{ form.fat_g }}{{ form.fat_g.errors }}</div>
<div class="form-field">{{ form.fibre_g.label_tag }}{{ form.fibre_g }}{{ form.fibre_g.errors }}</div>
<div class="form-field">{{ form.sugars_g.label_tag }}{{ form.sugars_g }}{{ form.sugars_g.errors }}</div>
<div class="form-field">{{ form.salt_g.label_tag }}{{ form.salt_g }}{{ form.salt_g.errors }}</div>
</div>
</details>
{% if product %}<p><a href="{% url 'food:product-edit' product.pk %}">Edit saved product nutrition for future logs</a></p>{% endif %}
<button class="button" type="submit">Save changes</button> <button class="button" type="submit">Save changes</button>
</form> </form>
<form method="post" action="{% url 'food:delete' entry.pk %}" onsubmit="return confirm('Delete this food entry?')" hx-post="{% url 'food:delete' entry.pk %}" hx-target="#food-workspace" hx-swap="outerHTML">{% csrf_token %}<button type="submit" class="button button--secondary">Delete entry</button></form> <form method="post" action="{% url 'food:delete' entry.pk %}" onsubmit="return confirm('Delete this food entry?')" hx-post="{% url 'food:delete' entry.pk %}" hx-target="#food-workspace" hx-swap="outerHTML">{% csrf_token %}<button type="submit" class="button button--secondary">Delete entry</button></form>
@@ -1,5 +1,5 @@
<div class="food-actions inventory-product-actions"> <div class="food-actions inventory-product-actions">
<a class="button" href="{% url 'food:scanner' %}?mode=inventory">Scan barcode</a> {% if not is_demo_account %}<a class="button" href="{% url 'food:scanner' %}?mode=inventory">Scan barcode</a>
<a class="button button--secondary" href="{% url 'food:inventory-external' %}?q={{ query|urlencode }}">Search Open Food Facts</a> <a class="button button--secondary" href="{% url 'food:inventory-external' %}?q={{ query|urlencode }}">Search Open Food Facts</a>{% endif %}
<a class="button button--secondary" href="{% url 'food:inventory-manual' %}">Create manual product</a> <a class="button button--secondary" href="{% url 'food:inventory-manual' %}">Create manual product</a>
</div> </div>
@@ -0,0 +1,21 @@
<fieldset class="nutrition-fields">
<legend>Nutrition</legend>
<p>Enter values for the basis amount and unit below. Leave a value blank when it is unknown; zero means the label says zero.</p>
<div class="form-field">{{ form.basis_amount.label_tag }}{{ form.basis_amount }}{{ form.basis_amount.errors }}</div>
<div class="form-field">{{ form.base_unit.label_tag }}{{ form.base_unit }}{{ form.base_unit.errors }}{% if form.base_unit.field.disabled %}<small>The nutrition unit is fixed for an existing product.</small>{% endif %}</div>
<div class="nutrition-field-grid">
<div class="form-field">{{ form.energy_kcal_100.label_tag }}{{ form.energy_kcal_100 }}{{ form.energy_kcal_100.errors }}</div>
<div class="form-field">{{ form.carbohydrates_100.label_tag }}{{ form.carbohydrates_100 }}{{ form.carbohydrates_100.errors }}</div>
<div class="form-field">{{ form.protein_100.label_tag }}{{ form.protein_100 }}{{ form.protein_100.errors }}</div>
<div class="form-field">{{ form.fat_100.label_tag }}{{ form.fat_100 }}{{ form.fat_100.errors }}</div>
</div>
<details {% if form.saturated_fat_100.errors or form.fibre_100.errors or form.sugars_100.errors or form.salt_100.errors %}open{% endif %}>
<summary>More nutrients</summary>
<div class="nutrition-field-grid">
<div class="form-field">{{ form.saturated_fat_100.label_tag }}{{ form.saturated_fat_100 }}{{ form.saturated_fat_100.errors }}</div>
<div class="form-field">{{ form.fibre_100.label_tag }}{{ form.fibre_100 }}{{ form.fibre_100.errors }}</div>
<div class="form-field">{{ form.sugars_100.label_tag }}{{ form.sugars_100 }}{{ form.sugars_100.errors }}</div>
<div class="form-field">{{ form.salt_100.label_tag }}{{ form.salt_100 }}{{ form.salt_100.errors }}</div>
</div>
</details>
</fieldset>
@@ -0,0 +1,5 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Edit product nutrition · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261021-nutrition"><div class="food-form-page"><a href="{% url 'food:inventory' %}">← Kitchen Inventory</a><h1>Edit {{ product.product_name }}</h1><p>Changes to this product affect future food logs. Existing Food Diary entries keep their recorded nutrition; edit an entry to correct its own values.</p>{% if product.source == 'openfoodfacts' %}<p>Imported from Open Food Facts{% if product.raw_data.manual_nutrition_override %}; nutrition has been corrected manually{% endif %}.</p>{% endif %}<form method="post" class="food-card product-form">{% csrf_token %}{{ form.non_field_errors }}
{% for field in form %}{% if field.name == 'product_name' or field.name == 'brand' or field.name == 'barcode' %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endif %}{% endfor %}
{% include 'food/partials/product_nutrition_fields.html' %}<button class="button" type="submit">Save product</button></form><p><a href="{% url 'food:inventory' %}">Kitchen Inventory</a> · <a href="{% url 'food:add' %}?product={{ product.pk }}">Log this food</a></p></div>{% endblock %}
+136
View File
@@ -0,0 +1,136 @@
from decimal import Decimal
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from .models import FoodLogEntry, FoodProduct
from .services.logging import apply_product_snapshot
from .services.openfoodfacts import cached_product
class NutritionUiTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user('nutrition-ui', password='test')
self.other = get_user_model().objects.create_user('nutrition-other', password='test')
self.client.force_login(self.user)
def test_inventory_product_creation_preserves_unknown_and_zero(self):
response = self.client.post(reverse('food:inventory-manual'), {
'product_name': 'Lentils', 'brand': '', 'barcode': '', 'package_quantity': '250 g',
'base_unit': 'g', 'basis_amount': '250', 'energy_kcal_100': '300',
'carbohydrates_100': '45', 'protein_100': '', 'fat_100': '',
'saturated_fat_100': '', 'fibre_100': '', 'sugars_100': '0', 'salt_100': '',
})
product = FoodProduct.objects.get(owner=self.user)
self.assertRedirects(response, f"{reverse('food:inventory-add')}?product={product.pk}",
fetch_redirect_response=False)
self.assertEqual(product.energy_kcal_100, Decimal('120.000'))
self.assertEqual(product.carbohydrates_100, Decimal('18.000'))
self.assertEqual(product.sugars_100, Decimal('0.000'))
self.assertIsNone(product.protein_100)
self.assertIsNone(product.salt_100)
self.assertEqual(product.package_amount, Decimal('250'))
def test_diary_manual_creation_allows_unknown_nutrients(self):
response = self.client.post(reverse('food:manual'), {
'product_name': 'Oat drink', 'brand': '', 'barcode': '',
'base_unit': 'ml', 'basis_amount': '200', 'energy_kcal_100': '80',
'carbohydrates_100': '', 'protein_100': '0', 'fat_100': '',
'saturated_fat_100': '', 'fibre_100': '', 'sugars_100': '', 'salt_100': '',
'meal': 'breakfast',
})
product = FoodProduct.objects.get(owner=self.user, product_name='Oat drink')
self.assertEqual(response.status_code, 302)
self.assertEqual(product.base_unit, 'ml')
self.assertEqual(product.energy_kcal_100, Decimal('40.000'))
self.assertEqual(product.protein_100, Decimal('0.000'))
self.assertIsNone(product.carbohydrates_100)
def test_invalid_product_keeps_entered_nutrition(self):
response = self.client.post(reverse('food:inventory-manual'), {
'product_name': 'Oats', 'brand': '', 'barcode': 'invalid',
'package_quantity': '250 g', 'base_unit': 'g', 'basis_amount': '250',
'energy_kcal_100': '300', 'protein_100': '0',
})
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'Enter a numeric barcode.')
self.assertContains(response, 'value="300"')
self.assertFalse(FoodProduct.objects.filter(owner=self.user, product_name='Oats').exists())
def test_product_edit_changes_future_logs_without_rewriting_old_entries(self):
product = FoodProduct.objects.create(owner=self.user, product_name='Oats',
energy_kcal_100=Decimal('100'), protein_100=Decimal('10'))
old = FoodLogEntry(user=self.user, date='2026-10-21', meal='breakfast',
amount=Decimal('100'), unit='g')
apply_product_snapshot(old, product)
old.save()
response = self.client.post(reverse('food:product-edit', args=[product.pk]), {
'product_name': 'Oats', 'brand': '', 'barcode': '', 'base_unit': 'g',
'basis_amount': '100', 'energy_kcal_100': '150', 'protein_100': '12',
'carbohydrates_100': '', 'fat_100': '', 'saturated_fat_100': '',
'fibre_100': '3', 'sugars_100': '', 'salt_100': '',
})
self.assertRedirects(response, reverse('food:product-edit', args=[product.pk]),
fetch_redirect_response=False)
product.refresh_from_db()
old.refresh_from_db()
self.assertEqual(product.energy_kcal_100, Decimal('150.000'))
self.assertEqual(product.fibre_100, Decimal('3.000'))
self.assertEqual(old.calories_kcal, Decimal('100.000'))
self.assertEqual(old.protein_g, Decimal('10.000'))
new = FoodLogEntry(user=self.user, date='2026-10-21', meal='lunch',
amount=Decimal('100'), unit='g')
apply_product_snapshot(new, product)
self.assertEqual(new.calories_kcal, Decimal('150.000'))
self.assertEqual(new.fibre_g, Decimal('3.000'))
self.assertEqual(self.client.get(reverse('food:product-edit', args=[
FoodProduct.objects.create(owner=self.other, product_name='Private').pk])).status_code, 404)
def test_entry_only_correction_and_later_portion_scaling(self):
product = FoodProduct.objects.create(owner=self.user, product_name='Soup',
energy_kcal_100=Decimal('100'), sugars_100=None)
entry = FoodLogEntry(user=self.user, date='2026-10-21', meal='lunch',
amount=Decimal('100'), unit='g')
apply_product_snapshot(entry, product)
entry.save()
url = reverse('food:edit', args=[entry.pk])
response = self.client.post(url, {
'meal': 'lunch', 'portion': 'custom', 'portion_count': '1',
'amount': '100', 'unit': 'g', 'quantity': '1', 'edit_nutrition': 'on',
'calories_kcal': '125', 'carbohydrates_g': '', 'protein_g': '',
'fat_g': '', 'fibre_g': '', 'sugars_g': '0', 'salt_g': '',
})
self.assertEqual(response.status_code, 302)
entry.refresh_from_db()
product.refresh_from_db()
self.assertEqual(entry.calories_kcal, Decimal('125.000'))
self.assertEqual(entry.sugars_g, Decimal('0.000'))
self.assertIsNone(entry.salt_g)
self.assertEqual(product.energy_kcal_100, Decimal('100'))
response = self.client.post(url, {'meal': 'lunch', 'portion': 'custom',
'portion_count': '1', 'amount': '200', 'unit': 'g', 'quantity': '1'})
self.assertEqual(response.status_code, 302)
entry.refresh_from_db()
self.assertEqual(entry.calories_kcal, Decimal('250.000'))
self.assertEqual(entry.sugars_g, Decimal('0.000'))
self.assertIsNone(entry.salt_g)
@patch('food.services.openfoodfacts.OpenFoodFactsClient.get_product')
def test_corrected_import_is_not_refreshed_over_manual_nutrition(self, get_product):
product = FoodProduct.objects.create(owner=self.user, product_name='Imported soup',
barcode='123456789', source=FoodProduct.Source.OPEN_FOOD_FACTS,
energy_kcal_100=Decimal('100'), raw_data={'code': '123456789'})
response = self.client.post(reverse('food:product-edit', args=[product.pk]), {
'product_name': 'Imported soup', 'brand': '', 'barcode': '123456789',
'base_unit': 'g', 'basis_amount': '100', 'energy_kcal_100': '120',
'carbohydrates_100': '', 'protein_100': '', 'fat_100': '',
'saturated_fat_100': '', 'fibre_100': '', 'sugars_100': '', 'salt_100': '',
})
self.assertEqual(response.status_code, 302)
product.refresh_from_db()
self.assertTrue(product.raw_data['manual_nutrition_override'])
self.assertEqual(cached_product(self.user, product.barcode, refresh=True).energy_kcal_100,
Decimal('120.000'))
get_product.assert_not_called()
+1
View File
@@ -32,5 +32,6 @@ urlpatterns = [
path('attachments/<uuid:identifier>/file/', views.attachment_file, name='attachment-file'), path('attachments/<uuid:identifier>/file/', views.attachment_file, name='attachment-file'),
path('product/<int:pk>/favourite/', views.toggle_favourite, name='toggle-favourite'), path('product/<int:pk>/favourite/', views.toggle_favourite, name='toggle-favourite'),
path('product/<int:pk>/hydration/', views.product_hydration, name='product-hydration'), path('product/<int:pk>/hydration/', views.product_hydration, name='product-hydration'),
path('product/<int:pk>/edit/', views.edit_product, name='product-edit'),
path('export/<str:period>/', views.export_csv, name='export'), path('export/<str:period>/', views.export_csv, name='export'),
] ]
+23 -1
View File
@@ -421,7 +421,11 @@ def edit_entry(request, pk):
updated = form.save(commit=False) updated = form.save(commit=False)
factor = updated.amount / original_amount factor = updated.amount / original_amount
for field, original in original_nutrients.items(): for field, original in original_nutrients.items():
setattr(updated, field, (original * factor).quantize(Decimal('0.001')) if original is not None else None) if form.cleaned_data['edit_nutrition']:
value = form.cleaned_data[field]
else:
value = (original * factor).quantize(Decimal('0.001')) if original is not None else None
setattr(updated, field, value)
with transaction.atomic(): with transaction.atomic():
sync_food_hydration(updated) sync_food_hydration(updated)
updated.full_clean() updated.full_clean()
@@ -441,6 +445,24 @@ def edit_entry(request, pk):
'portion_options': _portion_options(form, product)}) 'portion_options': _portion_options(form, product)})
@login_required
@require_http_methods(['GET', 'POST'])
def edit_product(request, pk):
product = get_object_or_404(FoodProduct, pk=pk, owner=request.user)
form = ManualFoodForm(request.POST or None, instance=product, user=request.user)
if request.method == 'POST' and form.is_valid():
product = form.save(commit=False)
nutrition_fields = {'energy_kcal_100', 'carbohydrates_100', 'protein_100',
'fat_100', 'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100'}
if product.source == FoodProduct.Source.OPEN_FOOD_FACTS and nutrition_fields.intersection(form.changed_data):
product.raw_data = {**(product.raw_data if isinstance(product.raw_data, dict) else {}),
'manual_nutrition_override': True}
product.save()
messages.success(request, 'Product saved. Existing diary entries keep their recorded nutrition.')
return redirect('food:product-edit', pk=product.pk)
return render(request, 'food/product_edit.html', {'form': form, 'product': product})
@login_required @login_required
@require_POST @require_POST
def delete_entry(request, pk): def delete_entry(request, pk):
View File
+91
View File
@@ -0,0 +1,91 @@
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from food.api import _idempotent, _json, _uuid, api_view, error
from recipes.models import Recipe
from .models import GroceryItem
from .services import GroceryError, add, apply_recipe, edit, product_for, recipe_preview, search
def _data(item):
return {'id': str(item.pk), 'name': item.name, 'quantity': str(item.quantity), 'unit': item.unit,
'category': item.category, 'product_id': str(item.product.api_id) if item.product_id else None,
'notes': item.notes, 'status': item.status,
'purchased_at': item.purchased_at.isoformat() if item.purchased_at else None,
'sources': [{'recipe_id': str(source.recipe.api_id), 'recipe_title': source.recipe.title,
'ingredient_id': source.ingredient_id} for source in item.sources.all()]}
def _page(request, qs):
try:
limit = min(max(int(request.GET.get('limit', 30)), 1), 100)
offset = max(int(request.GET.get('offset', 0)), 0)
except ValueError:
raise GroceryError('Invalid pagination.') from None
return JsonResponse({'count': qs.count(), 'results': [_data(item) for item in qs[offset:offset+limit]]})
@api_view({'GET': 'inventory:read', 'POST': 'inventory:write'}, ('GET', 'POST'))
def collection(request):
if request.method == 'GET':
product = product_for(request.api_user, request.GET.get('product_id'))
return _page(request, search(request.api_user, query=request.GET.get('query', ''),
category=request.GET.get('category', ''), product=product, status=request.GET.get('status', 'needed')))
data = _json(request)
if set(data) - {'name', 'quantity', 'unit', 'category', 'product_id', 'notes'}:
raise GroceryError('Unsupported grocery field.')
def action():
item = add(request.api_user, name=data.get('name', ''), quantity=data.get('quantity'),
unit=data.get('unit', 'pieces'), category=data.get('category', ''),
product=product_for(request.api_user, data.get('product_id')), notes=data.get('notes', ''))
return JsonResponse(_data(item), status=201)
return _idempotent(request, data, action)
@api_view({'PATCH': 'inventory:write', 'DELETE': 'inventory:write'}, ('PATCH', 'DELETE'))
def item(request, identifier):
item = GroceryItem.objects.filter(user=request.api_user, pk=identifier).first()
if item is None:
return error('not_found', 'Grocery item not found.', 404)
if request.method == 'DELETE':
item.delete()
return JsonResponse({'id': str(identifier), 'deleted': True})
return JsonResponse(_data(edit(request.api_user, identifier, _json(request))))
def _recipe(user, identifier):
return Recipe.objects.filter(owner=user, api_id=identifier).first()
def _plan_data(plan):
return {'recipe_id': str(plan['recipe'].api_id), 'servings': str(plan['servings']),
'requires_review': plan['requires_review'],
'lines': [{'ingredient_id': line['ingredient'].pk, 'name': line['name'],
'quantity': str(line['quantity']), 'unit': line['unit'],
'stock_used': str(line['stock_used']), 'listed': str(line['list_used']),
'missing': str(line['missing']), 'uncertain': line['uncertain'],
'reason': line['reason']} for line in plan['lines']]}
@api_view({'GET': 'inventory:read', 'POST': 'inventory:write'}, ('GET', 'POST'))
def recipe_import(request, identifier):
recipe = _recipe(request.api_user, identifier)
if recipe is None:
return error('not_found', 'Recipe not found.', 404)
data = request.GET if request.method == 'GET' else _json(request)
if request.method == 'GET':
optional = data.get('include_optional', 'false').lower() == 'true'
substitutions = {key[4:]: value for key, value in data.items() if key.startswith('sub_') and value}
else:
optional = data.get('include_optional', False)
substitutions = data.get('substitutions', {})
options = {'servings': data.get('servings'), 'include_optional': optional,
'substitutions': substitutions}
if request.method == 'GET':
return JsonResponse(_plan_data(recipe_preview(request.api_user, recipe, **options)))
if not isinstance(options['include_optional'], bool) or not isinstance(options['substitutions'], dict):
raise GroceryError('Invalid recipe options.')
def action():
return JsonResponse(_plan_data(apply_recipe(request.api_user, recipe,
confirmed_uncertain=data.get('confirm_uncertain') is True, **options)))
return _idempotent(request, data, action)
+67
View File
@@ -0,0 +1,67 @@
# Generated by Django 6.1.2 on 2026-10-21 18:45
import django.core.validators
import django.db.models.deletion
import uuid
from decimal import Decimal
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('food', '0011_log_quantity'),
('recipes', '0006_cooklater'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='GroceryItem',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(max_length=180)),
('quantity', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))])),
('unit', models.CharField(choices=[('pieces', 'pieces'), ('g', 'g'), ('kg', 'kg'), ('ml', 'ml'), ('L', 'L'), ('packs', 'packs'), ('portions', 'portions'), ('tsp', 'tsp'), ('tbsp', 'tbsp')], max_length=10)),
('category', models.CharField(blank=True, max_length=80)),
('notes', models.TextField(blank=True)),
('status', models.CharField(choices=[('needed', 'Needed'), ('purchased', 'Purchased')], default='needed', max_length=12)),
('purchased_at', models.DateTimeField(blank=True, null=True)),
('idempotency_key', models.CharField(blank=True, max_length=100)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='food.foodproduct')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='grocery_items', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('status', 'category', 'name', 'created_at'),
},
),
migrations.CreateModel(
name='GrocerySource',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('requested_quantity', models.DecimalField(decimal_places=3, max_digits=10)),
('requested_unit', models.CharField(max_length=10)),
('selection_key', models.CharField(max_length=120)),
('ingredient', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='recipes.recipeingredient')),
('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sources', to='groceries.groceryitem')),
('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.recipe')),
],
),
migrations.AddConstraint(
model_name='groceryitem',
constraint=models.CheckConstraint(condition=models.Q(('quantity__gt', 0)), name='groceries_positive_quantity'),
),
migrations.AddConstraint(
model_name='groceryitem',
constraint=models.UniqueConstraint(condition=models.Q(('idempotency_key', ''), _negated=True), fields=('user', 'idempotency_key'), name='groceries_unique_idempotency_key'),
),
migrations.AddConstraint(
model_name='grocerysource',
constraint=models.UniqueConstraint(fields=('item', 'recipe', 'ingredient', 'selection_key'), name='groceries_unique_source'),
),
]
@@ -0,0 +1,35 @@
# Generated by Django 6.1.2 on 2026-10-21 18:46
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('food', '0011_log_quantity'),
('groceries', '0001_initial'),
('recipes', '0006_cooklater'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='GroceryRecipeDemand',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('selection_key', models.CharField(blank=True, max_length=120)),
('name', models.CharField(max_length=180)),
('quantity', models.DecimalField(decimal_places=3, max_digits=10)),
('unit', models.CharField(max_length=10)),
('ingredient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.recipeingredient')),
('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='food.foodproduct')),
('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.recipe')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'constraints': [models.UniqueConstraint(fields=('user', 'recipe', 'ingredient', 'selection_key'), name='groceries_unique_recipe_demand')],
},
),
]
@@ -0,0 +1,25 @@
# Generated by Django 6.1.2 on 2026-10-21 18:49
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('food', '0011_log_quantity'),
('groceries', '0002_groceryrecipedemand'),
]
operations = [
migrations.AddField(
model_name='groceryitem',
name='inventory_transfer',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='grocery_origin', to='food.kitcheninventoryitem'),
),
migrations.AddField(
model_name='groceryitem',
name='inventory_transferred_at',
field=models.DateTimeField(blank=True, null=True),
),
]
+79
View File
@@ -0,0 +1,79 @@
import uuid
from decimal import Decimal
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from django.db import models
from django.db.models import Q
class GroceryItem(models.Model):
class Status(models.TextChoices):
NEEDED = 'needed', 'Needed'
PURCHASED = 'purchased', 'Purchased'
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='grocery_items')
name = models.CharField(max_length=180)
quantity = models.DecimalField(max_digits=10, decimal_places=3,
validators=[MinValueValidator(Decimal('0.001'))])
unit = models.CharField(max_length=10, choices=[('pieces', 'pieces'), ('g', 'g'), ('kg', 'kg'),
('ml', 'ml'), ('L', 'L'), ('packs', 'packs'),
('portions', 'portions'), ('tsp', 'tsp'), ('tbsp', 'tbsp')])
category = models.CharField(max_length=80, blank=True)
product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL, null=True, blank=True)
notes = models.TextField(blank=True)
status = models.CharField(max_length=12, choices=Status.choices, default=Status.NEEDED)
purchased_at = models.DateTimeField(null=True, blank=True)
inventory_transfer = models.OneToOneField('food.KitchenInventoryItem', on_delete=models.SET_NULL,
null=True, blank=True, related_name='grocery_origin')
inventory_transferred_at = models.DateTimeField(null=True, blank=True)
idempotency_key = models.CharField(max_length=100, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('status', 'category', 'name', 'created_at')
constraints = [
models.CheckConstraint(condition=Q(quantity__gt=0), name='groceries_positive_quantity'),
models.UniqueConstraint(fields=('user', 'idempotency_key'), condition=~Q(idempotency_key=''),
name='groceries_unique_idempotency_key'),
]
def clean(self):
if self.product_id and self.user_id and self.product.owner_id != self.user_id:
raise ValidationError({'product': 'Choose one of your own food products.'})
class GrocerySource(models.Model):
item = models.ForeignKey(GroceryItem, on_delete=models.CASCADE, related_name='sources')
recipe = models.ForeignKey('recipes.Recipe', on_delete=models.CASCADE)
ingredient = models.ForeignKey('recipes.RecipeIngredient', on_delete=models.SET_NULL, null=True, blank=True)
requested_quantity = models.DecimalField(max_digits=10, decimal_places=3)
requested_unit = models.CharField(max_length=10)
selection_key = models.CharField(max_length=120)
class Meta:
constraints = [models.UniqueConstraint(fields=('item', 'recipe', 'ingredient', 'selection_key'),
name='groceries_unique_source')]
def clean(self):
if self.item_id and self.recipe_id and self.item.user_id != self.recipe.owner_id:
raise ValidationError('Recipe and grocery item must have the same owner.')
class GroceryRecipeDemand(models.Model):
"""Remember recipe demand even when inventory currently covers it."""
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
recipe = models.ForeignKey('recipes.Recipe', on_delete=models.CASCADE)
ingredient = models.ForeignKey('recipes.RecipeIngredient', on_delete=models.CASCADE)
selection_key = models.CharField(max_length=120, blank=True)
name = models.CharField(max_length=180)
product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL, null=True, blank=True)
quantity = models.DecimalField(max_digits=10, decimal_places=3)
unit = models.CharField(max_length=10)
class Meta:
constraints = [models.UniqueConstraint(fields=('user', 'recipe', 'ingredient', 'selection_key'),
name='groceries_unique_recipe_demand')]
+268
View File
@@ -0,0 +1,268 @@
"""Owner-scoped grocery mutations and conservative recipe import."""
from decimal import Decimal, InvalidOperation
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from food.models import FoodProduct, InventoryLocation, KitchenInventoryItem
from recipes.models import Recipe
from recipes.services.analysis import AnalysisError, analyze, physical_amount
from .models import GroceryItem, GroceryRecipeDemand, GrocerySource
UNIT_FACTORS = {'g': ('mass', Decimal(1)), 'kg': ('mass', Decimal(1000)),
'ml': ('volume', Decimal(1)), 'L': ('volume', Decimal(1000)),
'pieces': ('pieces', Decimal(1)), 'packs': ('packs', Decimal(1)),
'portions': ('portions', Decimal(1))}
class GroceryError(ValueError):
pass
def amount(value):
try:
number = Decimal(str(value))
if not number.is_finite() or number <= 0 or number > Decimal('9999999.999') or number != number.quantize(Decimal('.001')):
raise GroceryError('Enter a positive quantity with at most three decimal places.')
return number
except (InvalidOperation, TypeError, ValueError):
raise GroceryError('Enter a valid positive quantity.') from None
def product_for(user, identifier):
if not identifier:
return None
return FoodProduct.objects.filter(owner=user, api_id=identifier).first() or _raise('Product not found.')
def _raise(message):
raise GroceryError(message)
@transaction.atomic
def add(user, *, name, quantity, unit, category='', product=None, notes='', idempotency_key=''):
name = str(name).strip()
if not name or len(name) > 180:
raise GroceryError('Enter a name of at most 180 characters.')
if unit not in dict(GroceryItem._meta.get_field('unit').choices):
raise GroceryError('Choose a supported unit.')
if product and product.owner_id != user.pk:
raise GroceryError('Product not found.')
if len(category) > 80 or len(idempotency_key) > 100:
raise GroceryError('Category or idempotency key is too long.')
quantity = amount(quantity)
if idempotency_key:
existing = GroceryItem.objects.filter(user=user, idempotency_key=idempotency_key).first()
if existing:
if (existing.name, existing.quantity, existing.unit, existing.category, existing.product_id, existing.notes) != (name, quantity, unit, category, product.pk if product else None, notes):
raise GroceryError('Idempotency key was used with different item details.')
return existing
if not idempotency_key and unit in UNIT_FACTORS:
kind, factor = UNIT_FACTORS[unit]
candidates = GroceryItem.objects.select_for_update().filter(user=user,
status=GroceryItem.Status.NEEDED, category=category)
for existing in candidates:
if ((product and existing.product_id != product.pk) or
(not product and (existing.product_id or existing.name.casefold() != name.casefold())) or
existing.unit not in UNIT_FACTORS or UNIT_FACTORS[existing.unit][0] != kind):
continue
converted = quantity * factor / UNIT_FACTORS[existing.unit][1]
if converted != converted.quantize(Decimal('.001')):
continue
existing.quantity += converted
if notes and notes not in existing.notes:
existing.notes = '\n'.join(filter(None, (existing.notes, notes)))
existing.full_clean()
existing.save()
return existing
item = GroceryItem(user=user, name=name, quantity=quantity, unit=unit,
category=category, product=product, notes=notes,
idempotency_key=idempotency_key)
item.full_clean()
item.save()
return item
def edit(user, identifier, changes):
with transaction.atomic():
item = GroceryItem.objects.select_for_update().filter(user=user, pk=identifier).first()
if item is None:
raise GroceryError('Grocery item not found.')
allowed = {'name', 'quantity', 'unit', 'category', 'notes', 'status', 'product_id'}
if set(changes) - allowed:
raise GroceryError('Unsupported grocery field.')
for key, value in changes.items():
if key == 'quantity':
value = amount(value)
elif key == 'product_id':
item.product = product_for(user, value)
continue
elif key == 'status':
if value not in GroceryItem.Status.values:
raise GroceryError('Invalid purchase status.')
item.purchased_at = timezone.now() if value == GroceryItem.Status.PURCHASED else None
elif key == 'name':
value = str(value).strip()
setattr(item, key, value)
item.full_clean()
item.save()
return item
def search(user, *, query='', category='', product=None, status='needed'):
items = GroceryItem.objects.filter(user=user).select_related('product').prefetch_related('sources__recipe')
if query:
items = items.filter(Q(name__icontains=query) | Q(notes__icontains=query))
if category:
items = items.filter(category=category)
if product:
items = items.filter(product=product)
if status != 'all':
if status not in GroceryItem.Status.values:
raise GroceryError('Invalid purchase status.')
items = items.filter(status=status)
return items
@transaction.atomic
def add_purchased_to_inventory(user, identifier, *, product, location):
"""Explicitly convert one purchased grocery row into owned kitchen stock."""
item = GroceryItem.objects.select_for_update().filter(user=user, pk=identifier,
status=GroceryItem.Status.PURCHASED).first()
if item is None:
raise GroceryError('Purchased grocery item not found.')
if item.inventory_transferred_at:
raise GroceryError('This grocery item was already added to inventory.')
if product.owner_id != user.pk:
raise GroceryError('Product not found.')
location_name = ' '.join(location.split())
if not location_name or len(location_name) > 100:
raise GroceryError('Enter a kitchen location.')
place, _ = InventoryLocation.objects.get_or_create(user=user, name__iexact=location_name,
defaults={'name': location_name})
if item.unit in ('pieces', 'packs'):
if item.quantity != item.quantity.to_integral_value():
raise GroceryError('Count units must be whole numbers.')
if item.quantity > 1000:
raise GroceryError('Transfer at most 1,000 count units at a time.')
stock = KitchenInventoryItem(user=user, product=product, location=place,
quantity=1 if item.unit == 'pieces' else int(item.quantity))
if item.unit == 'pieces':
stock.original_amount = Decimal(1)
stock.remaining_amount = Decimal(1)
stock.inventory_unit = 'pieces'
elif item.unit in ('g', 'kg', 'ml', 'L'):
factor = Decimal(1000) if item.unit in ('kg', 'L') else Decimal(1)
stock = KitchenInventoryItem(user=user, product=product, location=place, quantity=1,
original_amount=item.quantity * factor, remaining_amount=item.quantity * factor,
inventory_unit='g' if item.unit in ('g', 'kg') else 'ml')
else:
raise GroceryError('Set a weight, volume, or whole count before adding to inventory.')
stock.full_clean()
stock.save()
if item.unit == 'packs':
from food.services.inventory_consumption import materialize_packages
materialize_packages(stock)
if item.unit == 'pieces':
for _ in range(int(item.quantity) - 1):
KitchenInventoryItem.objects.create(user=user, product=product, location=place,
quantity=1, original_amount=Decimal(1), remaining_amount=Decimal(1),
inventory_unit='pieces')
# Keep the purchased grocery row for history; prevent duplicate transfer with a durable link.
item.inventory_transfer = stock
item.inventory_transferred_at = timezone.now()
item.save(update_fields=['inventory_transfer', 'inventory_transferred_at', 'updated_at'])
return stock
def _compatible(item, name, product, unit):
if product:
if item.product_id != product.pk:
return False
elif item.product_id or item.name.casefold() != name.casefold():
return False
return item.unit == unit
def recipe_preview(user, recipe, servings=None, *, include_optional=False, substitutions=None):
if recipe.owner_id != user.pk:
raise GroceryError('Recipe not found.')
try:
result = analyze(recipe, user, servings, include_optional=include_optional,
substitutions=substitutions or {})
except AnalysisError as exc:
raise GroceryError(str(exc)) from exc
proposed = []
existing = list(search(user))
demands = list(GroceryRecipeDemand.objects.filter(user=user))
for line in result['lines']:
if line['status'] == 'optional':
continue
product = line['product']
raw_quantity, raw_unit = line['quantity'], line['unit']
chosen = next((s for s in line['substitutions'] if str(s.pk) == line['selected_substitution']), None) or line['ingredient']
normalized, unit = physical_amount(raw_quantity, raw_unit, chosen.amount_per_unit,
chosen.amount_per_unit_unit)
if normalized is None:
normalized, unit = raw_quantity, raw_unit
group = next((g for g in result['groups'] if product and g['product'].pk == product.pk and g['unit'] == unit), None)
stock = group['plan']['total'] if group and group['plan'] else None
# Allocate known stock and existing list coverage across lines once, including repeat ingredients.
related = [item for item in existing if _compatible(item, line['name'], product, unit)]
matching_demands = [d for d in demands if d.unit == unit and
((product and d.product_id == product.pk) or
(not product and not d.product_id and d.name.casefold() == line['name'].casefold()))]
prior = sum((d.quantity for d in matching_demands), Decimal(0))
same_recipe = sum((d.quantity for d in matching_demands if d.recipe_id == recipe.pk and
d.ingredient_id == line['ingredient'].pk), Decimal(0))
additional = max(Decimal(0), normalized - same_recipe)
previous = [p for p in proposed if p['product_id'] == (product.pk if product else None) and
p['unit'] == unit]
used_stock = sum((p['stock_used'] for p in previous), Decimal(0))
stock_used = min(additional, max(Decimal(0), stock - prior - used_stock)) if stock is not None else Decimal(0)
listed = sum((item.quantity for item in related), Decimal(0))
prior_unmet = max(Decimal(0), prior - (stock or Decimal(0)))
used_list = sum((p['list_used'] for p in previous if p['name'].casefold() == line['name'].casefold()), Decimal(0))
list_used = min(additional - stock_used, max(Decimal(0), listed - prior_unmet - used_list))
missing = max(Decimal(0), additional - stock_used - list_used)
uncertain = stock is None or not product
proposed.append({'ingredient': line['ingredient'], 'name': line['name'], 'quantity': normalized,
'unit': unit, 'product': product, 'product_id': product.pk if product else None,
'selected_substitution': line['selected_substitution'],
'stock_used': stock_used, 'list_used': list_used, 'missing': missing,
'uncertain': uncertain, 'reason': line['reason'] or ('Stock quantity or product match is unknown.' if uncertain else ''),
'source': line['source']})
return {'recipe': recipe, 'servings': result['servings'], 'lines': proposed,
'substitutions': result['selected_substitutions'], 'include_optional': include_optional,
'requires_review': any(line['uncertain'] for line in proposed)}
@transaction.atomic
def apply_recipe(user, recipe, servings=None, *, include_optional=False, substitutions=None,
confirmed_uncertain=False):
# Lock the user's rows before recalculating coverage to avoid concurrent duplicate additions.
list(GroceryItem.objects.select_for_update().filter(user=user))
plan = recipe_preview(user, recipe, servings, include_optional=include_optional,
substitutions=substitutions)
if plan['requires_review'] and not confirmed_uncertain:
raise GroceryError('Review uncertain ingredients before adding them.')
for line in plan['lines']:
if line['missing'] > 0:
item = next((item for item in search(user) if _compatible(item, line['name'], line['product'], line['unit'])
and item.category == recipe.category), None)
if item:
item.quantity += line['missing']
item.full_clean()
item.save()
else:
item = add(user, name=line['name'], quantity=line['missing'], unit=line['unit'],
category=recipe.category, product=line['product'])
GrocerySource.objects.update_or_create(item=item, recipe=recipe, ingredient=line['ingredient'],
selection_key=str(plan['substitutions'].get(str(line['ingredient'].pk), '')),
defaults={'requested_quantity': line['quantity'], 'requested_unit': line['unit']})
GroceryRecipeDemand.objects.update_or_create(user=user, recipe=recipe,
ingredient=line['ingredient'], selection_key=str(plan['substitutions'].get(str(line['ingredient'].pk), '')),
defaults={'name': line['name'], 'product': line['product'], 'quantity': line['quantity'],
'unit': line['unit']})
return plan
@@ -0,0 +1 @@
.grocery-page{max-width:1050px;margin:0 auto;padding:clamp(1rem,3vw,2.5rem);color:var(--text,#21372c)}.grocery-page h1{font-size:clamp(2rem,4vw,3rem);margin:.2rem 0}.grocery-kicker{text-transform:uppercase;letter-spacing:.12em;font-weight:700}.grocery-panel{background:var(--surface,#fff);border:1px solid #d3ddd5;border-radius:1rem;padding:clamp(1rem,2vw,1.5rem);margin:1.25rem 0;box-shadow:0 6px 24px #172a2010}.grocery-panel h2{margin:0 0 1rem}.grocery-add,.grocery-filter,.grocery-edit{display:flex;flex-wrap:wrap;align-items:end;gap:.75rem}.grocery-add label,.grocery-filter label,.grocery-edit label{display:grid;gap:.3rem;min-width:120px;flex:1}.grocery-add label:first-child{flex:2;min-width:200px}.grocery-page input,.grocery-page select,.grocery-page textarea{box-sizing:border-box;width:100%;padding:.65rem;border:1px solid #a7b7a9;border-radius:.5rem;background:var(--surface,#fff);color:inherit;font:inherit}.grocery-page button{padding:.65rem 1rem;border:0;border-radius:.5rem;background:#315d4d;color:white;font:inherit;cursor:pointer}.grocery-page button:focus-visible,.grocery-page a:focus-visible,.grocery-page input:focus-visible,.grocery-page select:focus-visible,.grocery-page summary:focus-visible{outline:3px solid #bd7319;outline-offset:2px}.grocery-panel-head{display:flex;justify-content:space-between;align-items:center;gap:1rem}.grocery-page .grocery-text-button{background:transparent;color:#315d4d;text-decoration:underline;padding:.4rem}.grocery-group h3{border-bottom:1px solid #d3ddd5;padding-bottom:.4rem}.grocery-group ul,.grocery-preview-list{list-style:none;padding:0}.grocery-item{display:flex;align-items:start;gap:.8rem;border-bottom:1px solid #e2e8e2;padding:.8rem 0}.grocery-item-body{flex:1;min-width:0}.grocery-item-body strong,.grocery-item-body span,.grocery-item-body small{display:block}.grocery-item-body small{color:#52655b}.grocery-item-body details{margin-top:.4rem}.grocery-check{min-width:2.7rem}.grocery-uncertain{display:block;color:#8a4400;font-weight:600}.grocery-confirm{display:flex;gap:.5rem;align-items:center;margin:1rem 0}.grocery-confirm input{width:auto}.grocery-preview-list li{padding:.8rem 0;border-bottom:1px solid #d3ddd5}@media(max-width:600px){.grocery-page{padding:1rem}.grocery-add,.grocery-filter,.grocery-edit{display:grid;grid-template-columns:1fr 1fr}.grocery-add label:first-child,.grocery-add button,.grocery-edit label:first-child,.grocery-edit button{grid-column:1/-1}.grocery-item{gap:.4rem}.grocery-page .grocery-text-button{font-size:.9rem}}
@@ -0,0 +1,8 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Groceries · Tasknest{% endblock %}
{% block content %}
<link rel="stylesheet" href="{% static 'groceries/groceries.css' %}?v=2">
<div class="grocery-page"><header><p class="grocery-kicker">Food</p><h1>Grocery list</h1><p>Plan what to buy. Marking an item purchased does not add it to Kitchen Inventory.</p></header>
<section class="grocery-panel" aria-labelledby="quick-add"><h2 id="quick-add">Quick add</h2><form class="grocery-add" method="post" action="{% url 'groceries:add' %}">{% csrf_token %}<label>Name<input name="name" maxlength="180" required autocomplete="off"></label><label>Quantity<input name="quantity" type="number" min="0.001" step="0.001" value="1" required></label><label>Unit<select name="unit"><option value="pieces">pieces</option><option value="g">g</option><option value="kg">kg</option><option value="ml">ml</option><option value="L">L</option><option value="packs">packs</option><option value="portions">portions</option><option value="tsp">tsp</option><option value="tbsp">tbsp</option></select></label><label>Category<input name="category" maxlength="80"></label><button type="submit">Add item</button></form></section>
<section class="grocery-panel" aria-labelledby="grocery-items"><div class="grocery-panel-head"><h2 id="grocery-items">Items</h2><form method="post" action="{% url 'groceries:clear-purchased' %}">{% csrf_token %}<button type="submit" class="grocery-text-button">Clear purchased</button></form></div><form method="get" class="grocery-filter" hx-get="{% url 'groceries:index' %}" hx-target="#grocery-list" hx-push-url="true"><label>Search<input type="search" name="q" value="{{ query }}"></label><label>Status<select name="status"><option value="needed"{% if selected_status == 'needed' %} selected{% endif %}>Needed</option><option value="purchased"{% if selected_status == 'purchased' %} selected{% endif %}>Purchased</option><option value="all"{% if selected_status == 'all' %} selected{% endif %}>All</option></select></label><button type="submit">Filter</button></form><div id="grocery-list" aria-live="polite">{% include 'groceries/partials/list.html' %}</div></section></div>
{% endblock %}
@@ -0,0 +1,3 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Add to Kitchen Inventory · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'groceries/groceries.css' %}?v=2"><div class="grocery-page"><a href="{% url 'groceries:index' %}">← Grocery list</a><h1>Add purchased item to inventory</h1><section class="grocery-panel"><p><strong>{{ item.name }}</strong> · {{ item.quantity|floatformat:-3 }} {{ item.unit }}</p>{% if item.inventory_transferred_at %}<p>This item was already added to Kitchen Inventory.</p>{% else %}<p>Confirm the product and location. This creates stock only when you submit this form.</p><form method="post" class="grocery-add">{% csrf_token %}<label>Food product<select name="product_id" required><option value="">Choose a product</option>{% for product in products %}<option value="{{ product.api_id }}"{% if product.pk == item.product_id %} selected{% endif %}>{{ product.product_name }}{% if product.brand %} · {{ product.brand }}{% endif %}</option>{% endfor %}</select></label><label>Kitchen location<input name="location" value="Pantry" maxlength="100" required></label><button type="submit">Confirm and add stock</button></form>{% endif %}</section></div>{% endblock %}
@@ -0,0 +1,2 @@
{% regroup items by category as categories %}
{% for group in categories %}<section class="grocery-group"><h3>{{ group.grouper|default:'Other' }}</h3><ul>{% for item in group.list %}<li class="grocery-item"><form method="post" action="{% url 'groceries:update' item.pk %}" class="grocery-item-main">{% csrf_token %}<input type="hidden" name="status" value="{% if item.status == 'needed' %}purchased{% else %}needed{% endif %}"><button type="submit" class="grocery-check" aria-label="Mark {{ item.name }} {% if item.status == 'needed' %}purchased{% else %}needed{% endif %}" aria-pressed="{% if item.status == 'purchased' %}true{% else %}false{% endif %}">{% if item.status == 'purchased' %}✓{% else %}○{% endif %}</button></form><div class="grocery-item-body"><strong>{{ item.name }}</strong><span>{{ item.quantity|floatformat:-3 }} {{ item.unit }}</span>{% if item.notes %}<small>{{ item.notes }}</small>{% endif %}{% for source in item.sources.all %}<small>From {{ source.recipe.title }}</small>{% endfor %}{% if item.status == "purchased" %}<a href="{% url 'groceries:inventory-transfer' item.pk %}">{% if item.inventory_transferred_at %}Added to inventory{% else %}Add to inventory{% endif %}</a>{% endif %}<details><summary>Edit</summary><form method="post" action="{% url 'groceries:update' item.pk %}" class="grocery-edit">{% csrf_token %}<label>Name<input name="name" value="{{ item.name }}" required></label><label>Quantity<input name="quantity" type="number" min="0.001" step="0.001" value="{{ item.quantity }}" required></label><label>Unit<select name="unit"><option value="{{ item.unit }}" selected>{{ item.unit }}</option><option value="pieces">pieces</option><option value="g">g</option><option value="kg">kg</option><option value="ml">ml</option><option value="L">L</option><option value="packs">packs</option><option value="portions">portions</option><option value="tsp">tsp</option><option value="tbsp">tbsp</option></select></label><label>Category<input name="category" value="{{ item.category }}"></label><label>Notes<textarea name="notes">{{ item.notes }}</textarea></label><button type="submit">Save</button></form></details></div><form method="post" action="{% url 'groceries:delete' item.pk %}">{% csrf_token %}<button type="submit" class="grocery-text-button" aria-label="Delete {{ item.name }}">Delete</button></form></li>{% endfor %}</ul></section>{% empty %}<p class="grocery-empty">No grocery items here yet.</p>{% endfor %}
@@ -0,0 +1,3 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Review groceries · {{ recipe.title }}{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'groceries/groceries.css' %}?v=2"><div class="grocery-page"><a href="{% url 'recipes:detail' recipe.api_id %}">← Back to recipe</a><h1>Review groceries for {{ recipe.title }}</h1><p>Only known, compatible stock is subtracted. Items already on your grocery list are counted.</p>{% if error %}<p role="alert">{{ error }}</p>{% endif %}{% if plan %}<form method="get" class="grocery-panel grocery-filter"><label>Servings<input type="number" name="servings" min="0.01" max="99999.99" step="0.01" value="{{ plan.servings }}"></label><label><input type="checkbox" name="optional" value="1"{% if plan.include_optional %} checked{% endif %}> Include optional ingredients</label>{% for line in plan.lines %}{% if line.ingredient.substitutions.exists %}<label>{{ line.name }} alternative<select name="sub_{{ line.ingredient.pk }}"><option value="">Original</option>{% for substitute in line.ingredient.substitutions.all %}<option value="{{ substitute.pk }}"{% if line.selected_substitution == substitute.pk|stringformat:"s" %} selected{% endif %}>{{ substitute.name }}</option>{% endfor %}</select></label>{% endif %}{% endfor %}<button>Update preview</button></form><section class="grocery-panel"><h2>Missing ingredients</h2><ul class="grocery-preview-list">{% for line in plan.lines %}<li><strong>{{ line.name }}</strong> · {{ line.quantity|floatformat:-3 }} {{ line.unit }} needed · {{ line.stock_used|floatformat:-3 }} in stock · {{ line.list_used|floatformat:-3 }} listed · <b>{{ line.missing|floatformat:-3 }} to add</b>{% if line.uncertain %}<span class="grocery-uncertain">Review: {{ line.reason }}</span>{% endif %}{% if line.source %}<small>From {{ line.source }}</small>{% endif %}</li>{% empty %}<li>No ingredients to add.</li>{% endfor %}</ul><form method="post" action="{% url 'groceries:recipe-add' recipe.api_id %}">{% csrf_token %}<input type="hidden" name="servings" value="{{ plan.servings }}">{% if plan.include_optional %}<input type="hidden" name="optional" value="1">{% endif %}{% for key,value in plan.substitutions.items %}<input type="hidden" name="sub_{{ key }}" value="{{ value }}">{% endfor %}{% if plan.requires_review %}<label class="grocery-confirm"><input type="checkbox" name="confirm_uncertain" value="1" required> I reviewed the uncertain stock or ingredient matches.</label>{% endif %}<button type="submit">Add missing ingredients</button></form></section>{% endif %}</div>{% endblock %}
+100
View File
@@ -0,0 +1,100 @@
from decimal import Decimal
import json
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.test import override_settings
from django.conf import settings
from food.models import FoodProduct
from food.api import create_token
from recipes.models import Recipe, RecipeIngredient
from .models import GroceryItem
from .services import GroceryError, add, add_purchased_to_inventory, apply_recipe, edit, recipe_preview, search
class GroceryTests(TestCase):
def setUp(self):
User = get_user_model()
self.user = User.objects.create_user(username='grocery-user', password='test')
self.other = User.objects.create_user(username='grocery-other', password='test')
def test_manual_items_are_scoped_and_purchase_does_not_create_stock(self):
item = add(self.user, name='Milk', quantity='2', unit='L')
self.assertEqual(search(self.user).count(), 1)
self.assertEqual(search(self.other).count(), 0)
with self.assertRaises(GroceryError):
edit(self.other, item.pk, {'status': 'purchased'})
edit(self.user, item.pk, {'status': 'purchased'})
self.assertEqual(search(self.user).count(), 0)
self.assertEqual(search(self.user, status='purchased').count(), 1)
self.assertEqual(self.user.kitchen_inventory.count(), 0)
def test_compatible_manual_units_merge_and_keep_notes(self):
item = add(self.user, name='Flour', quantity='1', unit='kg', notes='Wholegrain')
merged = add(self.user, name='flour', quantity='500', unit='g', notes='For bread')
self.assertEqual(item.pk, merged.pk)
self.assertEqual(merged.quantity, Decimal('1.5'))
self.assertIn('Wholegrain', merged.notes)
self.assertIn('For bread', merged.notes)
add(self.user, name='Flour', quantity='1', unit='pieces')
self.assertEqual(GroceryItem.objects.filter(user=self.user).count(), 2)
def test_recipe_import_is_idempotent_and_does_not_reuse_stock(self):
product = FoodProduct.objects.create(owner=self.user, product_name='Flour')
first = Recipe.objects.create(owner=self.user, title='Bread', default_servings=2)
second = Recipe.objects.create(owner=self.user, title='Pancakes', default_servings=2)
RecipeIngredient.objects.create(recipe=first, name='Flour', quantity=200, unit='g', inventory_product=product)
RecipeIngredient.objects.create(recipe=second, name='Flour', quantity=100, unit='g', inventory_product=product)
self.assertEqual(recipe_preview(self.user, first)['lines'][0]['missing'], Decimal('200'))
apply_recipe(self.user, first)
apply_recipe(self.user, first)
self.assertEqual(GroceryItem.objects.get(user=self.user).quantity, Decimal('200'))
apply_recipe(self.user, second)
self.assertEqual(GroceryItem.objects.get(user=self.user).quantity, Decimal('300'))
def test_unknown_match_requires_review(self):
recipe = Recipe.objects.create(owner=self.user, title='Snack')
RecipeIngredient.objects.create(recipe=recipe, name='Rare ingredient', quantity=1, unit='pieces')
self.assertTrue(recipe_preview(self.user, recipe)['requires_review'])
with self.assertRaises(GroceryError):
apply_recipe(self.user, recipe)
apply_recipe(self.user, recipe, confirmed_uncertain=True)
self.assertEqual(GroceryItem.objects.filter(user=self.user).count(), 1)
@override_settings(MIDDLEWARE=[item for item in settings.MIDDLEWARE if not item.startswith('whitenoise.')],
SECURE_SSL_REDIRECT=False)
def test_page_and_recipe_preview_render(self):
self.client.force_login(self.user)
self.assertContains(self.client.get('/groceries/'), 'Quick add')
recipe = Recipe.objects.create(owner=self.user, title='Soup')
RecipeIngredient.objects.create(recipe=recipe, name='Water', quantity=200, unit='ml')
self.assertContains(self.client.get(f'/groceries/recipe/{recipe.api_id}/preview/'), 'Review groceries')
def test_inventory_transfer_requires_purchase_and_is_single_use(self):
item = add(self.user, name='Rice', quantity='500', unit='g')
product = FoodProduct.objects.create(owner=self.user, product_name='Rice')
with self.assertRaises(GroceryError):
add_purchased_to_inventory(self.user, item.pk, product=product, location='Pantry')
edit(self.user, item.pk, {'status': 'purchased'})
stock = add_purchased_to_inventory(self.user, item.pk, product=product, location='Pantry')
self.assertEqual(stock.remaining_amount, Decimal('500'))
with self.assertRaises(GroceryError):
add_purchased_to_inventory(self.user, item.pk, product=product, location='Pantry')
@override_settings(MIDDLEWARE=[item for item in settings.MIDDLEWARE if not item.startswith('whitenoise.')],
SECURE_SSL_REDIRECT=False)
def test_api_crud_is_owner_scoped(self):
_, token = create_token(self.user, 'groceries', ['inventory:read', 'inventory:write'])
_, other_token = create_token(self.other, 'groceries', ['inventory:read', 'inventory:write'])
headers = {'HTTP_AUTHORIZATION': f'Bearer {token}'}
response = self.client.post('/api/v1/groceries/', data=json.dumps({'name': 'Apples',
'quantity': '2', 'unit': 'pieces'}), content_type='application/json', **headers)
self.assertEqual(response.status_code, 201)
identifier = response.json()['id']
self.assertEqual(self.client.get('/api/v1/groceries/', **headers).json()['count'], 1)
self.assertEqual(self.client.patch(f'/api/v1/groceries/{identifier}/',
data=json.dumps({'status': 'purchased'}), content_type='application/json', **headers).status_code, 200)
other_headers = {'HTTP_AUTHORIZATION': f'Bearer {other_token}'}
self.assertEqual(self.client.delete(f'/api/v1/groceries/{identifier}/', **other_headers).status_code, 404)
self.assertEqual(self.client.get('/api/v1/groceries/', **other_headers).json()['count'], 0)
+14
View File
@@ -0,0 +1,14 @@
from django.urls import path
from . import views
app_name = 'groceries'
urlpatterns = [
path('', views.index, name='index'),
path('add/', views.create, name='add'),
path('clear-purchased/', views.clear_purchased, name='clear-purchased'),
path('<uuid:identifier>/update/', views.update, name='update'),
path('<uuid:identifier>/delete/', views.delete, name='delete'),
path('<uuid:identifier>/inventory/', views.inventory_transfer, name='inventory-transfer'),
path('recipe/<uuid:identifier>/preview/', views.preview_recipe, name='recipe-preview'),
path('recipe/<uuid:identifier>/add/', views.add_recipe, name='recipe-add'),
]
+119
View File
@@ -0,0 +1,119 @@
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.http import require_POST
from recipes.models import Recipe
from .models import GroceryItem
from food.models import FoodProduct
from .services import (GroceryError, add, add_purchased_to_inventory, apply_recipe,
edit, recipe_preview, search)
def _page(request, status=200):
selected = request.GET.get('status', 'needed')
try:
items = list(search(request.user, query=request.GET.get('q', ''), status=selected).order_by('category', 'status', 'name'))
except GroceryError:
selected, items = 'needed', list(search(request.user))
context = {'items': items, 'selected_status': selected, 'query': request.GET.get('q', '')}
template = 'groceries/partials/list.html' if request.headers.get('HX-Request') == 'true' else 'groceries/index.html'
return render(request, template, context, status=status)
@login_required
def index(request):
return _page(request)
@login_required
@require_POST
def create(request):
try:
add(request.user, name=request.POST.get('name', ''), quantity=request.POST.get('quantity', ''),
unit=request.POST.get('unit', 'pieces'), category=request.POST.get('category', '').strip(),
notes=request.POST.get('notes', '').strip())
messages.success(request, 'Added to grocery list.')
except GroceryError as exc:
messages.error(request, str(exc))
return redirect('groceries:index')
@login_required
@require_POST
def update(request, identifier):
try:
changes = {field: request.POST[field] for field in ('name', 'quantity', 'unit', 'category', 'notes', 'status')
if field in request.POST}
edit(request.user, identifier, changes)
except GroceryError as exc:
messages.error(request, str(exc))
return redirect('groceries:index')
@login_required
@require_POST
def delete(request, identifier):
item = get_object_or_404(GroceryItem, user=request.user, pk=identifier)
item.delete()
messages.success(request, 'Grocery item removed.')
return redirect('groceries:index')
@login_required
@require_POST
def clear_purchased(request):
count, _ = GroceryItem.objects.filter(user=request.user, status=GroceryItem.Status.PURCHASED).delete()
messages.success(request, f'Cleared {count} purchased items.')
return redirect('groceries:index')
@login_required
def inventory_transfer(request, identifier):
item = get_object_or_404(GroceryItem, user=request.user, pk=identifier,
status=GroceryItem.Status.PURCHASED)
if request.method == 'POST':
product = FoodProduct.objects.filter(owner=request.user, api_id=request.POST.get('product_id')).first()
try:
if product is None:
raise GroceryError('Choose one of your own food products.')
add_purchased_to_inventory(request.user, identifier, product=product,
location=request.POST.get('location', ''))
messages.success(request, 'Purchased item added to Kitchen Inventory.')
return redirect('groceries:index')
except GroceryError as exc:
messages.error(request, str(exc))
return render(request, 'groceries/inventory_transfer.html', {
'item': item, 'products': FoodProduct.objects.filter(owner=request.user).order_by('product_name')})
def _recipe_options(data):
return {'include_optional': data.get('optional') == '1',
'substitutions': {key[4:]: value for key, value in data.items() if key.startswith('sub_') and value}}
@login_required
def preview_recipe(request, identifier):
recipe = get_object_or_404(Recipe, owner=request.user, api_id=identifier)
try:
plan = recipe_preview(request.user, recipe, request.GET.get('servings'), **_recipe_options(request.GET))
error = ''
except GroceryError as exc:
plan, error = None, str(exc)
return render(request, 'groceries/recipe_preview.html', {'recipe': recipe, 'plan': plan, 'error': error})
@login_required
@require_POST
def add_recipe(request, identifier):
recipe = get_object_or_404(Recipe, owner=request.user, api_id=identifier)
try:
apply_recipe(request.user, recipe, request.POST.get('servings'),
confirmed_uncertain=request.POST.get('confirm_uncertain') == '1',
**_recipe_options(request.POST))
messages.success(request, 'Missing ingredients added to your grocery list.')
return redirect('groceries:index')
except GroceryError as exc:
messages.error(request, str(exc))
return redirect('groceries:recipe-preview', identifier=identifier)
+70
View File
@@ -196,6 +196,25 @@ class RecipeAnalysisInput(BaseModel):
substitutions: dict[str, str] = Field(default_factory=dict) substitutions: dict[str, str] = Field(default_factory=dict)
class GroceryItemInput(BaseModel):
name: str
quantity: Decimal = Field(gt=0)
unit: Literal['pieces', 'g', 'kg', 'ml', 'L', 'packs', 'portions', 'tsp', 'tbsp'] = 'pieces'
category: str = ''
product_id: str | None = None
notes: str = ''
class GroceryItemChanges(BaseModel):
name: str | None = None
quantity: Decimal | None = Field(default=None, gt=0)
unit: Literal['pieces', 'g', 'kg', 'ml', 'L', 'packs', 'portions', 'tsp', 'tbsp'] | None = None
category: str | None = None
product_id: str | None = None
notes: str | None = None
status: Literal['needed', 'purchased'] | None = None
class StressInput(BaseModel): class StressInput(BaseModel):
score: int = Field(ge=0, le=10) score: int = Field(ge=0, le=10)
recorded_at: str | None = None recorded_at: str | None = None
@@ -262,6 +281,12 @@ def _api_error(response: httpx2.Response) -> ToolError:
async def api_request(method: str, path: str, *, payload=None, params=None, files=None, form=None, async def api_request(method: str, path: str, *, payload=None, params=None, files=None, form=None,
idempotency_key=None, token=None, return_validation=False): idempotency_key=None, token=None, return_validation=False):
headers = {'Authorization': f'Bearer {token or _token()}'} headers = {'Authorization': f'Bearer {token or _token()}'}
# Django enforces HTTPS in production. This hop stays on loopback; mark it as
# the trusted internal side of the HTTPS proxy so it is not redirected to a
# TLS endpoint that the development server does not provide.
api_url = urlsplit(API_BASE)
if api_url.scheme == 'http' and api_url.hostname in {'127.0.0.1', 'localhost', '::1'}:
headers['X-Forwarded-Proto'] = 'https'
if idempotency_key: if idempotency_key:
headers['Idempotency-Key'] = idempotency_key headers['Idempotency-Key'] = idempotency_key
try: try:
@@ -270,6 +295,9 @@ async def api_request(method: str, path: str, *, payload=None, params=None, file
json=payload, params=params, files=files, data=form) json=payload, params=params, files=files, data=form)
except (httpx2.RequestError, TimeoutError): except (httpx2.RequestError, TimeoutError):
raise ToolError('TaskNest is unavailable. Retry with the same idempotency key if this was a creation.') from None raise ToolError('TaskNest is unavailable. Retry with the same idempotency key if this was a creation.') from None
if 300 <= response.status_code < 400:
logger.warning('TaskNest API unexpectedly redirected an MCP request: status=%s', response.status_code)
raise ToolError('TaskNest API redirected the request. Check the internal HTTPS proxy configuration.')
if response.status_code >= 400: if response.status_code >= 400:
if return_validation and response.status_code == 400: if return_validation and response.status_code == 400:
return response.json() return response.json()
@@ -619,6 +647,48 @@ def create_server() -> MCPServer:
return await api_request('GET', 'recipes/cook-later/', return await api_request('GET', 'recipes/cook-later/',
params={'search': search, 'limit': limit, 'offset': offset}) params={'search': search, 'limit': limit, 'offset': offset})
@server.tool(structured_output=True, description='List your grocery items by needed, purchased, or all status. Read only.')
async def grocery_list(status: Literal['needed', 'purchased', 'all'] = 'needed', limit: int = 30,
offset: int = 0) -> dict[str, Any]:
return await api_request('GET', 'groceries/', params={'status': status, 'limit': limit, 'offset': offset})
@server.tool(structured_output=True, description='Search your grocery list by text, category, product, and purchase status. Read only.')
async def grocery_search(query: str = '', category: str = '', product_id: str | None = None,
status: Literal['needed', 'purchased', 'all'] = 'all', limit: int = 30,
offset: int = 0) -> dict[str, Any]:
return await api_request('GET', 'groceries/', params={'query': query, 'category': category,
'product_id': product_id or '', 'status': status, 'limit': limit, 'offset': offset})
@server.tool(structured_output=True, description='Add one item to your grocery list. Does not change Kitchen Inventory. Reuse the idempotency key on retries.')
async def grocery_add(item: GroceryItemInput, idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
data = await api_request('POST', 'groceries/', payload=item.model_dump(mode='json', exclude_none=True),
idempotency_key=key)
return {**data, 'idempotency_key': key}
@server.tool(structured_output=True, description='Edit an owned grocery item, including purchase status. Purchasing never adds inventory.')
async def grocery_edit(item_id: str, changes: GroceryItemChanges) -> dict[str, Any]:
return await api_request('PATCH', f'groceries/{item_id}/',
payload=changes.model_dump(mode='json', exclude_unset=True))
@server.tool(structured_output=True, description='Delete one owned grocery item by stable UUID. Requires clear user intent.')
async def grocery_delete(item_id: str) -> dict[str, Any]:
return await api_request('DELETE', f'groceries/{item_id}/')
@server.tool(structured_output=True, description='Preview or confirm missing ingredients for an owned recipe, scaled to servings and selected substitutions. Omit confirm to preview. Set confirm true to add; uncertain matches additionally require confirm_uncertain true after review. Does not change Kitchen Inventory.')
async def grocery_add_recipe(recipe_id: str, options: RecipeAnalysisInput | None = None,
confirm: bool = False, confirm_uncertain: bool = False,
idempotency_key: str | None = None) -> dict[str, Any]:
values = (options or RecipeAnalysisInput()).model_dump(mode='json', exclude_none=True)
if not confirm:
params = {key: value for key, value in values.items() if key != 'substitutions'}
params.update({f'sub_{key}': value for key, value in values.get('substitutions', {}).items()})
return await api_request('GET', f'groceries/recipe/{recipe_id}/', params=params)
key = _key(idempotency_key)
data = await api_request('POST', f'groceries/recipe/{recipe_id}/',
payload={**values, 'confirm_uncertain': confirm_uncertain}, idempotency_key=key)
return {**data, 'idempotency_key': key}
@server.tool(structured_output=True, description='Create an owned recipe. Add measured ingredients with recipe_ingredient_add. Reuse idempotency_key on retries.') @server.tool(structured_output=True, description='Create an owned recipe. Add measured ingredients with recipe_ingredient_add. Reuse idempotency_key on retries.')
async def recipe_create(recipe: RecipeInput, idempotency_key: str | None = None) -> dict[str, Any]: async def recipe_create(recipe: RecipeInput, idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key) key = _key(idempotency_key)
+3 -1
View File
@@ -99,6 +99,7 @@ class McpHttpTests(LiveServerTestCase):
async with Client(streamable_http_client(self.mcp_url, http_client=http)) as client: async with Client(streamable_http_client(self.mcp_url, http_client=http)) as client:
return await operation(client) return await operation(client)
@override_settings(SECURE_SSL_REDIRECT=True)
def test_authentication_and_scope_boundaries(self): def test_authentication_and_scope_boundaries(self):
async def check(): async def check():
async with httpx2.AsyncClient(timeout=10) as http: async with httpx2.AsyncClient(timeout=10) as http:
@@ -293,6 +294,7 @@ class McpHttpTests(LiveServerTestCase):
self.assertEqual((await client.call_tool('stress_search')).structured_content['total'], 1) self.assertEqual((await client.call_tool('stress_search')).structured_content['total'], 1)
asyncio.run(self._client(secret, check)) asyncio.run(self._client(secret, check))
@override_settings(SECURE_SSL_REDIRECT=True)
def test_food_inventory_tools_and_user_isolation(self): def test_food_inventory_tools_and_user_isolation(self):
previous_day = localdate_for_user(self.a) - timedelta(days=1) previous_day = localdate_for_user(self.a) - timedelta(days=1)
FoodLogEntry.objects.create(user=self.a, date=previous_day, meal='breakfast', FoodLogEntry.objects.create(user=self.a, date=previous_day, meal='breakfast',
@@ -304,7 +306,7 @@ class McpHttpTests(LiveServerTestCase):
async def check(client): async def check(client):
names = {tool.name for tool in (await client.list_tools()).tools} names = {tool.name for tool in (await client.list_tools()).tools}
self.assertEqual(len(names), 44) self.assertGreaterEqual(len(names), 44)
self.assertTrue({'food_lookup_product', 'food_create_product', 'food_import_product', self.assertTrue({'food_lookup_product', 'food_create_product', 'food_import_product',
'inventory_import_groceries', 'recipe_cook_later_add', 'inventory_import_groceries', 'recipe_cook_later_add',
'recipe_cook_later_remove', 'recipe_cook_later_list'} <= names) 'recipe_cook_later_remove', 'recipe_cook_later_list'} <= names)
+33 -4
View File
@@ -1,14 +1,43 @@
"""Template context shared by Tasknest pages.""" """Template context shared by Tasknest pages."""
from .models import UserSettings from .models import UserSettings
from django.urls import reverse
def appearance(request): def appearance(request):
"""Expose the signed-in user’s saved colour preference without creating settings.""" """Expose the signed-in user’s saved colour preference without creating settings."""
user = getattr(request, "user", None) user = getattr(request, "user", None)
if user is not None and user.is_authenticated: if user is not None and user.is_authenticated:
saved_appearance = ( profile = UserSettings.objects.filter(user=user).values('appearance', 'is_demo').first()
UserSettings.objects.filter(user=user).values_list("appearance", flat=True).first() return {"user_appearance": profile['appearance'] if profile else UserSettings.Appearance.LIGHT,
"is_demo_account": bool(profile and profile['is_demo'])}
return {"user_appearance": UserSettings.Appearance.LIGHT, "is_demo_account": False}
def navigation(request):
"""A single site navigation tree for desktop and mobile."""
user = getattr(request, 'user', None)
if not user or not user.is_authenticated:
return {'nav_groups': ()}
current = request.path
definitions = (
('tasks', 'My tasks', 'planner:task-list', (('Daily planner', 'planner:daily-planner'),)),
('health', 'Health', 'planner:health', (('Stress', 'stress:journal'), ('Dreams', 'dreams:journal'))),
('food', 'Food', 'food:diary', (('Recipes', 'recipes:list'),
('Kitchen Inventory', 'food:inventory'),
('Groceries', 'groceries:index'))),
) )
return {"user_appearance": saved_appearance or UserSettings.Appearance.LIGHT} groups = []
return {"user_appearance": UserSettings.Appearance.LIGHT} for key, label, route, children in definitions:
url = reverse(route)
items = [{'label': child_label, 'url': reverse(child_route),
'active': current.startswith(reverse(child_route))}
for child_label, child_route in children]
# Food's root URL is a prefix of its children; exact match keeps its parent state clear.
parent_active = current == url or (key == 'food' and
getattr(request.resolver_match, 'namespace', '') == 'food' and
not any(item['active'] for item in items))
groups.append({'key': key, 'label': label, 'url': url, 'items': items,
'parent_active': parent_active,
'active': parent_active or any(item['active'] for item in items)})
return {'nav_groups': groups}
+7
View File
@@ -0,0 +1,7 @@
"""A recoverable page for expired forms and CSRF cookie changes."""
from django.shortcuts import render
def csrf_failure(request, reason=''):
return render(request, 'planner/csrf_failure.html', status=403)
+8
View File
@@ -0,0 +1,8 @@
"""Server-side restrictions for the public demonstration account."""
from .models import UserSettings
def is_demo_user(user):
return bool(getattr(user, 'is_authenticated', False) and
UserSettings.objects.filter(user_id=user.pk, is_demo=True).exists())
+57 -4
View File
@@ -3,11 +3,19 @@ from datetime import datetime, time, timedelta
from decimal import Decimal from decimal import Decimal
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand 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.db import transaction
from django.utils import timezone from django.utils import timezone
from food.models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit 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 ( from planner.models import (
BowelHealthCheckIn, BowelHealthCheckIn,
@@ -95,19 +103,29 @@ class Command(BaseCommand):
def add_arguments(self, parser): def add_arguments(self, parser):
parser.add_argument('--username', default='demo', help='Demo username (default: demo).') parser.add_argument('--username', default='demo', help='Demo username (default: demo).')
parser.add_argument('--password', default='demo', help='Demo password (default: demo).') parser.add_argument('--password', help='Initial or replacement demo password; prefer TASKNEST_DEMO_PASSWORD.')
@transaction.atomic @transaction.atomic
def handle(self, *args, **options): def handle(self, *args, **options):
username = options['username'] username = options['username']
password = options['password'] password = options['password'] or settings.TASKNEST_DEMO_PASSWORD
user_model = get_user_model() user_model = get_user_model()
user, created = user_model.objects.get_or_create(username=username) 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.set_password(password)
user.is_active = True user.is_active = True
user.save() user.save()
profile, _ = UserSettings.objects.get_or_create(user=user) profile, _ = UserSettings.objects.get_or_create(user=user)
profile.is_demo = True
profile.time_zone = DEFAULT_TIME_ZONE profile.time_zone = DEFAULT_TIME_ZONE
profile.appearance = UserSettings.Appearance.LIGHT profile.appearance = UserSettings.Appearance.LIGHT
profile.latitude = '52.367600' profile.latitude = '52.367600'
@@ -115,6 +133,11 @@ class Command(BaseCommand):
profile.onboarding_enabled = False profile.onboarding_enabled = False
profile.onboarding_step = 0 profile.onboarding_step = 0
profile.daily_water_goal_ml = 2000 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.daily_calorie_goal = 2000
profile.carbohydrate_goal_g = Decimal('250.0') profile.carbohydrate_goal_g = Decimal('250.0')
profile.protein_goal_g = Decimal('100.0') profile.protein_goal_g = Decimal('100.0')
@@ -136,13 +159,43 @@ class Command(BaseCommand):
WaterIntakeEntry.objects.filter(user=user).delete() WaterIntakeEntry.objects.filter(user=user).delete()
ToothBrushing.objects.filter(user=user).delete() ToothBrushing.objects.filter(user=user).delete()
BowelHealthCheckIn.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() 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() FoodFavourite.objects.filter(user=user).delete()
FoodPortion.objects.filter(user=user).delete() FoodPortion.objects.filter(user=user).delete()
FoodProduct.objects.filter(owner=user).delete() FoodProduct.objects.filter(owner=user).delete()
now = timezone.now() now = timezone.now()
today = localdate_for_user(user, 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 - timedelta(days=1), morning=True, evening=True)
ToothBrushing.objects.create(user=user, date=today, morning=True, evening=False) ToothBrushing.objects.create(user=user, date=today, morning=True, evening=False)
+72
View File
@@ -0,0 +1,72 @@
import logging
from django.conf import settings
from django.core.cache import cache
from django.http import HttpResponse, HttpResponseForbidden, JsonResponse
from django.utils import timezone
from .demo_policy import is_demo_user
logger = logging.getLogger(__name__)
class DemoAccountPolicyMiddleware:
"""Deny privileged and external actions even if a link is hidden in the UI."""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.path_info == '/o/token/' and request.method == 'POST':
from oauth2_provider.models import get_grant_model, get_refresh_token_model
grant_type = request.POST.get('grant_type')
credential = request.POST.get('refresh_token' if grant_type == 'refresh_token' else 'code')
model = (get_refresh_token_model() if grant_type == 'refresh_token'
else get_grant_model() if grant_type == 'authorization_code' else None)
field = 'token' if grant_type == 'refresh_token' else 'code'
if model and credential and model.objects.filter(
**{field: credential, 'user__planner_settings__is_demo': True}).exists():
logger.warning('Denied demo OAuth token exchange')
return JsonResponse({'error': 'access_denied'}, status=403)
if is_demo_user(request.user):
path = request.path_info
if request.method not in {'GET', 'HEAD', 'OPTIONS'}:
if request.META.get('CONTENT_LENGTH', '').isdigit() and int(request.META['CONTENT_LENGTH']) > 1024 * 1024:
return HttpResponse('Demo requests are limited to 1 MB.', status=413)
limits = (
(f'demo:writes:minute:{request.user.pk}', 60,
getattr(settings, 'DEMO_MUTATIONS_PER_MINUTE', 60)),
(f'demo:writes:day:{request.user.pk}:{timezone.localdate().isoformat()}',
86400, getattr(settings, 'DEMO_MUTATIONS_PER_DAY', 500)),
)
over_limit = False
for key, lifetime, maximum in limits:
cache.add(key, 0, lifetime)
try:
count = cache.incr(key)
except ValueError:
cache.set(key, 1, lifetime)
count = 1
over_limit |= count > maximum
if over_limit:
logger.warning('Demo account write limit reached: user_id=%s', request.user.pk)
response = HttpResponse('Demo request limit reached. Try again in a minute.', status=429)
response['Retry-After'] = '60'
return response
forbidden = (path.startswith(('/o/', '/admin/', '/food/settings/tokens/')) or
path == '/settings/notifications/ntfy/test/' or
(request.method == 'POST' and path in {
'/food/search/openfoodfacts/', '/food/import/openfoodfacts/',
'/food/inventory/search/openfoodfacts/', '/food/inventory/lookup/',
}) or
(request.method == 'POST' and path.startswith('/recipes/') and
not (path == '/recipes/match/reset/' or
(path.startswith('/recipes/match/') and path.endswith('/select/')) or
path.startswith('/recipes/cook-later/'))) or
(path == '/settings/' and request.method == 'POST' and
request.POST.get('section') in {'ntfy', 'location'}))
if forbidden:
logger.warning('Denied demo account action: user_id=%s path=%s',
request.user.pk, path)
return HttpResponseForbidden('This action is unavailable in the demo account.')
return self.get_response(request)
@@ -0,0 +1,27 @@
# Generated by Django 6.1.1 on 2026-10-19 14:54
from django.db import migrations, models
def mark_existing_demo(apps, schema_editor):
User = apps.get_model('auth', 'User')
UserSettings = apps.get_model('planner', 'UserSettings')
user = User.objects.filter(username='demo', is_staff=False, is_superuser=False).first()
if user:
UserSettings.objects.filter(user_id=user.pk).update(is_demo=True)
class Migration(migrations.Migration):
dependencies = [
('planner', '0021_automatic_hydration'),
]
operations = [
migrations.AddField(
model_name='usersettings',
name='is_demo',
field=models.BooleanField(default=False, editable=False),
),
migrations.RunPython(mark_existing_demo, migrations.RunPython.noop),
]
+1
View File
@@ -105,6 +105,7 @@ class UserSettings(models.Model):
user = models.OneToOneField( user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='planner_settings' settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='planner_settings'
) )
is_demo = models.BooleanField(default=False, editable=False)
latitude = models.DecimalField( latitude = models.DecimalField(
max_digits=9, decimal_places=6, blank=True, null=True, max_digits=9, decimal_places=6, blank=True, null=True,
validators=[MinValueValidator(-90), MaxValueValidator(90)], validators=[MinValueValidator(-90), MaxValueValidator(90)],
+3
View File
@@ -15,6 +15,7 @@ from urllib.request import urlopen
from django.core.cache import cache from django.core.cache import cache
from planner.models import Task, UserSettings from planner.models import Task, UserSettings
from planner.demo_policy import is_demo_user
OPEN_METEO_URL = 'https://api.open-meteo.com/v1/forecast' OPEN_METEO_URL = 'https://api.open-meteo.com/v1/forecast'
FORECAST_SEARCH_HORIZON_DAYS = 16 FORECAST_SEARCH_HORIZON_DAYS = 16
@@ -138,6 +139,8 @@ def _forecast_cache_key(user_id: int, latitude: Decimal, longitude: Decimal) ->
def forecasts_for_user(user) -> list[DailyForecast] | None: def forecasts_for_user(user) -> list[DailyForecast] | None:
"""Return cached normalized forecasts, or None when location/API is unavailable.""" """Return cached normalized forecasts, or None when location/API is unavailable."""
if is_demo_user(user):
return None
settings = UserSettings.objects.filter(user=user).first() settings = UserSettings.objects.filter(user=user).first()
if settings is None or settings.latitude is None or settings.longitude is None: if settings is None or settings.latitude is None or settings.longitude is None:
return None return None
+28 -3
View File
@@ -1,4 +1,29 @@
/* Keep the expanded navigation inside tablet widths as sections are added. */ /* One navigation tree is rendered for both the desktop header and mobile drawer. */
@media (min-width: 701px) and (max-width: 960px) { .primary-nav{gap:clamp(8px,1.3vw,20px);white-space:nowrap}
.primary-nav { gap: 8px; font-size: .82rem; } .nav-group{position:relative}
.nav-group__heading{display:flex;align-items:center}
.nav-group__heading>a{padding:9px 2px;color:#4d5852;text-decoration:none}
.nav-group__heading>a:hover,.nav-group--active .nav-group__heading>a{color:#235943}
.nav-group__toggle{display:grid;place-items:center;width:34px;height:40px;padding:0;border:0;border-radius:7px;color:#4d5852;background:transparent}
.nav-group__toggle span{display:block;font-size:1.15rem;line-height:1;transition:transform .18s ease}
.nav-group--open .nav-group__toggle span{transform:rotate(180deg)}
.nav-submenu{position:absolute;top:100%;left:0;z-index:30;min-width:190px;max-width:min(280px,90vw);margin:0;padding:6px;list-style:none;border:1px solid #d9e0d9;border-radius:12px;background:#fff;box-shadow:0 18px 45px #1d2b251c;white-space:normal}
.nav-submenu[hidden]{display:none!important}
.nav-submenu a{display:block;padding:10px 12px;border-radius:7px;color:#25292e;text-decoration:none}
.nav-submenu a:hover,.nav-submenu a[aria-current=page]{color:#174333;background:#e0f0e5}
.primary-nav a:focus-visible,.primary-nav button:focus-visible{outline:3px solid #235943;outline-offset:2px}
.nav-logout button{white-space:nowrap}
body[data-theme=dark] .nav-group__heading>a,body[data-theme=dark] .nav-group__toggle{color:#bac5bd}
body[data-theme=dark] .nav-group--active .nav-group__heading>a,body[data-theme=dark] .nav-group__heading>a:hover{color:#a9ddba}
body[data-theme=dark] .nav-submenu{border-color:#46544b;background:#242d27}
body[data-theme=dark] .nav-submenu a{color:#e8eee9}
body[data-theme=dark] .nav-submenu a:hover,body[data-theme=dark] .nav-submenu a[aria-current=page]{color:#fff;background:#355a45}
@media(min-width:701px) and (max-width:960px){.primary-nav{gap:8px;font-size:.82rem}.site-header__inner{gap:12px}}
@media(max-width:700px){
.js-nav-ready .nav-group__heading>a{display:block;flex:1;padding:11px 8px}
.js-nav-ready .nav-group__toggle{width:44px;height:44px}
.js-nav-ready .nav-submenu{position:static;min-width:0;max-width:none;margin:0 0 5px 12px;padding:0 0 0 10px;border:0;border-left:2px solid #d9e0d9;border-radius:0;box-shadow:none;background:transparent}
.js-nav-ready .nav-submenu a{padding:10px 8px}
.js-nav-ready .primary-nav>a:not(.button){display:block;padding:12px 8px}
} }
@media(prefers-reduced-motion:reduce){.nav-group__toggle span{transition:none}}
+43
View File
@@ -0,0 +1,43 @@
document.addEventListener('DOMContentLoaded', () => {
const nav = document.querySelector('#primary-navigation');
if (!nav) return;
const groups = Array.from(nav.querySelectorAll('[data-nav-group]'));
const mobile = window.matchMedia('(max-width: 700px)');
const setOpen = (group, open) => {
const trigger = group.querySelector('[data-nav-submenu-toggle]');
trigger.setAttribute('aria-expanded', String(open));
group.querySelector('[data-nav-submenu]').hidden = !open;
group.classList.toggle('nav-group--open', open);
};
const closeOthers = (except = null) => groups.forEach((group) => {
if (group !== except) setOpen(group, false);
});
const revealActive = () => {
closeOthers();
if (mobile.matches) {
const active = groups.find((group) => group.classList.contains('nav-group--active'));
if (active) setOpen(active, true);
}
};
groups.forEach((group) => {
group.querySelector('[data-nav-submenu-toggle]').addEventListener('click', () => {
const opening = !group.classList.contains('nav-group--open');
closeOthers(group);
setOpen(group, opening);
});
});
document.addEventListener('pointerdown', (event) => {
if (!nav.contains(event.target)) closeOthers();
});
document.addEventListener('keydown', (event) => {
if (event.key !== 'Escape') return;
const open = groups.find((group) => group.classList.contains('nav-group--open'));
if (!open) return;
event.preventDefault();
event.stopImmediatePropagation();
setOpen(open, false);
open.querySelector('[data-nav-submenu-toggle]').focus();
}, true);
mobile.addEventListener('change', revealActive);
revealActive();
});
+9 -9
View File
@@ -7,7 +7,8 @@
<meta name="description" content="A calm, focused personal task planner."> <meta name="description" content="A calm, focused personal task planner.">
<title>{% block title %}Tasknest{% endblock %}</title> <title>{% block title %}Tasknest{% endblock %}</title>
{% vite_asset 'src/main.js' %} {% vite_asset 'src/main.js' %}
<link rel="stylesheet" href="{% static 'planner/nav_spacing.css' %}?v=1"> <link rel="stylesheet" href="{% static 'planner/nav_spacing.css' %}?v=2">
<script src="{% static 'planner/navigation.js' %}?v=1" defer></script>
</head> </head>
<body data-theme="{{ user_appearance }}"> <body data-theme="{{ user_appearance }}">
<div class="app-shell"> <div class="app-shell">
@@ -21,14 +22,12 @@
<nav class="primary-nav" id="primary-navigation" aria-label="Primary navigation"> <nav class="primary-nav" id="primary-navigation" aria-label="Primary navigation">
<button class="mobile-nav-close" type="button" data-nav-close>Close menu <span aria-hidden="true">×</span></button> <button class="mobile-nav-close" type="button" data-nav-close>Close menu <span aria-hidden="true">×</span></button>
{% if user.is_authenticated %} {% if user.is_authenticated %}
<a href="{% url 'planner:task-list' %}">My tasks</a> {% for group in nav_groups %}
<a id="daily-planner-nav" class="{% if onboarding_tour.target == 'daily-planner' %}onboarding-highlight{% endif %}" href="{% url 'planner:daily-planner' %}">Daily planner</a> <div class="nav-group{% if group.active %} nav-group--active{% endif %}" data-nav-group>
<a id="health-nav" class="{% if onboarding_tour.target == 'wellbeing' %}onboarding-highlight{% endif %}" href="{% url 'planner:health' %}">Health</a> <div class="nav-group__heading"><a href="{{ group.url }}"{% if group.parent_active %} aria-current="page"{% endif %}{% if group.key == 'health' %} id="health-nav" class="{% if onboarding_tour.target == 'wellbeing' %}onboarding-highlight{% endif %}"{% endif %}>{{ group.label }}</a><button type="button" class="nav-group__toggle" aria-label="Toggle {{ group.label }} submenu" aria-expanded="false" aria-controls="nav-submenu-{{ group.key }}" data-nav-submenu-toggle><span aria-hidden="true">⌄</span></button></div>
<a href="{% url 'stress:journal' %}"{% if request.resolver_match.namespace == 'stress' %} aria-current="page"{% endif %}>Stress</a> <ul class="nav-submenu" id="nav-submenu-{{ group.key }}" data-nav-submenu hidden>{% for child in group.items %}<li><a href="{{ child.url }}"{% if child.active %} aria-current="page"{% endif %}{% if group.key == 'tasks' %} id="daily-planner-nav" class="{% if onboarding_tour.target == 'daily-planner' %}onboarding-highlight{% endif %}"{% endif %}>{{ child.label }}</a></li>{% endfor %}</ul>
<a href="{% url 'dreams:journal' %}"{% if request.resolver_match.namespace == 'dreams' %} aria-current="page"{% endif %}>Dreams</a> </div>
<a href="{% url 'food:diary' %}">Food</a> {% endfor %}
<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>
<a id="settings-nav" class="{% if onboarding_tour.target == 'settings' %}onboarding-highlight{% endif %}" href="{% url 'planner:user-settings' %}">Settings</a> <a id="settings-nav" class="{% if onboarding_tour.target == 'settings' %}onboarding-highlight{% endif %}" href="{% url 'planner:user-settings' %}">Settings</a>
<form method="post" action="{% url 'planner:user-settings' %}" class="theme-toggle">{% csrf_token %}<input type="hidden" name="section" value="appearance"><input type="hidden" name="next" value="{{ request.path }}">{% if user_appearance == 'dark' %}<input type="hidden" name="appearance" value="light"><button type="submit" aria-label="Use light mode" title="Use light mode"><span aria-hidden="true">☀</span><span class="sr-only">Use light mode</span></button>{% else %}<input type="hidden" name="appearance" value="dark"><button type="submit" aria-label="Use dark mode" title="Use dark mode"><span aria-hidden="true">☾</span><span class="sr-only">Use dark mode</span></button>{% endif %}</form> <form method="post" action="{% url 'planner:user-settings' %}" class="theme-toggle">{% csrf_token %}<input type="hidden" name="section" value="appearance"><input type="hidden" name="next" value="{{ request.path }}">{% if user_appearance == 'dark' %}<input type="hidden" name="appearance" value="light"><button type="submit" aria-label="Use light mode" title="Use light mode"><span aria-hidden="true">☀</span><span class="sr-only">Use light mode</span></button>{% else %}<input type="hidden" name="appearance" value="dark"><button type="submit" aria-label="Use dark mode" title="Use dark mode"><span aria-hidden="true">☾</span><span class="sr-only">Use dark mode</span></button>{% endif %}</form>
<form method="post" action="{% url 'planner:logout' %}" class="nav-logout">{% csrf_token %}<button type="submit">Log out</button></form> <form method="post" action="{% url 'planner:logout' %}" class="nav-logout">{% csrf_token %}<button type="submit">Log out</button></form>
@@ -41,6 +40,7 @@
</header> </header>
<div class="mobile-nav-backdrop" data-nav-backdrop hidden></div> <div class="mobile-nav-backdrop" data-nav-backdrop hidden></div>
<main class="page-content {% block page_class %}{% endblock %}"> <main class="page-content {% block page_class %}{% endblock %}">
{% if is_demo_account %}<p class="flash-message" role="note">Shared demo account: other visitors can see edits you make here. Please do not enter personal information. Demo changes reset at midnight Amsterdam time.</p>{% endif %}
{% if messages %}{% for message in messages %}<p class="flash-message" role="status">{{ message }}</p>{% endfor %}{% endif %} {% if messages %}{% for message in messages %}<p class="flash-message" role="status">{{ message }}</p>{% endfor %}{% endif %}
{% block content %}{% endblock %} {% block content %}{% endblock %}
</main> </main>
@@ -0,0 +1,10 @@
{% extends 'planner/base.html' %}
{% block title %}Form expired · Tasknest{% endblock %}
{% block content %}
<section class="settings-page">
<p class="eyebrow">Please try again</p>
<h1>This form expired</h1>
<p>Your security cookie changed or this page was open for too long. Open a fresh page and submit again.</p>
<p><a class="button" href="{% url 'planner:login' %}">Go to log in</a></p>
</section>
{% endblock %}
@@ -5,11 +5,11 @@
<p class="eyebrow">Personal preferences</p><h1>Settings</h1> <p class="eyebrow">Personal preferences</p><h1>Settings</h1>
<section class="settings-card"><h2>Time zone</h2><p>Dates and displayed times, including fasting, use this time zone. Europe/Amsterdam is the default.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="time-zone">{% for field in time_zone_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save time zone</button></form></section> <section class="settings-card"><h2>Time zone</h2><p>Dates and displayed times, including fasting, use this time zone. Europe/Amsterdam is the default.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="time-zone">{% for field in time_zone_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save time zone</button></form></section>
<section class="settings-card"><h2>First-run help</h2><p>{% if onboarding_enabled %}The guided tour is ready to continue on your dashboard.{% else %}Help is off. You can run the tour again whenever you want.{% endif %}</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="onboarding"><button class="button" type="submit" name="action" value="restart">Run feature tour</button><button class="text-link" type="submit" name="action" value="disable">Turn help off</button></form></section> <section class="settings-card"><h2>First-run help</h2><p>{% if onboarding_enabled %}The guided tour is ready to continue on your dashboard.{% else %}Help is off. You can run the tour again whenever you want.{% endif %}</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="onboarding"><button class="button" type="submit" name="action" value="restart">Run feature tour</button><button class="text-link" type="submit" name="action" value="disable">Turn help off</button></form></section>
<section class="settings-card"><h2>Location &amp; weather</h2><p>Location is optional and private. It is used only to retrieve your forecast.</p><form method="post" data-geolocation-form>{% csrf_token %}<input type="hidden" name="section" value="location">{% for field in profile_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button button--secondary" type="button" data-use-location>Use my current location</button><span data-location-status role="status"></span><button class="button" type="submit">Save location</button></form></section> {% if not is_demo_account %}<section class="settings-card"><h2>Location &amp; weather</h2><p>Location is optional and private. It is used only to retrieve your forecast.</p><form method="post" data-geolocation-form>{% csrf_token %}<input type="hidden" name="section" value="location">{% for field in profile_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button button--secondary" type="button" data-use-location>Use my current location</button><span data-location-status role="status"></span><button class="button" type="submit">Save location</button></form></section>
<section class="settings-card"><h2>Sick Day Mode</h2><p>Temporarily defer routine work while you recover.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="sick-day">{% for field in sick_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Enable Sick Day Mode</strong><small>Give routine tasks a rest while you recover.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save Sick Day settings</button></form></section> {% endif %}<section class="settings-card"><h2>Sick Day Mode</h2><p>Temporarily defer routine work while you recover.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="sick-day">{% for field in sick_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Enable Sick Day Mode</strong><small>Give routine tasks a rest while you recover.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save Sick Day settings</button></form></section>
<section class="settings-card"><h2>Hydration</h2><p>Set your daily fluid goal and how drinks are counted.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="hydration">{% for field in hydration_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save hydration settings</button></form></section> <section class="settings-card"><h2>Hydration</h2><p>Set your daily fluid goal and how drinks are counted.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="hydration">{% for field in hydration_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save hydration settings</button></form></section>
<section class="settings-card"><h2>Food</h2><p>Set optional daily nutrition goals. Exercise calories do not change these goals.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="food">{% for field in food_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save food goals</button></form></section> <section class="settings-card"><h2>Food</h2><p>Set optional daily nutrition goals. Exercise calories do not change these goals.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="food">{% for field in food_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save food goals</button></form></section>
<section class="settings-card"><h2>API access</h2><p>Create scoped tokens for apps that need access to your food log or kitchen inventory.</p><a class="button" href="{% url 'food:tokens' %}">Manage API tokens</a></section> {% if not is_demo_account %}<section class="settings-card"><h2>API access</h2><p>Create scoped tokens for apps that need access to your food log or kitchen inventory.</p><a class="button" href="{% url 'food:tokens' %}">Manage API tokens</a></section>
<section class="settings-card" aria-labelledby="ntfy-title"> <section class="settings-card" aria-labelledby="ntfy-title">
<h2 id="ntfy-title">Notifications / ntfy</h2> <h2 id="ntfy-title">Notifications / ntfy</h2>
<p>Enter your private topic URL, test it, then enable notifications.</p> <p>Enter your private topic URL, test it, then enable notifications.</p>
@@ -21,6 +21,6 @@
<button class="button" type="submit">Save notification settings</button> <button class="button" type="submit">Save notification settings</button>
</form> </form>
</section> </section>
<section class="settings-card"><h2>Fasting</h2><form method="post">{% csrf_token %}<input type="hidden" name="section" value="fasting">{% for field in fasting_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Track fasting</strong><small>Show the daily fasting and eating timer.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save fasting settings</button></form></section> {% endif %}<section class="settings-card"><h2>Fasting</h2><form method="post">{% csrf_token %}<input type="hidden" name="section" value="fasting">{% for field in fasting_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Track fasting</strong><small>Show the daily fasting and eating timer.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save fasting settings</button></form></section>
</section> </section>
{% endblock %} {% endblock %}
+32
View File
@@ -0,0 +1,32 @@
import re
from django.contrib.auth import get_user_model
from django.test import Client, TestCase
from django.urls import reverse
class CsrfRecoveryTests(TestCase):
def setUp(self):
self.client = Client(enforce_csrf_checks=True)
get_user_model().objects.create_user('csrf-synthetic', password='test-password')
def test_stale_login_form_offers_retry_and_fresh_form_succeeds(self):
login_url = reverse('planner:login')
self.client.get(login_url, secure=True)
stale = self.client.post(login_url, {
'username': 'csrf-synthetic', 'password': 'test-password',
'csrfmiddlewaretoken': 'invalid',
}, secure=True, HTTP_ORIGIN='https://testserver')
self.assertEqual(stale.status_code, 403)
self.assertContains(stale, 'This form expired', status_code=403)
self.assertContains(stale, 'Go to log in', status_code=403)
fresh = self.client.get(login_url, secure=True)
token = re.search(r'name="csrfmiddlewaretoken" value="([^"]+)"',
fresh.content.decode()).group(1)
response = self.client.post(login_url, {
'username': 'csrf-synthetic', 'password': 'test-password',
'csrfmiddlewaretoken': token,
}, secure=True, HTTP_ORIGIN='https://testserver')
self.assertRedirects(response, reverse('planner:task-list'),
fetch_redirect_response=False)
+126
View File
@@ -0,0 +1,126 @@
from django.contrib.auth import get_user_model
from django.core.files.base import ContentFile
from django.core.management import call_command
from django.core.cache import cache
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from datetime import timedelta
from oauth2_provider.models import Application, get_grant_model
from dreams.models import DreamEntry
from food.api import create_token
from food.models import PersonalAccessToken
from food.models import FoodLogAttachment, FoodLogEntry
from planner.models import UserSettings
from recipes.models import Recipe
from stress.models import StressEntry
from tempfile import TemporaryDirectory
class DemoPolicyTests(TestCase):
def setUp(self):
self.demo = get_user_model().objects.create_user('synthetic-demo', password='test')
UserSettings.objects.create(user=self.demo, is_demo=True)
self.normal = get_user_model().objects.create_user('synthetic-normal', password='test')
self.client.force_login(self.demo)
def test_demo_cannot_create_tokens_or_authorize(self):
with self.assertRaises(ValueError):
create_token(self.demo, 'blocked', ['food:read'])
self.assertEqual(self.client.get(reverse('food:tokens')).status_code, 403)
self.assertEqual(self.client.get('/o/authorize/').status_code, 403)
self.assertFalse(PersonalAccessToken.objects.filter(user=self.demo).exists())
self.assertEqual(self.client.get('/settings/notifications/ntfy/test/').status_code, 403)
def test_demo_cannot_trigger_external_requests_or_upload(self):
self.assertEqual(self.client.post('/food/search/openfoodfacts/', {'q': 'oats'}).status_code, 403)
self.assertEqual(self.client.post('/recipes/new/', content_type='multipart/form-data').status_code, 403)
self.assertEqual(self.client.post('/recipes/new/', {'title': 'Injected'}).status_code, 403)
self.assertEqual(self.client.post('/settings/', {'section': 'ntfy', 'ntfy_url': 'https://example.com'}).status_code, 403)
def test_normal_user_keeps_token_access(self):
self.client.force_login(self.normal)
self.assertEqual(self.client.get(reverse('food:tokens')).status_code, 200)
token, _ = create_token(self.normal, 'allowed', ['food:read'])
self.assertEqual(token.user_id, self.normal.pk)
def test_legacy_demo_oauth_code_cannot_be_exchanged_anonymously(self):
application = Application.objects.create(user=self.demo, name='Legacy demo client',
client_type=Application.CLIENT_PUBLIC,
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
redirect_uris='https://example.com/callback')
get_grant_model().objects.create(user=self.demo, application=application,
code='legacy-demo-code', expires=timezone.now() + timedelta(minutes=5),
redirect_uri='https://example.com/callback', scope='food:read')
self.client.logout()
response = self.client.post('/o/token/', {'grant_type': 'authorization_code',
'code': 'legacy-demo-code'})
self.assertEqual(response.status_code, 403)
self.assertEqual(response.json()['error'], 'access_denied')
@override_settings(DEMO_MUTATIONS_PER_MINUTE=2)
def test_demo_mutation_rate_and_body_size_limits(self):
cache.clear()
url = reverse('planner:hydration-add')
self.assertEqual(self.client.post(url).status_code, 200)
self.assertEqual(self.client.post(url).status_code, 200)
self.assertEqual(self.client.post(url).status_code, 429)
cache.clear()
response = self.client.post(url, data='x' * (1024 * 1024 + 1), content_type='text/plain')
self.assertEqual(response.status_code, 413)
class DemoResetTests(TestCase):
def test_reset_clears_new_journals_and_tokens_without_touching_other_user(self):
call_command('seed_demo', username='synthetic-seed', password='test', verbosity=0)
demo = get_user_model().objects.get(username='synthetic-seed')
other = get_user_model().objects.create_user('synthetic-other', password='test')
temporary_stress = StressEntry.objects.create(user=demo, score=3)
StressEntry.objects.create(user=other, score=3)
temporary_dream = DreamEntry.objects.create(user=demo, wake_up_date='2026-10-19',
title='Temporary dream', narrative='Demo data')
token = PersonalAccessToken.objects.create(user=demo, name='legacy', prefix='legacy123',
token_hash='0' * 64, scopes=['food:read'])
call_command('seed_demo', username='synthetic-seed', verbosity=0)
self.assertFalse(StressEntry.objects.filter(pk=temporary_stress.pk).exists())
self.assertTrue(StressEntry.objects.filter(user=other).exists())
self.assertFalse(DreamEntry.objects.filter(pk=temporary_dream.pk).exists())
self.assertEqual(StressEntry.objects.filter(user=demo).count(), 1)
self.assertEqual(DreamEntry.objects.filter(user=demo).count(), 1)
self.assertFalse(PersonalAccessToken.objects.filter(pk=token.pk).exists())
self.assertTrue(UserSettings.objects.get(user=demo).is_demo)
demo.refresh_from_db()
self.assertTrue(demo.check_password('test'))
def test_reset_refuses_unmarked_account(self):
from django.core.management.base import CommandError
user = get_user_model().objects.create_user('synthetic-real', password='test')
UserSettings.objects.create(user=user)
with self.assertRaises(CommandError):
call_command('seed_demo', username='synthetic-real', password='test', verbosity=0)
def test_reset_removes_owned_files_and_sessions(self):
with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
with self.captureOnCommitCallbacks(execute=True):
call_command('seed_demo', username='synthetic-files', password='test', verbosity=0)
demo = get_user_model().objects.get(username='synthetic-files')
recipe = Recipe.objects.create(owner=demo, title='Temporary recipe')
curated = Recipe.objects.create(owner=demo, title='Curated recipe',
status=Recipe.Status.PUBLISHED)
recipe.photo.save('recipe.png', ContentFile(b'recipe image'), save=True)
entry = FoodLogEntry.objects.filter(user=demo).first()
attachment = FoodLogAttachment(log_entry=entry, original_filename='food.png',
content_type='image/png', file_size=10)
attachment.image.save('food.png', ContentFile(b'food image'), save=True)
recipe_path, attachment_path = recipe.photo.path, attachment.image.path
self.client.force_login(demo)
with self.captureOnCommitCallbacks(execute=True):
call_command('seed_demo', username='synthetic-files', password='test', verbosity=0)
from pathlib import Path
self.assertFalse(Path(recipe_path).exists())
self.assertFalse(Path(attachment_path).exists())
self.assertTrue(Recipe.objects.filter(pk=curated.pk).exists())
self.assertFalse(Recipe.objects.filter(pk=recipe.pk).exists())
self.assertRedirects(self.client.get(reverse('planner:user-settings')),
'/login/?next=/settings/', fetch_redirect_response=False)
+22
View File
@@ -0,0 +1,22 @@
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
@override_settings(MIDDLEWARE=[item for item in settings.MIDDLEWARE if not item.startswith('whitenoise.')],
SECURE_SSL_REDIRECT=False)
class NavigationTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='nav-test', password='test')
self.client.force_login(self.user)
def test_navigation_has_one_tree_and_active_child(self):
response = self.client.get(reverse('groceries:index'))
self.assertEqual(response.status_code, 200)
html = response.content.decode()
self.assertEqual(html.count('id="nav-submenu-food"'), 1)
self.assertIn('href="/groceries/" aria-current="page"', html)
self.assertIn('nav-group--active', html)
for url in ('/daily/', '/health/', '/food/', '/recipes/', '/food/inventory/', '/groceries/'):
self.assertIn(f'href="{url}"', html)
@@ -45,6 +45,7 @@
</div> </div>
<form class="recipes-serving-form" method="get" action="{% url 'recipes:detail' selected.api_id %}"><label for="recipe-servings">Servings</label><input id="recipe-servings" type="number" name="servings" min="0.01" max="99999.99" step="0.01" value="{{ analysis.servings|floatformat:-2 }}"><label class="recipes-checkbox"><input type="checkbox" name="optional" value="1"{% if analysis.include_optional %} checked{% endif %}> Include optional ingredients</label><button type="submit" class="recipes-outline-button">Update</button></form> <form class="recipes-serving-form" method="get" action="{% url 'recipes:detail' selected.api_id %}"><label for="recipe-servings">Servings</label><input id="recipe-servings" type="number" name="servings" min="0.01" max="99999.99" step="0.01" value="{{ analysis.servings|floatformat:-2 }}"><label class="recipes-checkbox"><input type="checkbox" name="optional" value="1"{% if analysis.include_optional %} checked{% endif %}> Include optional ingredients</label><button type="submit" class="recipes-outline-button">Update</button></form>
<p class="recipes-cook-entry"><a class="button" href="{% url 'recipes:cook' selected.api_id %}?servings={{ analysis.servings }}{% if analysis.include_optional %}&amp;optional=1{% endif %}">Start cooking</a></p> <p class="recipes-cook-entry"><a class="button" href="{% url 'recipes:cook' selected.api_id %}?servings={{ analysis.servings }}{% if analysis.include_optional %}&amp;optional=1{% endif %}">Start cooking</a></p>
<p class="recipes-cook-entry"><a class="recipes-outline-button" href="{% url 'groceries:recipe-preview' selected.api_id %}?servings={{ analysis.servings }}{% if analysis.include_optional %}&amp;optional=1{% endif %}">Add missing ingredients to groceries</a></p>
{% if analysis_error %}<p class="recipes-form-error" role="alert">{{ analysis_error }}</p>{% endif %} {% if analysis_error %}<p class="recipes-form-error" role="alert">{{ analysis_error }}</p>{% endif %}
<div class="recipes-content-grid"> <div class="recipes-content-grid">
<section class="recipes-panel" aria-labelledby="recipe-ingredients-heading"><h3 id="recipe-ingredients-heading">Ingredients</h3><ul class="recipes-ingredient-list">{% for line in analysis.lines %}<li><span>{{ line.name }}{% if line.source %}<small>From {{ line.source }}</small>{% endif %}{% if line.ingredient.preparation_note %}<small>{{ line.ingredient.preparation_note }}</small>{% endif %}<small class="recipes-stock-label recipes-stock-label--{{ line.status }}">{{ line.status|capfirst }}{% if line.reason %}: {{ line.reason }}{% endif %}</small></span><strong>{{ line.quantity|floatformat:-3 }} {{ line.unit }}</strong>{% if line.optional %}<em>Optional{% if not analysis.include_optional %} · excluded{% endif %}</em>{% endif %}</li>{% empty %}<li class="recipes-muted">No ingredients added yet.</li>{% endfor %}</ul></section> <section class="recipes-panel" aria-labelledby="recipe-ingredients-heading"><h3 id="recipe-ingredients-heading">Ingredients</h3><ul class="recipes-ingredient-list">{% for line in analysis.lines %}<li><span>{{ line.name }}{% if line.source %}<small>From {{ line.source }}</small>{% endif %}{% if line.ingredient.preparation_note %}<small>{{ line.ingredient.preparation_note }}</small>{% endif %}<small class="recipes-stock-label recipes-stock-label--{{ line.status }}">{{ line.status|capfirst }}{% if line.reason %}: {{ line.reason }}{% endif %}</small></span><strong>{{ line.quantity|floatformat:-3 }} {{ line.unit }}</strong>{% if line.optional %}<em>Optional{% if not analysis.include_optional %} · excluded{% endif %}</em>{% endif %}</li>{% empty %}<li class="recipes-muted">No ingredients added yet.</li>{% endfor %}</ul></section>
+1
View File
@@ -1,6 +1,7 @@
asarPy==1.0.1 asarPy==1.0.1
asgiref==3.12.1 asgiref==3.12.1
Django==6.1.1 Django==6.1.1
whitenoise==6.12.0
Pillow==12.3.0 Pillow==12.3.0
django-oauth-toolkit==3.4.1 django-oauth-toolkit==3.4.1
mcp==2.3.0 mcp==2.3.0
+30 -6
View File
@@ -12,25 +12,42 @@ https://docs.djangoproject.com/en/6.1/ref/settings/
import os import os
from pathlib import Path from pathlib import Path
from django.core.exceptions import ImproperlyConfigured
# Build paths inside the project like this: BASE_DIR / 'subdir'. # Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production def _local_env(name):
# See https://docs.djangoproject.com/en/6.1/howto/deployment/checklist/ if name in os.environ:
return os.environ[name]
path = BASE_DIR.parent / '.env'
try:
lines = path.read_text(encoding='utf-8').splitlines()
except FileNotFoundError:
return ''
for line in lines:
key, separator, value = line.strip().partition('=')
if separator and key == name:
return value.strip().strip('"\'')
return ''
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-x%2-iw9@k2s1td)7m7-ww55w1x(5lh$j*luk8_fbytb-36il%t'
# SECURITY WARNING: don't run with debug turned on in production! DEBUG = _local_env('DJANGO_DEBUG').lower() in {'1', 'true', 'yes'}
DEBUG = True SECRET_KEY = _local_env('DJANGO_SECRET_KEY')
TASKNEST_DEMO_PASSWORD = _local_env('TASKNEST_DEMO_PASSWORD')
if not SECRET_KEY:
raise ImproperlyConfigured('Set DJANGO_SECRET_KEY in the environment or ignored .env file.')
SESSION_COOKIE_SECURE = not DEBUG
CSRF_COOKIE_SECURE = not DEBUG
SECURE_SSL_REDIRECT = not DEBUG
ALLOWED_HOSTS = ["localhost", "127.0.0.1", "tasksnest.jorendegraaf.eu"] ALLOWED_HOSTS = ["localhost", "127.0.0.1", "tasksnest.jorendegraaf.eu"]
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
CSRF_TRUSTED_ORIGINS = [ CSRF_TRUSTED_ORIGINS = [
"https://tasksnest.jorendegraaf.eu", "https://tasksnest.jorendegraaf.eu",
] ]
CSRF_FAILURE_VIEW = 'planner.csrf.csrf_failure'
# Application definition # Application definition
@@ -45,6 +62,7 @@ INSTALLED_APPS = [
'planner', 'planner',
'food.apps.FoodConfig', 'food.apps.FoodConfig',
'recipes', 'recipes',
'groceries',
'stress', 'stress',
'dreams', 'dreams',
] ]
@@ -55,10 +73,12 @@ RECIPE_MATCH_DEMO_USERNAME = os.environ.get('TASKNEST_RECIPE_MATCH_DEMO_USERNAME
MIDDLEWARE = [ MIDDLEWARE = [
'food.api_middleware.ApiErrorMiddleware', 'food.api_middleware.ApiErrorMiddleware',
'django.middleware.security.SecurityMiddleware', 'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware', 'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',
'planner.middleware_demo.DemoAccountPolicyMiddleware',
'planner.middleware.UserTimezoneMiddleware', 'planner.middleware.UserTimezoneMiddleware',
'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
@@ -87,6 +107,8 @@ OAUTH2_PROVIDER = {
'DCR_ENABLED': False, 'DCR_ENABLED': False,
'OAUTH2_GRANT_TYPES_SUPPORTED': ['authorization_code', 'refresh_token'], 'OAUTH2_GRANT_TYPES_SUPPORTED': ['authorization_code', 'refresh_token'],
'OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED': ['none', 'client_secret_basic', 'client_secret_post'], 'OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED': ['none', 'client_secret_basic', 'client_secret_post'],
'ALLOWED_REDIRECT_URI_SCHEMES': ['http', 'https'] if DEBUG else ['https'],
'COMPLIANT_BCP_RFC9700_REDIRECT_URI_SCHEME': not DEBUG,
'COMPLIANT_BCP_RFC9700_TOKEN_STORAGE': True, 'COMPLIANT_BCP_RFC9700_TOKEN_STORAGE': True,
'COMPLIANT_BCP_RFC9700_PKCE_METHOD': True, 'COMPLIANT_BCP_RFC9700_PKCE_METHOD': True,
'COMPLIANT_BCP_RFC9700_PKCE_REQUIRED': True, 'COMPLIANT_BCP_RFC9700_PKCE_REQUIRED': True,
@@ -109,6 +131,7 @@ TEMPLATES = [
'django.contrib.auth.context_processors.auth', 'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages', 'django.contrib.messages.context_processors.messages',
'planner.context_processors.appearance', 'planner.context_processors.appearance',
'planner.context_processors.navigation',
], ],
}, },
}, },
@@ -163,6 +186,7 @@ USE_TZ = True
# https://docs.djangoproject.com/en/6.1/howto/static-files/ # https://docs.djangoproject.com/en/6.1/howto/static-files/
STATIC_URL = 'static/' STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_ROOT = BASE_DIR / 'private_media' MEDIA_ROOT = BASE_DIR / 'private_media'
# Vite writes built assets and its manifest here. Use the Vite server only when # Vite writes built assets and its manifest here. Use the Vite server only when
+1
View File
@@ -27,6 +27,7 @@ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('food/', include('food.urls', namespace='food')), path('food/', include('food.urls', namespace='food')),
path('recipes/', include('recipes.urls', namespace='recipes')), path('recipes/', include('recipes.urls', namespace='recipes')),
path('groceries/', include('groceries.urls', namespace='groceries')),
path('stress/', include('stress.urls', namespace='stress')), path('stress/', include('stress.urls', namespace='stress')),
path('dreams/', include('dreams.urls', namespace='dreams')), path('dreams/', include('dreams.urls', namespace='dreams')),
path('', include('planner.urls')), path('', include('planner.urls')),