From 5b986134be0a1f4751b37171945dd7b23b420fb0 Mon Sep 17 00:00:00 2001 From: Joren de Graaf Date: Thu, 22 Oct 2026 10:32:41 +0200 Subject: [PATCH] latest changes --- .../page-2026-10-19T16-00-13-503Z.yml | 29 + .../page-2026-10-19T16-00-19-542Z.yml | 681 ++++++++++++++++++ AGENTS.md | 4 +- main/MCP.md | 2 + main/README.md | 34 +- main/deploy/systemd/tasknest-demo-seed.timer | 2 +- main/food/api.py | 5 + main/food/api_urls.py | 4 + main/food/forms.py | 53 +- main/food/services/openfoodfacts.py | 1 + main/food/static/food/food.css | 3 + main/food/templates/food/edit.html | 2 +- main/food/templates/food/inventory_add.html | 2 +- main/food/templates/food/inventory_edit.html | 2 +- .../food/templates/food/inventory_manual.html | 4 +- .../templates/food/inventory_overview.html | 1 + main/food/templates/food/manual.html | 4 +- .../templates/food/partials/add_content.html | 12 +- .../templates/food/partials/edit_content.html | 15 + .../partials/inventory_product_actions.html | 4 +- .../partials/product_nutrition_fields.html | 21 + main/food/templates/food/product_edit.html | 5 + main/food/test_nutrition_ui.py | 136 ++++ main/food/urls.py | 1 + main/food/views.py | 24 +- main/groceries/__init__.py | 0 main/groceries/api.py | 91 +++ main/groceries/migrations/0001_initial.py | 67 ++ .../migrations/0002_groceryrecipedemand.py | 35 + ...groceryitem_inventory_transfer_and_more.py | 25 + main/groceries/migrations/__init__.py | 0 main/groceries/models.py | 79 ++ main/groceries/services.py | 268 +++++++ main/groceries/static/groceries/groceries.css | 1 + main/groceries/templates/groceries/index.html | 8 + .../groceries/inventory_transfer.html | 3 + .../templates/groceries/partials/list.html | 2 + .../templates/groceries/recipe_preview.html | 3 + main/groceries/tests.py | 100 +++ main/groceries/urls.py | 14 + main/groceries/views.py | 119 +++ main/mcp_server/server.py | 70 ++ main/mcp_server/tests.py | 4 +- main/planner/context_processors.py | 39 +- main/planner/csrf.py | 7 + main/planner/demo_policy.py | 8 + main/planner/management/commands/seed_demo.py | 63 +- main/planner/middleware_demo.py | 72 ++ .../migrations/0022_usersettings_is_demo.py | 27 + main/planner/models.py | 1 + main/planner/services/weather.py | 3 + main/planner/static/planner/nav_spacing.css | 31 +- main/planner/static/planner/navigation.js | 43 ++ main/planner/templates/planner/base.html | 18 +- .../templates/planner/csrf_failure.html | 10 + .../templates/planner/user_settings.html | 8 +- main/planner/test_csrf_recovery.py | 32 + main/planner/test_demo_policy.py | 126 ++++ main/planner/test_navigation.py | 22 + main/recipes/templates/recipes/library.html | 1 + main/requirements.txt | 1 + main/tasksnest/settings.py | 36 +- main/tasksnest/urls.py | 1 + 63 files changed, 2412 insertions(+), 77 deletions(-) create mode 100644 .playwright-mcp/page-2026-10-19T16-00-13-503Z.yml create mode 100644 .playwright-mcp/page-2026-10-19T16-00-19-542Z.yml create mode 100644 main/food/templates/food/partials/product_nutrition_fields.html create mode 100644 main/food/templates/food/product_edit.html create mode 100644 main/food/test_nutrition_ui.py create mode 100644 main/groceries/__init__.py create mode 100644 main/groceries/api.py create mode 100644 main/groceries/migrations/0001_initial.py create mode 100644 main/groceries/migrations/0002_groceryrecipedemand.py create mode 100644 main/groceries/migrations/0003_groceryitem_inventory_transfer_and_more.py create mode 100644 main/groceries/migrations/__init__.py create mode 100644 main/groceries/models.py create mode 100644 main/groceries/services.py create mode 100644 main/groceries/static/groceries/groceries.css create mode 100644 main/groceries/templates/groceries/index.html create mode 100644 main/groceries/templates/groceries/inventory_transfer.html create mode 100644 main/groceries/templates/groceries/partials/list.html create mode 100644 main/groceries/templates/groceries/recipe_preview.html create mode 100644 main/groceries/tests.py create mode 100644 main/groceries/urls.py create mode 100644 main/groceries/views.py create mode 100644 main/planner/csrf.py create mode 100644 main/planner/demo_policy.py create mode 100644 main/planner/middleware_demo.py create mode 100644 main/planner/migrations/0022_usersettings_is_demo.py create mode 100644 main/planner/static/planner/navigation.js create mode 100644 main/planner/templates/planner/csrf_failure.html create mode 100644 main/planner/test_csrf_recovery.py create mode 100644 main/planner/test_demo_policy.py create mode 100644 main/planner/test_navigation.py diff --git a/.playwright-mcp/page-2026-10-19T16-00-13-503Z.yml b/.playwright-mcp/page-2026-10-19T16-00-13-503Z.yml new file mode 100644 index 0000000..1202218 --- /dev/null +++ b/.playwright-mcp/page-2026-10-19T16-00-13-503Z.yml @@ -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: . \ No newline at end of file diff --git a/.playwright-mcp/page-2026-10-19T16-00-19-542Z.yml b/.playwright-mcp/page-2026-10-19T16-00-19-542Z.yml new file mode 100644 index 0000000..804bd49 --- /dev/null +++ b/.playwright-mcp/page-2026-10-19T16-00-19-542Z.yml @@ -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 \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index c79c019..8856714 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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`. +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 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. @@ -25,4 +27,4 @@ For UI changes, check relevant semantic headings and controls, accessible names When I give you a card to work on, you should: 1. Look in the TasksNest project 2. Move the card to in-progress and add any pertinent findings at the end to the progress notes. This also applies to passes/phases that have a defined downtime for me to check and push things to git. -3. When you're done with the card you can move it to complete. \ No newline at end of file +3. When you're done with the card you can move it to complete. diff --git a/main/MCP.md b/main/MCP.md index 006ad76..54170e1 100644 --- a/main/MCP.md +++ b/main/MCP.md @@ -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. +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/`: ```caddyfile diff --git a/main/README.md b/main/README.md index d5ab131..1219874 100644 --- a/main/README.md +++ b/main/README.md @@ -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 ``` -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 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 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 `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 ``` -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. ## Fasting phase notifications diff --git a/main/deploy/systemd/tasknest-demo-seed.timer b/main/deploy/systemd/tasknest-demo-seed.timer index af22a56..1ecf187 100644 --- a/main/deploy/systemd/tasknest-demo-seed.timer +++ b/main/deploy/systemd/tasknest-demo-seed.timer @@ -2,7 +2,7 @@ Description=Run the Tasknest demo-data reset every day [Timer] -OnCalendar=*-*-* 03:15:00 Europe/Amsterdam +OnCalendar=*-*-* 00:00:00 Europe/Amsterdam Persistent=true Unit=tasknest-demo-seed.service diff --git a/main/food/api.py b/main/food/api.py index 70929d8..f7a49e1 100644 --- a/main/food/api.py +++ b/main/food/api.py @@ -19,6 +19,7 @@ from django.utils.dateparse import parse_date, parse_time from django.views.decorators.csrf import csrf_exempt 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 .models import (ApiIdempotencyRecord, FoodLogAttachment, FoodLogEntry, FoodProduct, InventoryCategory, InventoryLocation, KitchenInventoryItem, @@ -52,6 +53,8 @@ def token_value(): 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() 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) @@ -74,6 +77,8 @@ def _authenticate(request): return None, error('revoked_token', 'API token has been revoked.', 401) if token.expires_at and token.expires_at <= timezone.now(): 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()) return token, None diff --git a/main/food/api_urls.py b/main/food/api_urls.py index 970d284..1d7e85e 100644 --- a/main/food/api_urls.py +++ b/main/food/api_urls.py @@ -3,6 +3,7 @@ from . import api, api_schema from recipes import api as recipe_api from stress import api as stress_api from dreams import api as dream_api +from groceries import api as grocery_api urlpatterns = [ path('auth/whoami/', api.whoami), @@ -34,6 +35,9 @@ urlpatterns = [ path('hydration/manual/', api.hydration_log), path('hydration/manual//', api.hydration_manual_entry), path('hydration/settings/', api.hydration_settings), + path('groceries/', grocery_api.collection), + path('groceries//', grocery_api.item), + path('groceries/recipe//', grocery_api.recipe_import), 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_item), diff --git a/main/food/forms.py b/main/food/forms.py index 555847b..23c2e7a 100644 --- a/main/food/forms.py +++ b/main/food/forms.py @@ -7,15 +7,16 @@ from .models import FoodLogEntry, FoodPortion, FoodProduct, KitchenInventoryItem class ManualFoodForm(forms.ModelForm): 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: 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 = { 'energy_kcal_100': 'Calories for base quantity', 'carbohydrates_100': 'Carbohydrates for base quantity', 'protein_100': 'Protein 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)', 'sugars_100': 'Sugars 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) super().__init__(*args, **kwargs) self.fields['barcode'].required = False - for field in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100'): - self.fields[field].required = True + self.fields['base_unit'].required = False + 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): 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(): + 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.') return barcode @@ -42,7 +50,7 @@ class ManualFoodForm(forms.ModelForm): if basis: factor = Decimal('100') / basis 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) 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.') @@ -52,7 +60,7 @@ class ManualFoodForm(forms.ModelForm): product = super().save(commit=False) factor = Decimal('100') / self.cleaned_data['basis_amount'] 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] setattr(product, name, (value * factor).quantize(Decimal('0.001')) if value is not None else None) if commit: @@ -162,9 +170,15 @@ class FoodLogForm(forms.ModelForm): class FoodLogEditForm(FoodLogForm): + edit_nutrition = forms.BooleanField(required=False, label='Use these nutrition values for this entry') + class Meta(FoodLogForm.Meta): - fields = FoodLogForm.Meta.fields + ('quantity',) - labels = {**FoodLogForm.Meta.labels, 'quantity': 'Quantity (portions)'} + fields = FoodLogForm.Meta.fields + ('quantity', 'calories_kcal', 'carbohydrates_g', + '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, '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()) -class InventoryManualProductForm(forms.ModelForm): - class Meta: - model = FoodProduct - fields = ('product_name', 'brand', 'barcode', 'package_quantity') - - 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 +class InventoryManualProductForm(ManualFoodForm): + class Meta(ManualFoodForm.Meta): + fields = ('product_name', 'brand', 'barcode', 'package_quantity', 'base_unit', + 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', + 'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100') diff --git a/main/food/services/openfoodfacts.py b/main/food/services/openfoodfacts.py index 0ff1f8d..5c559f4 100644 --- a/main/food/services/openfoodfacts.py +++ b/main/food/services/openfoodfacts.py @@ -147,6 +147,7 @@ def cached_product(user, barcode, *, refresh=False): raise ValueError('Enter a numeric barcode.') product = FoodProduct.objects.filter(owner=user, barcode=barcode).first() 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))): return product if not settings.OPENFOODFACTS_ENABLED: diff --git a/main/food/static/food/food.css b/main/food/static/food/food.css index 972dc1d..2494bc6 100644 --- a/main/food/static/food/food.css +++ b/main/food/static/food/food.css @@ -105,3 +105,6 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317} .food-ring-laps{font-size:.7rem} .food-macro--pink{--accent:#d45b8b} .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}} diff --git a/main/food/templates/food/edit.html b/main/food/templates/food/edit.html index 164d502..0ccf54f 100644 --- a/main/food/templates/food/edit.html +++ b/main/food/templates/food/edit.html @@ -1,6 +1,6 @@ {% extends 'planner/base.html' %}{% load static %} {% block title %}Edit food log · Tasknest{% endblock %} {% block content %} - + {% include 'food/partials/edit_content.html' %} {% endblock %} diff --git a/main/food/templates/food/inventory_add.html b/main/food/templates/food/inventory_add.html index 1fbe3f1..831b7cf 100644 --- a/main/food/templates/food/inventory_add.html +++ b/main/food/templates/food/inventory_add.html @@ -3,7 +3,7 @@ {% block content %}
← Kitchen Inventory

Add to inventory

{% if product %} -
{% if product.image_url %}{% endif %}

{{ product.product_name }}

{% if product.brand %}

{{ product.brand }}

{% endif %}{% if product.package_quantity %}

{{ product.package_quantity }}

{% endif %}{% if off_categories %}

Open Food Facts: {{ off_categories }}

{% endif %}
+
{% if product.image_url %}{% endif %}

{{ product.product_name }}

{% if product.brand %}

{{ product.brand }}

{% endif %}{% if product.package_quantity %}

{{ product.package_quantity }}

{% endif %}{% if off_categories %}

Open Food Facts: {{ off_categories }}

{% endif %}

View or edit product nutrition

{% if existing %}

Already in inventory

{% for item in existing %}
{{ item.location.name }} · Quantity {{ item.quantity }}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}
{% csrf_token %}
{% endfor %}

Use the form below to add this product separately.

{% endif %}
{% csrf_token %}{{ form.non_field_errors }} {% for field in form %}
{{ field.label_tag }}{% if field.name == 'quantity' %}
{{ field }}
{% else %}{{ field }}{% endif %}{{ field.errors }}
{% endfor %} diff --git a/main/food/templates/food/inventory_edit.html b/main/food/templates/food/inventory_edit.html index aa9beb2..9f0c212 100644 --- a/main/food/templates/food/inventory_edit.html +++ b/main/food/templates/food/inventory_edit.html @@ -1,3 +1,3 @@ {% extends 'planner/base.html' %}{% load static %} {% block title %}Edit inventory item · Tasknest{% endblock %} -{% block content %}
← Kitchen Inventory

Edit {{ item.product.product_name }}

{% csrf_token %}{{ form.non_field_errors }}{% for field in form %}
{{ field.label_tag }}{% if field.name == 'quantity' %}
{{ field }}
{% else %}{{ field }}{% endif %}{{ field.errors }}
{% endfor %}{% for location in locations %}{% for category in categories %}
{% endblock %} +{% block content %}
← Kitchen Inventory

Edit {{ item.product.product_name }}

This form changes stock for this package. View or edit product nutrition for future food logs.

{% csrf_token %}{{ form.non_field_errors }}{% for field in form %}
{{ field.label_tag }}{% if field.name == 'quantity' %}
{{ field }}
{% else %}{{ field }}{% endif %}{{ field.errors }}
{% endfor %}{% for location in locations %}{% for category in categories %}
{% endblock %} diff --git a/main/food/templates/food/inventory_manual.html b/main/food/templates/food/inventory_manual.html index a2e3cd6..5b1cc05 100644 --- a/main/food/templates/food/inventory_manual.html +++ b/main/food/templates/food/inventory_manual.html @@ -1,3 +1,5 @@ {% extends 'planner/base.html' %}{% load static %} {% block title %}Create inventory product · Tasknest{% endblock %} -{% block content %}
← Add item

Create product

Save a product to the shared food catalogue. Nutrition can be added later.

{% csrf_token %}{% for field in form %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endfor %}
{% endblock %} +{% block content %}
← Add item

Create product

Save a product for both Kitchen Inventory and Food Diary. Package size describes stock; nutrition is entered separately for the chosen basis.

{% 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' %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endif %}{% endfor %} +{% include 'food/partials/product_nutrition_fields.html' %}
{% endblock %} diff --git a/main/food/templates/food/inventory_overview.html b/main/food/templates/food/inventory_overview.html index 1cf310e..0a706db 100644 --- a/main/food/templates/food/inventory_overview.html +++ b/main/food/templates/food/inventory_overview.html @@ -8,6 +8,7 @@ {% for card in cards %}
{% if card.product.image_url %}{% endif %}

{{ card.product.product_name }}

{% if card.product.brand %}

{{ card.product.brand }}

{% endif %}

{{ card.total|floatformat:-3 }} {% if card.unit == "packs" and card.total == 1 %}pack{% else %}{{ card.unit }}{% endif %} remaining · {{ card.packages|length }} package{{ card.packages|length|pluralize }}

+

View or edit product nutrition

View packages
{% for item in card.packages %}
Pack {{ forloop.counter }} · {{ item.package_status|title }}

{% 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 %}

{{ item.location.name }}{% if item.category %} · {{ item.category.name }}{% endif %}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}
{% endfor %}
Use amount
{% csrf_token %}
{% empty %}

No inventory items found.

Add your first item
{% endfor %} diff --git a/main/food/templates/food/manual.html b/main/food/templates/food/manual.html index a31143b..db4a021 100644 --- a/main/food/templates/food/manual.html +++ b/main/food/templates/food/manual.html @@ -1,3 +1,5 @@ {% extends 'planner/base.html' %}{% load static %} {% block title %}Create food · Tasknest{% endblock %} -{% block content %}
← Back to foods

Create a food

Enter nutrition for the base quantity and unit you choose. Missing optional values stay unknown.

{% csrf_token %}{% for field in form %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endfor %}
{% endblock %} +{% block content %}
← Back to foods

Create a food

Save nutrition once, then choose how much to log. You can correct this product later; existing diary entries keep their recorded values.

{% csrf_token %}{{ form.non_field_errors }} +{% for field in form %}{% if field.name == 'product_name' or field.name == 'brand' or field.name == 'barcode' %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endif %}{% endfor %} +{% include 'food/partials/product_nutrition_fields.html' %}
{% endblock %} diff --git a/main/food/templates/food/partials/add_content.html b/main/food/templates/food/partials/add_content.html index fb40c13..5c0842b 100644 --- a/main/food/templates/food/partials/add_content.html +++ b/main/food/templates/food/partials/add_content.html @@ -12,11 +12,13 @@
Carbohydrates
{{ product.carbohydrates_100|default_if_none:'—' }} g
Protein
{{ product.protein_100|default_if_none:'—' }} g
Fat
{{ product.fat_100|default_if_none:'—' }} g
+
Saturated fat
{{ product.saturated_fat_100|default_if_none:'—' }} g
Sugars
{{ product.sugars_100|default_if_none:'—' }} g
Fibre
{{ product.fibre_100|default_if_none:'—' }} g
Salt
{{ product.salt_100|default_if_none:'—' }} g
{% if product.source == 'openfoodfacts' %}

Product data from Open Food Facts.

{% endif %} +

Edit product nutrition

{% csrf_token %} @@ -50,11 +52,11 @@

Recent

{% include 'food/partials/product_list.html' with products=recents %}
{% else %}{% include 'food/partials/product_list.html' with products=products %}{% endif %} - {% csrf_token %}
-

External product data from Open Food Facts.

+ {% if not is_demo_account %}Scan barcode + Search Open Food Facts{% endif %}
+ {% if not is_demo_account %}
{% csrf_token %}
{% endif %} + {% if not is_demo_account %}

External product data from Open Food Facts.

{% endif %} {% endif %} {% if product %}{% endif %} -{% if not product %}{% endif %} +{% if not product and not is_demo_account %}{% endif %} diff --git a/main/food/templates/food/partials/edit_content.html b/main/food/templates/food/partials/edit_content.html index 73a092a..afac6e4 100644 --- a/main/food/templates/food/partials/edit_content.html +++ b/main/food/templates/food/partials/edit_content.html @@ -9,6 +9,21 @@
{% csrf_token %} {% include 'food/partials/portion_fields.html' %}
{{ form.quantity.label_tag }}{{ form.quantity }}{{ form.quantity.errors }}Multiplies the selected portion. For example, 2 means two of that portion.
+
+ Correct nutrition for this entry +

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.

+
{{ form.edit_nutrition.label_tag }}{{ form.edit_nutrition }}{{ form.edit_nutrition.errors }}Without this selection, nutrition scales automatically when the portion amount changes.
+
+
{{ form.calories_kcal.label_tag }}{{ form.calories_kcal }}{{ form.calories_kcal.errors }}
+
{{ form.carbohydrates_g.label_tag }}{{ form.carbohydrates_g }}{{ form.carbohydrates_g.errors }}
+
{{ form.protein_g.label_tag }}{{ form.protein_g }}{{ form.protein_g.errors }}
+
{{ form.fat_g.label_tag }}{{ form.fat_g }}{{ form.fat_g.errors }}
+
{{ form.fibre_g.label_tag }}{{ form.fibre_g }}{{ form.fibre_g.errors }}
+
{{ form.sugars_g.label_tag }}{{ form.sugars_g }}{{ form.sugars_g.errors }}
+
{{ form.salt_g.label_tag }}{{ form.salt_g }}{{ form.salt_g.errors }}
+
+
+ {% if product %}

Edit saved product nutrition for future logs

{% endif %}
{% csrf_token %}
diff --git a/main/food/templates/food/partials/inventory_product_actions.html b/main/food/templates/food/partials/inventory_product_actions.html index 2072200..3dc8a12 100644 --- a/main/food/templates/food/partials/inventory_product_actions.html +++ b/main/food/templates/food/partials/inventory_product_actions.html @@ -1,5 +1,5 @@ diff --git a/main/food/templates/food/partials/product_nutrition_fields.html b/main/food/templates/food/partials/product_nutrition_fields.html new file mode 100644 index 0000000..1a4f68f --- /dev/null +++ b/main/food/templates/food/partials/product_nutrition_fields.html @@ -0,0 +1,21 @@ +
+ Nutrition +

Enter values for the basis amount and unit below. Leave a value blank when it is unknown; zero means the label says zero.

+
{{ form.basis_amount.label_tag }}{{ form.basis_amount }}{{ form.basis_amount.errors }}
+
{{ form.base_unit.label_tag }}{{ form.base_unit }}{{ form.base_unit.errors }}{% if form.base_unit.field.disabled %}The nutrition unit is fixed for an existing product.{% endif %}
+
+
{{ form.energy_kcal_100.label_tag }}{{ form.energy_kcal_100 }}{{ form.energy_kcal_100.errors }}
+
{{ form.carbohydrates_100.label_tag }}{{ form.carbohydrates_100 }}{{ form.carbohydrates_100.errors }}
+
{{ form.protein_100.label_tag }}{{ form.protein_100 }}{{ form.protein_100.errors }}
+
{{ form.fat_100.label_tag }}{{ form.fat_100 }}{{ form.fat_100.errors }}
+
+
+ More nutrients +
+
{{ form.saturated_fat_100.label_tag }}{{ form.saturated_fat_100 }}{{ form.saturated_fat_100.errors }}
+
{{ form.fibre_100.label_tag }}{{ form.fibre_100 }}{{ form.fibre_100.errors }}
+
{{ form.sugars_100.label_tag }}{{ form.sugars_100 }}{{ form.sugars_100.errors }}
+
{{ form.salt_100.label_tag }}{{ form.salt_100 }}{{ form.salt_100.errors }}
+
+
+
diff --git a/main/food/templates/food/product_edit.html b/main/food/templates/food/product_edit.html new file mode 100644 index 0000000..d3e9f2b --- /dev/null +++ b/main/food/templates/food/product_edit.html @@ -0,0 +1,5 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}Edit product nutrition · Tasknest{% endblock %} +{% block content %}
← Kitchen Inventory

Edit {{ product.product_name }}

Changes to this product affect future food logs. Existing Food Diary entries keep their recorded nutrition; edit an entry to correct its own values.

{% if product.source == 'openfoodfacts' %}

Imported from Open Food Facts{% if product.raw_data.manual_nutrition_override %}; nutrition has been corrected manually{% endif %}.

{% endif %}
{% csrf_token %}{{ form.non_field_errors }} +{% for field in form %}{% if field.name == 'product_name' or field.name == 'brand' or field.name == 'barcode' %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endif %}{% endfor %} +{% include 'food/partials/product_nutrition_fields.html' %}

Kitchen Inventory · Log this food

{% endblock %} diff --git a/main/food/test_nutrition_ui.py b/main/food/test_nutrition_ui.py new file mode 100644 index 0000000..a9d1600 --- /dev/null +++ b/main/food/test_nutrition_ui.py @@ -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() diff --git a/main/food/urls.py b/main/food/urls.py index 6f9e8c3..602a7fd 100644 --- a/main/food/urls.py +++ b/main/food/urls.py @@ -32,5 +32,6 @@ urlpatterns = [ path('attachments//file/', views.attachment_file, name='attachment-file'), path('product//favourite/', views.toggle_favourite, name='toggle-favourite'), path('product//hydration/', views.product_hydration, name='product-hydration'), + path('product//edit/', views.edit_product, name='product-edit'), path('export//', views.export_csv, name='export'), ] diff --git a/main/food/views.py b/main/food/views.py index 62ea42b..6267d2d 100644 --- a/main/food/views.py +++ b/main/food/views.py @@ -421,7 +421,11 @@ def edit_entry(request, pk): updated = form.save(commit=False) factor = updated.amount / original_amount 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(): sync_food_hydration(updated) updated.full_clean() @@ -441,6 +445,24 @@ def edit_entry(request, pk): '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 @require_POST def delete_entry(request, pk): diff --git a/main/groceries/__init__.py b/main/groceries/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main/groceries/api.py b/main/groceries/api.py new file mode 100644 index 0000000..6fdd563 --- /dev/null +++ b/main/groceries/api.py @@ -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) diff --git a/main/groceries/migrations/0001_initial.py b/main/groceries/migrations/0001_initial.py new file mode 100644 index 0000000..a222bf1 --- /dev/null +++ b/main/groceries/migrations/0001_initial.py @@ -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'), + ), + ] diff --git a/main/groceries/migrations/0002_groceryrecipedemand.py b/main/groceries/migrations/0002_groceryrecipedemand.py new file mode 100644 index 0000000..67d5de0 --- /dev/null +++ b/main/groceries/migrations/0002_groceryrecipedemand.py @@ -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')], + }, + ), + ] diff --git a/main/groceries/migrations/0003_groceryitem_inventory_transfer_and_more.py b/main/groceries/migrations/0003_groceryitem_inventory_transfer_and_more.py new file mode 100644 index 0000000..10d3f66 --- /dev/null +++ b/main/groceries/migrations/0003_groceryitem_inventory_transfer_and_more.py @@ -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), + ), + ] diff --git a/main/groceries/migrations/__init__.py b/main/groceries/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main/groceries/models.py b/main/groceries/models.py new file mode 100644 index 0000000..aa1c33d --- /dev/null +++ b/main/groceries/models.py @@ -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')] diff --git a/main/groceries/services.py b/main/groceries/services.py new file mode 100644 index 0000000..4e48c52 --- /dev/null +++ b/main/groceries/services.py @@ -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 diff --git a/main/groceries/static/groceries/groceries.css b/main/groceries/static/groceries/groceries.css new file mode 100644 index 0000000..8e4e80b --- /dev/null +++ b/main/groceries/static/groceries/groceries.css @@ -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}} diff --git a/main/groceries/templates/groceries/index.html b/main/groceries/templates/groceries/index.html new file mode 100644 index 0000000..4b05449 --- /dev/null +++ b/main/groceries/templates/groceries/index.html @@ -0,0 +1,8 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}Groceries · Tasknest{% endblock %} +{% block content %} + +

Food

Grocery list

Plan what to buy. Marking an item purchased does not add it to Kitchen Inventory.

+

Quick add

{% csrf_token %}
+

Items

{% csrf_token %}
{% include 'groceries/partials/list.html' %}
+{% endblock %} diff --git a/main/groceries/templates/groceries/inventory_transfer.html b/main/groceries/templates/groceries/inventory_transfer.html new file mode 100644 index 0000000..53e075f --- /dev/null +++ b/main/groceries/templates/groceries/inventory_transfer.html @@ -0,0 +1,3 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}Add to Kitchen Inventory · Tasknest{% endblock %} +{% block content %}
← Grocery list

Add purchased item to inventory

{{ item.name }} · {{ item.quantity|floatformat:-3 }} {{ item.unit }}

{% if item.inventory_transferred_at %}

This item was already added to Kitchen Inventory.

{% else %}

Confirm the product and location. This creates stock only when you submit this form.

{% csrf_token %}
{% endif %}
{% endblock %} diff --git a/main/groceries/templates/groceries/partials/list.html b/main/groceries/templates/groceries/partials/list.html new file mode 100644 index 0000000..350c654 --- /dev/null +++ b/main/groceries/templates/groceries/partials/list.html @@ -0,0 +1,2 @@ +{% regroup items by category as categories %} +{% for group in categories %}

{{ group.grouper|default:'Other' }}

    {% for item in group.list %}
  • {% csrf_token %}
    {{ item.name }}{{ item.quantity|floatformat:-3 }} {{ item.unit }}{% if item.notes %}{{ item.notes }}{% endif %}{% for source in item.sources.all %}From {{ source.recipe.title }}{% endfor %}{% if item.status == "purchased" %}{% if item.inventory_transferred_at %}Added to inventory{% else %}Add to inventory{% endif %}{% endif %}
    Edit
    {% csrf_token %}
    {% csrf_token %}
  • {% endfor %}
{% empty %}

No grocery items here yet.

{% endfor %} diff --git a/main/groceries/templates/groceries/recipe_preview.html b/main/groceries/templates/groceries/recipe_preview.html new file mode 100644 index 0000000..d9580a4 --- /dev/null +++ b/main/groceries/templates/groceries/recipe_preview.html @@ -0,0 +1,3 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}Review groceries · {{ recipe.title }}{% endblock %} +{% block content %}
← Back to recipe

Review groceries for {{ recipe.title }}

Only known, compatible stock is subtracted. Items already on your grocery list are counted.

{% if error %}

{{ error }}

{% endif %}{% if plan %}
{% for line in plan.lines %}{% if line.ingredient.substitutions.exists %}{% endif %}{% endfor %}

Missing ingredients

    {% for line in plan.lines %}
  • {{ line.name }} · {{ line.quantity|floatformat:-3 }} {{ line.unit }} needed · {{ line.stock_used|floatformat:-3 }} in stock · {{ line.list_used|floatformat:-3 }} listed · {{ line.missing|floatformat:-3 }} to add{% if line.uncertain %}Review: {{ line.reason }}{% endif %}{% if line.source %}From {{ line.source }}{% endif %}
  • {% empty %}
  • No ingredients to add.
  • {% endfor %}
{% csrf_token %}{% if plan.include_optional %}{% endif %}{% for key,value in plan.substitutions.items %}{% endfor %}{% if plan.requires_review %}{% endif %}
{% endif %}
{% endblock %} diff --git a/main/groceries/tests.py b/main/groceries/tests.py new file mode 100644 index 0000000..d266164 --- /dev/null +++ b/main/groceries/tests.py @@ -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) diff --git a/main/groceries/urls.py b/main/groceries/urls.py new file mode 100644 index 0000000..efc07a4 --- /dev/null +++ b/main/groceries/urls.py @@ -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('/update/', views.update, name='update'), + path('/delete/', views.delete, name='delete'), + path('/inventory/', views.inventory_transfer, name='inventory-transfer'), + path('recipe//preview/', views.preview_recipe, name='recipe-preview'), + path('recipe//add/', views.add_recipe, name='recipe-add'), +] diff --git a/main/groceries/views.py b/main/groceries/views.py new file mode 100644 index 0000000..b4f5663 --- /dev/null +++ b/main/groceries/views.py @@ -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) diff --git a/main/mcp_server/server.py b/main/mcp_server/server.py index 8d5e838..038e11f 100644 --- a/main/mcp_server/server.py +++ b/main/mcp_server/server.py @@ -196,6 +196,25 @@ class RecipeAnalysisInput(BaseModel): 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): score: int = Field(ge=0, le=10) 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, idempotency_key=None, token=None, return_validation=False): 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: headers['Idempotency-Key'] = idempotency_key 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) except (httpx2.RequestError, TimeoutError): 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 return_validation and response.status_code == 400: return response.json() @@ -619,6 +647,48 @@ def create_server() -> MCPServer: return await api_request('GET', 'recipes/cook-later/', 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.') async def recipe_create(recipe: RecipeInput, idempotency_key: str | None = None) -> dict[str, Any]: key = _key(idempotency_key) diff --git a/main/mcp_server/tests.py b/main/mcp_server/tests.py index 720f2fd..52e5753 100644 --- a/main/mcp_server/tests.py +++ b/main/mcp_server/tests.py @@ -99,6 +99,7 @@ class McpHttpTests(LiveServerTestCase): async with Client(streamable_http_client(self.mcp_url, http_client=http)) as client: return await operation(client) + @override_settings(SECURE_SSL_REDIRECT=True) def test_authentication_and_scope_boundaries(self): async def check(): 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) asyncio.run(self._client(secret, check)) + @override_settings(SECURE_SSL_REDIRECT=True) def test_food_inventory_tools_and_user_isolation(self): previous_day = localdate_for_user(self.a) - timedelta(days=1) FoodLogEntry.objects.create(user=self.a, date=previous_day, meal='breakfast', @@ -304,7 +306,7 @@ class McpHttpTests(LiveServerTestCase): async def check(client): 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', 'inventory_import_groceries', 'recipe_cook_later_add', 'recipe_cook_later_remove', 'recipe_cook_later_list'} <= names) diff --git a/main/planner/context_processors.py b/main/planner/context_processors.py index 6bd4348..6ef5e87 100644 --- a/main/planner/context_processors.py +++ b/main/planner/context_processors.py @@ -1,14 +1,43 @@ """Template context shared by Tasknest pages.""" from .models import UserSettings +from django.urls import reverse def appearance(request): """Expose the signed-in user’s saved colour preference without creating settings.""" user = getattr(request, "user", None) if user is not None and user.is_authenticated: - saved_appearance = ( - UserSettings.objects.filter(user=user).values_list("appearance", flat=True).first() - ) - return {"user_appearance": saved_appearance or UserSettings.Appearance.LIGHT} - return {"user_appearance": UserSettings.Appearance.LIGHT} + profile = UserSettings.objects.filter(user=user).values('appearance', 'is_demo').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'))), + ) + groups = [] + 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} diff --git a/main/planner/csrf.py b/main/planner/csrf.py new file mode 100644 index 0000000..9b3b972 --- /dev/null +++ b/main/planner/csrf.py @@ -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) diff --git a/main/planner/demo_policy.py b/main/planner/demo_policy.py new file mode 100644 index 0000000..4a5bfaf --- /dev/null +++ b/main/planner/demo_policy.py @@ -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()) diff --git a/main/planner/management/commands/seed_demo.py b/main/planner/management/commands/seed_demo.py index a81ed8b..84a307f 100644 --- a/main/planner/management/commands/seed_demo.py +++ b/main/planner/management/commands/seed_demo.py @@ -3,11 +3,19 @@ from datetime import datetime, time, timedelta from decimal import Decimal 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.utils import timezone from food.models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit +from food.models import (FoodLogAttachment, InventoryCategory, InventoryConsumption, + InventoryLocation, KitchenInventoryItem, PersonalAccessToken) +from recipes.models import Recipe, RecipeSelection, CookLater, RecipeUse, RecipeCookingRun +from stress.models import StressEntry +from dreams.models import DreamEntry +from oauth2_provider.models import get_access_token_model, get_grant_model, get_refresh_token_model from planner.models import ( BowelHealthCheckIn, @@ -95,19 +103,29 @@ class Command(BaseCommand): def add_arguments(self, parser): 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 def handle(self, *args, **options): username = options['username'] - password = options['password'] + password = options['password'] or settings.TASKNEST_DEMO_PASSWORD user_model = get_user_model() - user, created = user_model.objects.get_or_create(username=username) - user.set_password(password) + user = user_model.objects.filter(username=username).first() + created = user is None + if created and not password: + raise CommandError('Set TASKNEST_DEMO_PASSWORD before creating a demo account.') + if created: + user = user_model(username=username) + if not created and (user.is_staff or user.is_superuser or + UserSettings.objects.filter(user=user).exclude(is_demo=True).exists()): + raise CommandError('Refusing to reset an account that is not marked as a demo account.') + if password: + user.set_password(password) user.is_active = True user.save() profile, _ = UserSettings.objects.get_or_create(user=user) + profile.is_demo = True profile.time_zone = DEFAULT_TIME_ZONE profile.appearance = UserSettings.Appearance.LIGHT profile.latitude = '52.367600' @@ -115,6 +133,11 @@ class Command(BaseCommand): profile.onboarding_enabled = False profile.onboarding_step = 0 profile.daily_water_goal_ml = 2000 + profile.auto_count_food_drinks = True + profile.include_liquid_foods = False + profile.show_hydration_breakdown = True + profile.allow_manual_hydration_adjustments = True + profile.hydration_beverage_rules = {} profile.daily_calorie_goal = 2000 profile.carbohydrate_goal_g = Decimal('250.0') profile.protein_goal_g = Decimal('100.0') @@ -136,13 +159,43 @@ class Command(BaseCommand): WaterIntakeEntry.objects.filter(user=user).delete() ToothBrushing.objects.filter(user=user).delete() BowelHealthCheckIn.objects.filter(user=user).delete() + for attachment in FoodLogAttachment.objects.filter(log_entry__user=user): + storage, name = attachment.image.storage, attachment.image.name + transaction.on_commit(lambda storage=storage, name=name: storage.delete(name)) FoodLogEntry.objects.filter(user=user).delete() + StressEntry.objects.filter(user=user).delete() + DreamEntry.objects.filter(user=user).delete() + RecipeSelection.objects.filter(user=user).delete() + CookLater.objects.filter(user=user).delete() + RecipeUse.objects.filter(user=user).delete() + RecipeCookingRun.objects.filter(user=user).delete() + demo_drafts = Recipe.objects.filter(owner=user, status=Recipe.Status.DRAFT) + for recipe in demo_drafts.exclude(photo=''): + storage, name = recipe.photo.storage, recipe.photo.name + transaction.on_commit(lambda storage=storage, name=name: storage.delete(name)) + demo_drafts.delete() + KitchenInventoryItem.objects.filter(user=user).delete() + InventoryConsumption.objects.filter(user=user).delete() + InventoryLocation.objects.filter(user=user).delete() + InventoryCategory.objects.filter(user=user).delete() + get_refresh_token_model().objects.filter(user=user).delete() + get_grant_model().objects.filter(user=user).delete() + get_access_token_model().objects.filter(user=user).delete() + PersonalAccessToken.objects.filter(user=user).delete() + for session in Session.objects.filter(expire_date__gt=timezone.now()).iterator(): + if session.get_decoded().get('_auth_user_id') == str(user.pk): + session.delete() FoodFavourite.objects.filter(user=user).delete() FoodPortion.objects.filter(user=user).delete() FoodProduct.objects.filter(owner=user).delete() now = timezone.now() today = localdate_for_user(user, now) + StressEntry.objects.create(user=user, score=3, daily_date=today, + note='A manageable day after a short walk.') + DreamEntry.objects.create(user=user, wake_up_date=today - timedelta(days=1), + title='The quiet garden', + narrative='I walked through a calm garden and found a familiar path home.') ToothBrushing.objects.create(user=user, date=today - timedelta(days=1), morning=True, evening=True) ToothBrushing.objects.create(user=user, date=today, morning=True, evening=False) diff --git a/main/planner/middleware_demo.py b/main/planner/middleware_demo.py new file mode 100644 index 0000000..065d430 --- /dev/null +++ b/main/planner/middleware_demo.py @@ -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) diff --git a/main/planner/migrations/0022_usersettings_is_demo.py b/main/planner/migrations/0022_usersettings_is_demo.py new file mode 100644 index 0000000..10e82db --- /dev/null +++ b/main/planner/migrations/0022_usersettings_is_demo.py @@ -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), + ] diff --git a/main/planner/models.py b/main/planner/models.py index e39f796..651f25a 100644 --- a/main/planner/models.py +++ b/main/planner/models.py @@ -105,6 +105,7 @@ class UserSettings(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='planner_settings' ) + is_demo = models.BooleanField(default=False, editable=False) latitude = models.DecimalField( max_digits=9, decimal_places=6, blank=True, null=True, validators=[MinValueValidator(-90), MaxValueValidator(90)], diff --git a/main/planner/services/weather.py b/main/planner/services/weather.py index 7c62603..341e047 100644 --- a/main/planner/services/weather.py +++ b/main/planner/services/weather.py @@ -15,6 +15,7 @@ from urllib.request import urlopen from django.core.cache import cache from planner.models import Task, UserSettings +from planner.demo_policy import is_demo_user OPEN_METEO_URL = 'https://api.open-meteo.com/v1/forecast' 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: """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() if settings is None or settings.latitude is None or settings.longitude is None: return None diff --git a/main/planner/static/planner/nav_spacing.css b/main/planner/static/planner/nav_spacing.css index e042371..f3451ec 100644 --- a/main/planner/static/planner/nav_spacing.css +++ b/main/planner/static/planner/nav_spacing.css @@ -1,4 +1,29 @@ -/* Keep the expanded navigation inside tablet widths as sections are added. */ -@media (min-width: 701px) and (max-width: 960px) { - .primary-nav { gap: 8px; font-size: .82rem; } +/* One navigation tree is rendered for both the desktop header and mobile drawer. */ +.primary-nav{gap:clamp(8px,1.3vw,20px);white-space:nowrap} +.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}} diff --git a/main/planner/static/planner/navigation.js b/main/planner/static/planner/navigation.js new file mode 100644 index 0000000..18ad08f --- /dev/null +++ b/main/planner/static/planner/navigation.js @@ -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(); +}); diff --git a/main/planner/templates/planner/base.html b/main/planner/templates/planner/base.html index 083e3f6..a2ab932 100644 --- a/main/planner/templates/planner/base.html +++ b/main/planner/templates/planner/base.html @@ -7,7 +7,8 @@ {% block title %}Tasknest{% endblock %} {% vite_asset 'src/main.js' %} - + +
@@ -21,14 +22,12 @@

Start cooking

+

Add missing ingredients to groceries

{% if analysis_error %}{% endif %}

Ingredients

    {% for line in analysis.lines %}
  • {{ line.name }}{% if line.source %}From {{ line.source }}{% endif %}{% if line.ingredient.preparation_note %}{{ line.ingredient.preparation_note }}{% endif %}{{ line.status|capfirst }}{% if line.reason %}: {{ line.reason }}{% endif %}{{ line.quantity|floatformat:-3 }} {{ line.unit }}{% if line.optional %}Optional{% if not analysis.include_optional %} · excluded{% endif %}{% endif %}
  • {% empty %}
  • No ingredients added yet.
  • {% endfor %}
diff --git a/main/requirements.txt b/main/requirements.txt index da99de8..dd68e12 100644 --- a/main/requirements.txt +++ b/main/requirements.txt @@ -1,6 +1,7 @@ asarPy==1.0.1 asgiref==3.12.1 Django==6.1.1 +whitenoise==6.12.0 Pillow==12.3.0 django-oauth-toolkit==3.4.1 mcp==2.3.0 diff --git a/main/tasksnest/settings.py b/main/tasksnest/settings.py index fe30e8c..87200b5 100644 --- a/main/tasksnest/settings.py +++ b/main/tasksnest/settings.py @@ -12,25 +12,42 @@ https://docs.djangoproject.com/en/6.1/ref/settings/ import os from pathlib import Path +from django.core.exceptions import ImproperlyConfigured # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent -# Quick-start development settings - unsuitable for production -# See https://docs.djangoproject.com/en/6.1/howto/deployment/checklist/ +def _local_env(name): + 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 = True +DEBUG = _local_env('DJANGO_DEBUG').lower() in {'1', 'true', 'yes'} +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"] SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") CSRF_TRUSTED_ORIGINS = [ "https://tasksnest.jorendegraaf.eu", ] +CSRF_FAILURE_VIEW = 'planner.csrf.csrf_failure' # Application definition @@ -45,6 +62,7 @@ INSTALLED_APPS = [ 'planner', 'food.apps.FoodConfig', 'recipes', + 'groceries', 'stress', 'dreams', ] @@ -55,10 +73,12 @@ RECIPE_MATCH_DEMO_USERNAME = os.environ.get('TASKNEST_RECIPE_MATCH_DEMO_USERNAME MIDDLEWARE = [ 'food.api_middleware.ApiErrorMiddleware', 'django.middleware.security.SecurityMiddleware', + 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'planner.middleware_demo.DemoAccountPolicyMiddleware', 'planner.middleware.UserTimezoneMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', @@ -87,6 +107,8 @@ OAUTH2_PROVIDER = { 'DCR_ENABLED': False, 'OAUTH2_GRANT_TYPES_SUPPORTED': ['authorization_code', 'refresh_token'], '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_PKCE_METHOD': True, 'COMPLIANT_BCP_RFC9700_PKCE_REQUIRED': True, @@ -109,6 +131,7 @@ TEMPLATES = [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', '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/ STATIC_URL = 'static/' +STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / 'private_media' # Vite writes built assets and its manifest here. Use the Vite server only when diff --git a/main/tasksnest/urls.py b/main/tasksnest/urls.py index a66c2f4..634e40e 100644 --- a/main/tasksnest/urls.py +++ b/main/tasksnest/urls.py @@ -27,6 +27,7 @@ urlpatterns = [ path('admin/', admin.site.urls), path('food/', include('food.urls', namespace='food')), path('recipes/', include('recipes.urls', namespace='recipes')), + path('groceries/', include('groceries.urls', namespace='groceries')), path('stress/', include('stress.urls', namespace='stress')), path('dreams/', include('dreams.urls', namespace='dreams')), path('', include('planner.urls')),