diff --git a/.playwright-mcp/fibre-after-empty-1280.png b/.playwright-mcp/fibre-after-empty-1280.png new file mode 100644 index 0000000..25c312a Binary files /dev/null and b/.playwright-mcp/fibre-after-empty-1280.png differ diff --git a/.playwright-mcp/fibre-after-empty-320.png b/.playwright-mcp/fibre-after-empty-320.png new file mode 100644 index 0000000..eebd09b Binary files /dev/null and b/.playwright-mcp/fibre-after-empty-320.png differ diff --git a/.playwright-mcp/fibre-after-empty-375.png b/.playwright-mcp/fibre-after-empty-375.png new file mode 100644 index 0000000..14f27a9 Binary files /dev/null and b/.playwright-mcp/fibre-after-empty-375.png differ diff --git a/.playwright-mcp/fibre-after-empty-390.png b/.playwright-mcp/fibre-after-empty-390.png new file mode 100644 index 0000000..4e7d21e Binary files /dev/null and b/.playwright-mcp/fibre-after-empty-390.png differ diff --git a/.playwright-mcp/fibre-after-empty-430.png b/.playwright-mcp/fibre-after-empty-430.png new file mode 100644 index 0000000..c188fc5 Binary files /dev/null and b/.playwright-mcp/fibre-after-empty-430.png differ diff --git a/.playwright-mcp/fibre-after-empty-768.png b/.playwright-mcp/fibre-after-empty-768.png new file mode 100644 index 0000000..560c667 Binary files /dev/null and b/.playwright-mcp/fibre-after-empty-768.png differ diff --git a/.playwright-mcp/fibre-before-1280.png b/.playwright-mcp/fibre-before-1280.png new file mode 100644 index 0000000..f45c6c8 Binary files /dev/null and b/.playwright-mcp/fibre-before-1280.png differ diff --git a/.playwright-mcp/fibre-before-320.png b/.playwright-mcp/fibre-before-320.png new file mode 100644 index 0000000..5d504a4 Binary files /dev/null and b/.playwright-mcp/fibre-before-320.png differ diff --git a/.playwright-mcp/fibre-before-375.png b/.playwright-mcp/fibre-before-375.png new file mode 100644 index 0000000..1184d32 Binary files /dev/null and b/.playwright-mcp/fibre-before-375.png differ diff --git a/.playwright-mcp/fibre-before-390.png b/.playwright-mcp/fibre-before-390.png new file mode 100644 index 0000000..e025a5f Binary files /dev/null and b/.playwright-mcp/fibre-before-390.png differ diff --git a/.playwright-mcp/fibre-before-430.png b/.playwright-mcp/fibre-before-430.png new file mode 100644 index 0000000..9f799c9 Binary files /dev/null and b/.playwright-mcp/fibre-before-430.png differ diff --git a/.playwright-mcp/fibre-before-768.png b/.playwright-mcp/fibre-before-768.png new file mode 100644 index 0000000..8068cac Binary files /dev/null and b/.playwright-mcp/fibre-before-768.png differ diff --git a/.playwright-mcp/nutrient-help-desktop.png b/.playwright-mcp/nutrient-help-desktop.png new file mode 100644 index 0000000..e0f6afa Binary files /dev/null and b/.playwright-mcp/nutrient-help-desktop.png differ diff --git a/.playwright-mcp/nutrient-help-mobile.png b/.playwright-mcp/nutrient-help-mobile.png new file mode 100644 index 0000000..695d0b0 Binary files /dev/null and b/.playwright-mcp/nutrient-help-mobile.png differ diff --git a/.playwright-mcp/page-2026-10-09T18-44-39-014Z.yml b/.playwright-mcp/page-2026-10-09T18-44-39-014Z.yml new file mode 100644 index 0000000..c796bdd --- /dev/null +++ b/.playwright-mcp/page-2026-10-09T18-44-39-014Z.yml @@ -0,0 +1,96 @@ +- generic [ref=f4e2]: + - banner [ref=f4e3]: + - generic [ref=f4e4]: + - button "Open menu" [ref=f4e5] [cursor=pointer] + - link "Tasknest home" [ref=f4e10] [cursor=pointer]: + - /url: / + - generic [aria-hidden] [ref=f4e11]: ✓ + - generic [ref=f4e12]: tasknest + - main [ref=f4e13]: + - generic [ref=f4e15]: + - generic [ref=f4e16]: + - generic [ref=f4e17]: + - paragraph [ref=f4e18]: Food diary + - heading "Friday 9 October 2026" [level=1] [ref=f4e19] + - navigation "Diary dates" [ref=f4e20]: + - link "Previous day" [ref=f4e21] [cursor=pointer]: + - /url: /food/?date=2026-10-08 + - text: ← + - link "Today" [ref=f4e22] [cursor=pointer]: + - /url: /food/ + - link "Next day" [ref=f4e23] [cursor=pointer]: + - /url: /food/?date=2026-10-10 + - text: → + - generic [ref=f4e24]: + - generic [ref=f4e25]: + - region [ref=f4e26]: + - generic [ref=f4e27]: + - generic [ref=f4e28]: + - heading "Breakfast" [level=2] [ref=f4e29] + - paragraph [ref=f4e30]: 0 kcal + - link "Add food to Breakfast" [ref=f4e31] [cursor=pointer]: + - /url: /food/add/?date=2026-10-09&meal=breakfast + - text: + + - paragraph [ref=f4e32]: Nothing logged yet. + - region [ref=f4e33]: + - generic [ref=f4e34]: + - generic [ref=f4e35]: + - heading "Lunch" [level=2] [ref=f4e36] + - paragraph [ref=f4e37]: 0 kcal + - link "Add food to Lunch" [ref=f4e38] [cursor=pointer]: + - /url: /food/add/?date=2026-10-09&meal=lunch + - text: + + - paragraph [ref=f4e39]: Nothing logged yet. + - region [ref=f4e40]: + - generic [ref=f4e41]: + - generic [ref=f4e42]: + - heading "Dinner" [level=2] [ref=f4e43] + - paragraph [ref=f4e44]: 0 kcal + - link "Add food to Dinner" [ref=f4e45] [cursor=pointer]: + - /url: /food/add/?date=2026-10-09&meal=dinner + - text: + + - paragraph [ref=f4e46]: Nothing logged yet. + - region [ref=f4e47]: + - generic [ref=f4e48]: + - generic [ref=f4e49]: + - heading "Snacks" [level=2] [ref=f4e50] + - paragraph [ref=f4e51]: 0 kcal + - link "Add food to Snacks" [ref=f4e52] [cursor=pointer]: + - /url: /food/add/?date=2026-10-09&meal=snacks + - text: + + - paragraph [ref=f4e53]: Nothing logged yet. + - link "Add food" [ref=f4e54] [cursor=pointer]: + - /url: /food/add/?date=2026-10-09 + - complementary "Daily nutrition summary" [ref=f4e55]: + - generic [ref=f4e56]: + - heading "Calories" [level=2] [ref=f4e57] + - paragraph [ref=f4e58]: 2000 kcal remaining + - progressbar "Calories eaten" [ref=f4e59] + - paragraph [ref=f4e60]: "0 kcal eaten · Goal: 2000 kcal" + - region "Macronutrients" [ref=f4e61]: + - article [ref=f4e62]: + - generic [ref=f4e63]: 0% + - generic [ref=f4e65]: + - heading "Carbohydrates" [level=3] [ref=f4e66] + - paragraph [ref=f4e67]: 0.0 g eaten + - paragraph [ref=f4e68]: 250.0 g remaining + - article [ref=f4e69]: + - generic [ref=f4e70]: 0% + - generic [ref=f4e72]: + - heading "Protein" [level=3] [ref=f4e73] + - paragraph [ref=f4e74]: 0.0 g eaten + - paragraph [ref=f4e75]: 100.0 g remaining + - article [ref=f4e76]: + - generic [ref=f4e77]: 0% + - generic [ref=f4e79]: + - heading "Fat" [level=3] [ref=f4e80] + - paragraph [ref=f4e81]: 0.0 g eaten + - paragraph [ref=f4e82]: 70.0 g remaining + - region [ref=f4e83]: + - heading "Export food diary" [level=2] [ref=f4e84] + - paragraph [ref=f4e85]: Download your logged entries as CSV. + - generic [ref=f4e86]: + - link "Current week CSV" [ref=f4e87] [cursor=pointer]: + - /url: /food/export/week/ + - link "Current month CSV" [ref=f4e88] [cursor=pointer]: + - /url: /food/export/month/ \ No newline at end of file diff --git a/.playwright-mcp/page-2026-10-09T18-50-43-264Z.yml b/.playwright-mcp/page-2026-10-09T18-50-43-264Z.yml new file mode 100644 index 0000000..0fef8e2 --- /dev/null +++ b/.playwright-mcp/page-2026-10-09T18-50-43-264Z.yml @@ -0,0 +1,175 @@ +- generic [ref=f5e2]: + - banner [ref=f5e3]: + - generic [ref=f5e4]: + - link "Tasknest home" [ref=f5e5] [cursor=pointer]: + - /url: / + - generic [aria-hidden] [ref=f5e6]: ✓ + - generic [ref=f5e7]: tasknest + - navigation "Primary navigation" [ref=f5e8]: + - link "My tasks" [ref=f5e9] [cursor=pointer]: + - /url: / + - link "Daily planner" [ref=f5e10] [cursor=pointer]: + - /url: /daily/ + - link "Health" [ref=f5e11] [cursor=pointer]: + - /url: /health/ + - link "Food" [ref=f5e12] [cursor=pointer]: + - /url: /food/ + - link "Kitchen Inventory" [ref=f5e13] [cursor=pointer]: + - /url: /food/inventory/ + - link "Settings" [ref=f5e14] [cursor=pointer]: + - /url: /settings/ + - button "Use light mode" [ref=f5e16] [cursor=pointer]: + - generic [aria-hidden] [ref=f5e17]: ☀ + - button "Log out" [ref=f5e20] [cursor=pointer] + - main [ref=f5e21]: + - generic [ref=f5e23]: + - generic [ref=f5e24]: + - generic [ref=f5e25]: + - paragraph [ref=f5e26]: Food diary + - heading "Saturday 3 October 2026" [level=1] [ref=f5e27] + - navigation "Diary dates" [ref=f5e28]: + - link "Previous day" [ref=f5e29] [cursor=pointer]: + - /url: /food/?date=2026-10-02 + - text: ← + - link "Today" [ref=f5e30] [cursor=pointer]: + - /url: /food/ + - link "Next day" [ref=f5e31] [cursor=pointer]: + - /url: /food/?date=2026-10-04 + - text: → + - generic [ref=f5e32]: + - generic [ref=f5e33]: + - region [ref=f5e34]: + - generic [ref=f5e35]: + - generic [ref=f5e36]: + - heading "Breakfast" [level=2] [ref=f5e37] + - paragraph [ref=f5e38]: 472 kcal + - link "Add food to Breakfast" [ref=f5e39] [cursor=pointer]: + - /url: /food/add/?date=2026-10-03&meal=breakfast + - text: + + - list [ref=f5e40]: + - listitem [ref=f5e41]: + - generic [ref=f5e43]: + - strong [ref=f5e44]: Greek yoghurt + - generic [ref=f5e45]: Demo dairy + - generic [ref=f5e46]: 183 kcal · My bowl (250 g) + - link "Edit Greek yoghurt" [ref=f5e47] [cursor=pointer]: + - /url: /food/log/13/ + - text: Edit + - listitem [ref=f5e48]: + - generic [ref=f5e50]: + - strong [ref=f5e51]: Banana + - generic [ref=f5e52]: 107 kcal · (120 g) + - link "Edit Banana" [ref=f5e53] [cursor=pointer]: + - /url: /food/log/14/ + - text: Edit + - listitem [ref=f5e54]: + - generic [ref=f5e56]: + - strong [ref=f5e57]: Greek yoghurt + - generic [ref=f5e58]: Demo dairy + - generic [ref=f5e59]: 183 kcal · My bowl (250 g) + - link "Edit Greek yoghurt" [ref=f5e60] [cursor=pointer]: + - /url: /food/log/23/ + - text: Edit + - region [ref=f5e61]: + - generic [ref=f5e62]: + - generic [ref=f5e63]: + - heading "Lunch" [level=2] [ref=f5e64] + - paragraph [ref=f5e65]: 338 kcal + - link "Add food to Lunch" [ref=f5e66] [cursor=pointer]: + - /url: /food/add/?date=2026-10-03&meal=lunch + - text: + + - list [ref=f5e67]: + - listitem [ref=f5e68]: + - generic [ref=f5e70]: + - strong [ref=f5e71]: Wholegrain sandwich + - generic [ref=f5e72]: Demo bakery + - generic [ref=f5e73]: 250 kcal · (100 g) + - link "Edit Wholegrain sandwich" [ref=f5e74] [cursor=pointer]: + - /url: /food/log/15/ + - text: Edit + - listitem [ref=f5e75]: + - generic [ref=f5e77]: + - strong [ref=f5e78]: Tomato soup + - generic [ref=f5e79]: Home made + - generic [ref=f5e80]: 88 kcal · One mug (250 ml) + - link "Edit Tomato soup" [ref=f5e81] [cursor=pointer]: + - /url: /food/log/16/ + - text: Edit + - region [ref=f5e82]: + - generic [ref=f5e83]: + - generic [ref=f5e84]: + - heading "Dinner" [level=2] [ref=f5e85] + - paragraph [ref=f5e86]: 261 kcal + - link "Add food to Dinner" [ref=f5e87] [cursor=pointer]: + - /url: /food/add/?date=2026-10-03&meal=dinner + - text: + + - list [ref=f5e88]: + - listitem [ref=f5e89]: + - generic [ref=f5e91]: + - strong [ref=f5e92]: Pasta with vegetables + - generic [ref=f5e93]: Home made + - generic [ref=f5e94]: 261 kcal · (180 g) + - link "Edit Pasta with vegetables" [ref=f5e95] [cursor=pointer]: + - /url: /food/log/17/ + - text: Edit + - region [ref=f5e96]: + - generic [ref=f5e97]: + - generic [ref=f5e98]: + - heading "Snacks" [level=2] [ref=f5e99] + - paragraph [ref=f5e100]: 174 kcal + - link "Add food to Snacks" [ref=f5e101] [cursor=pointer]: + - /url: /food/add/?date=2026-10-03&meal=snacks + - text: + + - list [ref=f5e102]: + - listitem [ref=f5e103]: + - generic [ref=f5e105]: + - strong [ref=f5e106]: Almonds + - generic [ref=f5e107]: 174 kcal · (30 g) + - link "Edit Almonds" [ref=f5e108] [cursor=pointer]: + - /url: /food/log/18/ + - text: Edit + - link "Add food" [ref=f5e109] [cursor=pointer]: + - /url: /food/add/?date=2026-10-03 + - complementary "Daily nutrition summary" [ref=f5e110]: + - generic [ref=f5e111]: + - heading "Calories" [level=2] [ref=f5e112] + - paragraph [ref=f5e113]: 756 kcal remaining + - progressbar "Calories eaten" [ref=f5e114] + - paragraph [ref=f5e116]: "1244 kcal eaten · Goal: 2000 kcal" + - region "Daily nutrition goals" [ref=f5e117]: + - article [ref=f5e118]: + - progressbar "Protein progress" [ref=f5e119]: + - generic [aria-hidden] [ref=f5e120]: 69% + - generic [ref=f5e121]: + - heading "Protein" [level=3] [ref=f5e122] + - paragraph [ref=f5e123]: 69.6 g eaten · 100.0 g goal + - paragraph [ref=f5e124]: 30.4 g remaining + - article [ref=f5e125]: + - progressbar "Carbohydrates progress" [ref=f5e126]: + - generic [aria-hidden] [ref=f5e127]: 58% + - generic [ref=f5e128]: + - heading "Carbohydrates" [level=3] [ref=f5e129] + - paragraph [ref=f5e130]: 146.3 g eaten · 250.0 g goal + - paragraph [ref=f5e131]: 103.7 g remaining + - article [ref=f5e132]: + - progressbar "Fat progress" [ref=f5e133]: + - generic [aria-hidden] [ref=f5e134]: 53% + - generic [ref=f5e135]: + - heading "Fat" [level=3] [ref=f5e136] + - paragraph [ref=f5e137]: 37.3 g eaten · 70.0 g goal + - paragraph [ref=f5e138]: 32.7 g remaining + - article [ref=f5e139]: + - progressbar "Fibre progress" [ref=f5e140]: + - generic [aria-hidden] [ref=f5e141]: 43% + - generic [ref=f5e142]: + - heading "Fibre" [level=3] [ref=f5e143] + - paragraph [ref=f5e144]: At least 17.4 g · 40.0 g goal + - paragraph [ref=f5e145]: Some entries unknown + - region [ref=f5e146]: + - heading "Export food diary" [level=2] [ref=f5e147] + - paragraph [ref=f5e148]: Download your logged entries as CSV. + - generic [ref=f5e149]: + - link "Current week CSV" [ref=f5e150] [cursor=pointer]: + - /url: /food/export/week/ + - link "Current month CSV" [ref=f5e151] [cursor=pointer]: + - /url: /food/export/month/ \ No newline at end of file diff --git a/.playwright-mcp/page-2026-10-09T18-53-30-761Z.yml b/.playwright-mcp/page-2026-10-09T18-53-30-761Z.yml new file mode 100644 index 0000000..52bd810 --- /dev/null +++ b/.playwright-mcp/page-2026-10-09T18-53-30-761Z.yml @@ -0,0 +1,121 @@ +- generic [ref=f7e2]: + - banner [ref=f7e3]: + - generic [ref=f7e4]: + - link "Tasknest home" [ref=f7e5] [cursor=pointer]: + - /url: / + - generic [aria-hidden] [ref=f7e6]: ✓ + - generic [ref=f7e7]: tasknest + - navigation "Primary navigation" [ref=f7e8]: + - link "My tasks" [ref=f7e9] [cursor=pointer]: + - /url: / + - link "Daily planner" [ref=f7e10] [cursor=pointer]: + - /url: /daily/ + - link "Health" [ref=f7e11] [cursor=pointer]: + - /url: /health/ + - link "Food" [ref=f7e12] [cursor=pointer]: + - /url: /food/ + - link "Kitchen Inventory" [ref=f7e13] [cursor=pointer]: + - /url: /food/inventory/ + - link "Settings" [ref=f7e14] [cursor=pointer]: + - /url: /settings/ + - button "Use light mode" [ref=f7e16] [cursor=pointer]: + - generic [aria-hidden] [ref=f7e17]: ☀ + - button "Log out" [ref=f7e20] [cursor=pointer] + - main [ref=f7e21]: + - generic [ref=f7e23]: + - generic [ref=f7e24]: + - generic [ref=f7e25]: + - paragraph [ref=f7e26]: Food diary + - heading "Friday 9 October 2026" [level=1] [ref=f7e27] + - navigation "Diary dates" [ref=f7e28]: + - link "Previous day" [ref=f7e29] [cursor=pointer]: + - /url: /food/?date=2026-10-08 + - text: ← + - link "Today" [ref=f7e30] [cursor=pointer]: + - /url: /food/ + - link "Next day" [ref=f7e31] [cursor=pointer]: + - /url: /food/?date=2026-10-10 + - text: → + - generic [ref=f7e32]: + - generic [ref=f7e33]: + - region [ref=f7e34]: + - generic [ref=f7e35]: + - generic [ref=f7e36]: + - heading "Breakfast" [level=2] [ref=f7e37] + - paragraph [ref=f7e38]: 0 kcal + - link "Add food to Breakfast" [ref=f7e39] [cursor=pointer]: + - /url: /food/add/?date=2026-10-09&meal=breakfast + - text: + + - paragraph [ref=f7e40]: Nothing logged yet. + - region [ref=f7e41]: + - generic [ref=f7e42]: + - generic [ref=f7e43]: + - heading "Lunch" [level=2] [ref=f7e44] + - paragraph [ref=f7e45]: 0 kcal + - link "Add food to Lunch" [ref=f7e46] [cursor=pointer]: + - /url: /food/add/?date=2026-10-09&meal=lunch + - text: + + - paragraph [ref=f7e47]: Nothing logged yet. + - region [ref=f7e48]: + - generic [ref=f7e49]: + - generic [ref=f7e50]: + - heading "Dinner" [level=2] [ref=f7e51] + - paragraph [ref=f7e52]: 0 kcal + - link "Add food to Dinner" [ref=f7e53] [cursor=pointer]: + - /url: /food/add/?date=2026-10-09&meal=dinner + - text: + + - paragraph [ref=f7e54]: Nothing logged yet. + - region [ref=f7e55]: + - generic [ref=f7e56]: + - generic [ref=f7e57]: + - heading "Snacks" [level=2] [ref=f7e58] + - paragraph [ref=f7e59]: 0 kcal + - link "Add food to Snacks" [ref=f7e60] [cursor=pointer]: + - /url: /food/add/?date=2026-10-09&meal=snacks + - text: + + - paragraph [ref=f7e61]: Nothing logged yet. + - link "Add food" [ref=f7e62] [cursor=pointer]: + - /url: /food/add/?date=2026-10-09 + - complementary "Daily nutrition summary" [ref=f7e63]: + - generic [ref=f7e64]: + - heading "Calories" [level=2] [ref=f7e65] + - paragraph [ref=f7e66]: 2000 kcal remaining + - progressbar "Calories eaten" [ref=f7e67] + - paragraph [ref=f7e68]: "0 kcal eaten · Goal: 2000 kcal" + - region "Daily nutrition goals" [ref=f7e69]: + - article [ref=f7e70]: + - progressbar "Protein progress" [ref=f7e71]: + - generic [aria-hidden] [ref=f7e72]: 0% + - generic [ref=f7e73]: + - heading "Protein" [level=3] [ref=f7e74] + - paragraph [ref=f7e75]: 0.0 g eaten · 100.0 g goal + - paragraph [ref=f7e76]: 100.0 g remaining + - article [ref=f7e77]: + - progressbar "Carbohydrates progress" [ref=f7e78]: + - generic [aria-hidden] [ref=f7e79]: 0% + - generic [ref=f7e80]: + - heading "Carbohydrates" [level=3] [ref=f7e81] + - paragraph [ref=f7e82]: 0.0 g eaten · 250.0 g goal + - paragraph [ref=f7e83]: 250.0 g remaining + - article [ref=f7e84]: + - progressbar "Fat progress" [ref=f7e85]: + - generic [aria-hidden] [ref=f7e86]: 0% + - generic [ref=f7e87]: + - heading "Fat" [level=3] [ref=f7e88] + - paragraph [ref=f7e89]: 0.0 g eaten · 70.0 g goal + - paragraph [ref=f7e90]: 70.0 g remaining + - article [ref=f7e91]: + - progressbar "Fibre progress" [ref=f7e92]: + - generic [aria-hidden] [ref=f7e93]: 0% + - generic [ref=f7e94]: + - heading "Fibre" [level=3] [ref=f7e95] + - paragraph [ref=f7e96]: 0.0 g eaten · 40.0 g goal + - paragraph [ref=f7e97]: 40.0 g remaining + - region [ref=f7e98]: + - heading "Export food diary" [level=2] [ref=f7e99] + - paragraph [ref=f7e100]: Download your logged entries as CSV. + - generic [ref=f7e101]: + - link "Current week CSV" [ref=f7e102] [cursor=pointer]: + - /url: /food/export/week/ + - link "Current month CSV" [ref=f7e103] [cursor=pointer]: + - /url: /food/export/month/ \ No newline at end of file diff --git a/.playwright-mcp/page-2026-10-11T13-17-53-175Z.yml b/.playwright-mcp/page-2026-10-11T13-17-53-175Z.yml new file mode 100644 index 0000000..b6d5627 --- /dev/null +++ b/.playwright-mcp/page-2026-10-11T13-17-53-175Z.yml @@ -0,0 +1,3 @@ +- generic [active] [ref=e1]: + - heading "Bad Request (400)" [level=1] [ref=e2] + - paragraph \ No newline at end of file diff --git a/.playwright-mcp/page-2026-10-11T13-17-58-296Z.yml b/.playwright-mcp/page-2026-10-11T13-17-58-296Z.yml new file mode 100644 index 0000000..584b3fc --- /dev/null +++ b/.playwright-mcp/page-2026-10-11T13-17-58-296Z.yml @@ -0,0 +1,3 @@ +- generic [active] [ref=f1e1]: + - heading "Bad Request (400)" [level=1] [ref=f1e2] + - paragraph \ No newline at end of file diff --git a/.playwright-mcp/page-2026-10-11T13-18-22-714Z.yml b/.playwright-mcp/page-2026-10-11T13-18-22-714Z.yml new file mode 100644 index 0000000..363dbee --- /dev/null +++ b/.playwright-mcp/page-2026-10-11T13-18-22-714Z.yml @@ -0,0 +1,129 @@ +- generic [ref=f2e2]: + - banner [ref=f2e3]: + - generic [ref=f2e4]: + - link "Tasknest home" [ref=f2e5] [cursor=pointer]: + - /url: / + - generic [aria-hidden] [ref=f2e6]: ✓ + - generic [ref=f2e7]: tasknest + - navigation "Primary navigation" [ref=f2e8]: + - link "My tasks" [ref=f2e9] [cursor=pointer]: + - /url: / + - link "Daily planner" [ref=f2e10] [cursor=pointer]: + - /url: /daily/ + - link "Health" [ref=f2e11] [cursor=pointer]: + - /url: /health/ + - link "Food" [ref=f2e12] [cursor=pointer]: + - /url: /food/ + - link "Kitchen Inventory" [ref=f2e13] [cursor=pointer]: + - /url: /food/inventory/ + - link "Settings" [ref=f2e14] [cursor=pointer]: + - /url: /settings/ + - button "Use light mode" [ref=f2e16] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e17]: ☀ + - button "Log out" [ref=f2e20] [cursor=pointer] + - main [ref=f2e21]: + - generic [ref=f2e23]: + - generic [ref=f2e24]: + - generic [ref=f2e25]: + - paragraph [ref=f2e26]: Food diary + - heading "Sunday 11 October 2026" [level=1] [ref=f2e27] + - navigation "Diary dates" [ref=f2e28]: + - link "Previous day" [ref=f2e29] [cursor=pointer]: + - /url: /food/?date=2026-10-10 + - text: ← + - link "Today" [ref=f2e30] [cursor=pointer]: + - /url: /food/ + - link "Next day" [ref=f2e31] [cursor=pointer]: + - /url: /food/?date=2026-10-12 + - text: → + - generic [ref=f2e32]: + - generic [ref=f2e33]: + - region [ref=f2e34]: + - generic [ref=f2e35]: + - generic [ref=f2e36]: + - heading "Breakfast" [level=2] [ref=f2e37] + - paragraph [ref=f2e38]: 0 kcal + - link "Add food to Breakfast" [ref=f2e39] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=breakfast + - text: + + - paragraph [ref=f2e40]: Nothing logged yet. + - region [ref=f2e41]: + - generic [ref=f2e42]: + - generic [ref=f2e43]: + - heading "Lunch" [level=2] [ref=f2e44] + - paragraph [ref=f2e45]: 0 kcal + - link "Add food to Lunch" [ref=f2e46] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=lunch + - text: + + - paragraph [ref=f2e47]: Nothing logged yet. + - region [ref=f2e48]: + - generic [ref=f2e49]: + - generic [ref=f2e50]: + - heading "Dinner" [level=2] [ref=f2e51] + - paragraph [ref=f2e52]: 0 kcal + - link "Add food to Dinner" [ref=f2e53] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=dinner + - text: + + - paragraph [ref=f2e54]: Nothing logged yet. + - region [ref=f2e55]: + - generic [ref=f2e56]: + - generic [ref=f2e57]: + - heading "Snacks" [level=2] [ref=f2e58] + - paragraph [ref=f2e59]: 0 kcal + - link "Add food to Snacks" [ref=f2e60] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=snacks + - text: + + - paragraph [ref=f2e61]: Nothing logged yet. + - link "Add food" [ref=f2e62] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11 + - complementary "Daily nutrition summary" [ref=f2e63]: + - generic [ref=f2e64]: + - heading "Calories" [level=2] [ref=f2e65] + - paragraph [ref=f2e66]: 2000 kcal remaining + - progressbar "Calories eaten" [ref=f2e67] + - paragraph [ref=f2e68]: "0 kcal eaten · Goal: 2000 kcal" + - region "Daily nutrition goals" [ref=f2e69]: + - article [ref=f2e70]: + - button "About Protein" [ref=f2e71] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e72]: "?" + - progressbar "Protein progress" [ref=f2e73]: + - generic [aria-hidden] [ref=f2e74]: 0% + - generic [ref=f2e75]: + - heading "Protein" [level=3] [ref=f2e76] + - paragraph [ref=f2e77]: 0.0 g eaten · 100.0 g goal + - paragraph [ref=f2e78]: 100.0 g remaining + - article [ref=f2e79]: + - button "About Carbohydrates" [ref=f2e80] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e81]: "?" + - progressbar "Carbohydrates progress" [ref=f2e82]: + - generic [aria-hidden] [ref=f2e83]: 0% + - generic [ref=f2e84]: + - heading "Carbohydrates" [level=3] [ref=f2e85] + - paragraph [ref=f2e86]: 0.0 g eaten · 250.0 g goal + - paragraph [ref=f2e87]: 250.0 g remaining + - article [ref=f2e88]: + - button "About Fat" [ref=f2e89] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e90]: "?" + - progressbar "Fat progress" [ref=f2e91]: + - generic [aria-hidden] [ref=f2e92]: 0% + - generic [ref=f2e93]: + - heading "Fat" [level=3] [ref=f2e94] + - paragraph [ref=f2e95]: 0.0 g eaten · 70.0 g goal + - paragraph [ref=f2e96]: 70.0 g remaining + - article [ref=f2e97]: + - button "About Fibre" [ref=f2e98] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e99]: "?" + - progressbar "Fibre progress" [ref=f2e100]: + - generic [aria-hidden] [ref=f2e101]: 0% + - generic [ref=f2e102]: + - heading "Fibre" [level=3] [ref=f2e103] + - paragraph [ref=f2e104]: 0.0 g eaten · 40.0 g goal + - paragraph [ref=f2e105]: 40.0 g remaining + - region [ref=f2e106]: + - heading "Export food diary" [level=2] [ref=f2e107] + - paragraph [ref=f2e108]: Download your logged entries as CSV. + - generic [ref=f2e109]: + - link "Current week CSV" [ref=f2e110] [cursor=pointer]: + - /url: /food/export/week/ + - link "Current month CSV" [ref=f2e111] [cursor=pointer]: + - /url: /food/export/month/ \ No newline at end of file diff --git a/.playwright-mcp/page-2026-10-11T13-18-30-712Z.yml b/.playwright-mcp/page-2026-10-11T13-18-30-712Z.yml new file mode 100644 index 0000000..8b8d6ec --- /dev/null +++ b/.playwright-mcp/page-2026-10-11T13-18-30-712Z.yml @@ -0,0 +1,153 @@ +- generic [ref=f2e2]: + - banner [ref=f2e3]: + - generic [ref=f2e4]: + - link "Tasknest home" [ref=f2e5] [cursor=pointer]: + - /url: / + - generic [aria-hidden] [ref=f2e6]: ✓ + - generic [ref=f2e7]: tasknest + - navigation "Primary navigation" [ref=f2e8]: + - link "My tasks" [ref=f2e9] [cursor=pointer]: + - /url: / + - link "Daily planner" [ref=f2e10] [cursor=pointer]: + - /url: /daily/ + - link "Health" [ref=f2e11] [cursor=pointer]: + - /url: /health/ + - link "Food" [ref=f2e12] [cursor=pointer]: + - /url: /food/ + - link "Kitchen Inventory" [ref=f2e13] [cursor=pointer]: + - /url: /food/inventory/ + - link "Settings" [ref=f2e14] [cursor=pointer]: + - /url: /settings/ + - button "Use light mode" [ref=f2e16] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e17]: ☀ + - button "Log out" [ref=f2e20] [cursor=pointer] + - main [ref=f2e21]: + - generic [ref=f2e23]: + - generic [ref=f2e24]: + - generic [ref=f2e25]: + - paragraph [ref=f2e26]: Food diary + - heading "Sunday 11 October 2026" [level=1] [ref=f2e27] + - navigation "Diary dates" [ref=f2e28]: + - link "Previous day" [ref=f2e29] [cursor=pointer]: + - /url: /food/?date=2026-10-10 + - text: ← + - link "Today" [ref=f2e30] [cursor=pointer]: + - /url: /food/ + - link "Next day" [ref=f2e31] [cursor=pointer]: + - /url: /food/?date=2026-10-12 + - text: → + - generic [ref=f2e32]: + - generic [ref=f2e33]: + - region [ref=f2e34]: + - generic [ref=f2e35]: + - generic [ref=f2e36]: + - heading "Breakfast" [level=2] [ref=f2e37] + - paragraph [ref=f2e38]: 0 kcal + - link "Add food to Breakfast" [ref=f2e39] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=breakfast + - text: + + - paragraph [ref=f2e40]: Nothing logged yet. + - region [ref=f2e41]: + - generic [ref=f2e42]: + - generic [ref=f2e43]: + - heading "Lunch" [level=2] [ref=f2e44] + - paragraph [ref=f2e45]: 0 kcal + - link "Add food to Lunch" [ref=f2e46] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=lunch + - text: + + - paragraph [ref=f2e47]: Nothing logged yet. + - region [ref=f2e48]: + - generic [ref=f2e49]: + - generic [ref=f2e50]: + - heading "Dinner" [level=2] [ref=f2e51] + - paragraph [ref=f2e52]: 0 kcal + - link "Add food to Dinner" [ref=f2e53] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=dinner + - text: + + - paragraph [ref=f2e54]: Nothing logged yet. + - region [ref=f2e55]: + - generic [ref=f2e56]: + - generic [ref=f2e57]: + - heading "Snacks" [level=2] [ref=f2e58] + - paragraph [ref=f2e59]: 0 kcal + - link "Add food to Snacks" [ref=f2e60] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=snacks + - text: + + - paragraph [ref=f2e61]: Nothing logged yet. + - link "Add food" [ref=f2e62] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11 + - complementary "Daily nutrition summary" [ref=f2e63]: + - generic [ref=f2e64]: + - heading "Calories" [level=2] [ref=f2e65] + - paragraph [ref=f2e66]: 2000 kcal remaining + - progressbar "Calories eaten" [ref=f2e67] + - paragraph [ref=f2e68]: "0 kcal eaten · Goal: 2000 kcal" + - region "Daily nutrition goals" [ref=f2e69]: + - article [ref=f2e70]: + - button "About Protein" [expanded] [ref=f2e71] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e72]: "?" + - progressbar "Protein progress" [ref=f2e73]: + - generic [aria-hidden] [ref=f2e74]: 0% + - generic [ref=f2e75]: + - heading "Protein" [level=3] [ref=f2e76] + - paragraph [ref=f2e77]: 0.0 g eaten · 100.0 g goal + - paragraph [ref=f2e78]: 100.0 g remaining + - region [ref=f2e112]: + - generic [ref=f2e113]: + - heading "Protein" [level=4] [ref=f2e114] + - button "Close" [active] [ref=f2e115] [cursor=pointer]: × + - paragraph [ref=f2e116]: Helps build and maintain muscles and supports recovery. + - strong [ref=f2e117]: "Good sources:" + - list [ref=f2e118]: + - listitem [ref=f2e119]: + - strong [ref=f2e120]: Poultry + - text: ": chicken breast, turkey" + - listitem [ref=f2e121]: + - strong [ref=f2e122]: Fish + - text: ": tuna, salmon, cod" + - listitem [ref=f2e123]: + - strong [ref=f2e124]: Eggs + - listitem [ref=f2e125]: + - strong [ref=f2e126]: Dairy + - text: ": skyr, quark (kwark), cottage cheese" + - listitem [ref=f2e127]: + - strong [ref=f2e128]: Legumes + - text: ": lentils, chickpeas, beans" + - listitem [ref=f2e129]: + - strong [ref=f2e130]: Plant proteins + - text: ": tofu, tempeh, edamame" + - article [ref=f2e79]: + - button "About Carbohydrates" [ref=f2e80] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e81]: "?" + - progressbar "Carbohydrates progress" [ref=f2e82]: + - generic [aria-hidden] [ref=f2e83]: 0% + - generic [ref=f2e84]: + - heading "Carbohydrates" [level=3] [ref=f2e85] + - paragraph [ref=f2e86]: 0.0 g eaten · 250.0 g goal + - paragraph [ref=f2e87]: 250.0 g remaining + - article [ref=f2e88]: + - button "About Fat" [ref=f2e89] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e90]: "?" + - progressbar "Fat progress" [ref=f2e91]: + - generic [aria-hidden] [ref=f2e92]: 0% + - generic [ref=f2e93]: + - heading "Fat" [level=3] [ref=f2e94] + - paragraph [ref=f2e95]: 0.0 g eaten · 70.0 g goal + - paragraph [ref=f2e96]: 70.0 g remaining + - article [ref=f2e97]: + - button "About Fibre" [ref=f2e98] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e99]: "?" + - progressbar "Fibre progress" [ref=f2e100]: + - generic [aria-hidden] [ref=f2e101]: 0% + - generic [ref=f2e102]: + - heading "Fibre" [level=3] [ref=f2e103] + - paragraph [ref=f2e104]: 0.0 g eaten · 40.0 g goal + - paragraph [ref=f2e105]: 40.0 g remaining + - region [ref=f2e106]: + - heading "Export food diary" [level=2] [ref=f2e107] + - paragraph [ref=f2e108]: Download your logged entries as CSV. + - generic [ref=f2e109]: + - link "Current week CSV" [ref=f2e110] [cursor=pointer]: + - /url: /food/export/week/ + - link "Current month CSV" [ref=f2e111] [cursor=pointer]: + - /url: /food/export/month/ \ No newline at end of file diff --git a/.playwright-mcp/page-2026-10-11T13-18-53-502Z.yml b/.playwright-mcp/page-2026-10-11T13-18-53-502Z.yml new file mode 100644 index 0000000..5373deb --- /dev/null +++ b/.playwright-mcp/page-2026-10-11T13-18-53-502Z.yml @@ -0,0 +1,139 @@ +- generic [ref=f2e2]: + - banner [ref=f2e3]: + - generic [ref=f2e4]: + - button "Open menu" [ref=f2e131] [cursor=pointer] + - link "Tasknest home" [ref=f2e5] [cursor=pointer]: + - /url: / + - generic [aria-hidden] [ref=f2e6]: ✓ + - generic [ref=f2e7]: tasknest + - main [ref=f2e21]: + - generic [ref=f2e23]: + - generic [ref=f2e24]: + - generic [ref=f2e25]: + - paragraph [ref=f2e26]: Food diary + - heading "Sunday 11 October 2026" [level=1] [ref=f2e27] + - navigation "Diary dates" [ref=f2e28]: + - link "Previous day" [ref=f2e29] [cursor=pointer]: + - /url: /food/?date=2026-10-10 + - text: ← + - link "Today" [ref=f2e30] [cursor=pointer]: + - /url: /food/ + - link "Next day" [ref=f2e31] [cursor=pointer]: + - /url: /food/?date=2026-10-12 + - text: → + - generic [ref=f2e32]: + - generic [ref=f2e33]: + - region [ref=f2e34]: + - generic [ref=f2e35]: + - generic [ref=f2e36]: + - heading "Breakfast" [level=2] [ref=f2e37] + - paragraph [ref=f2e38]: 0 kcal + - link "Add food to Breakfast" [ref=f2e39] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=breakfast + - text: + + - paragraph [ref=f2e40]: Nothing logged yet. + - region [ref=f2e41]: + - generic [ref=f2e42]: + - generic [ref=f2e43]: + - heading "Lunch" [level=2] [ref=f2e44] + - paragraph [ref=f2e45]: 0 kcal + - link "Add food to Lunch" [ref=f2e46] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=lunch + - text: + + - paragraph [ref=f2e47]: Nothing logged yet. + - region [ref=f2e48]: + - generic [ref=f2e49]: + - generic [ref=f2e50]: + - heading "Dinner" [level=2] [ref=f2e51] + - paragraph [ref=f2e52]: 0 kcal + - link "Add food to Dinner" [ref=f2e53] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=dinner + - text: + + - paragraph [ref=f2e54]: Nothing logged yet. + - region [ref=f2e55]: + - generic [ref=f2e56]: + - generic [ref=f2e57]: + - heading "Snacks" [level=2] [ref=f2e58] + - paragraph [ref=f2e59]: 0 kcal + - link "Add food to Snacks" [ref=f2e60] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=snacks + - text: + + - paragraph [ref=f2e61]: Nothing logged yet. + - link "Add food" [ref=f2e62] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11 + - complementary "Daily nutrition summary" [ref=f2e63]: + - generic [ref=f2e64]: + - heading "Calories" [level=2] [ref=f2e65] + - paragraph [ref=f2e66]: 2000 kcal remaining + - progressbar "Calories eaten" [ref=f2e67] + - paragraph [ref=f2e68]: "0 kcal eaten · Goal: 2000 kcal" + - region "Daily nutrition goals" [ref=f2e69]: + - article [ref=f2e70]: + - button "About Protein" [ref=f2e71] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e72]: "?" + - progressbar "Protein progress" [ref=f2e73]: + - generic [aria-hidden] [ref=f2e74]: 0% + - generic [ref=f2e75]: + - heading "Protein" [level=3] [ref=f2e76] + - paragraph [ref=f2e77]: 0.0 g eaten · 100.0 g goal + - paragraph [ref=f2e78]: 100.0 g remaining + - article [ref=f2e79]: + - button "About Carbohydrates" [ref=f2e80] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e81]: "?" + - progressbar "Carbohydrates progress" [ref=f2e82]: + - generic [aria-hidden] [ref=f2e83]: 0% + - generic [ref=f2e84]: + - heading "Carbohydrates" [level=3] [ref=f2e85] + - paragraph [ref=f2e86]: 0.0 g eaten · 250.0 g goal + - paragraph [ref=f2e87]: 250.0 g remaining + - article [ref=f2e88]: + - button "About Fat" [expanded] [ref=f2e89] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e90]: "?" + - progressbar "Fat progress" [ref=f2e91]: + - generic [aria-hidden] [ref=f2e92]: 0% + - generic [ref=f2e93]: + - heading "Fat" [level=3] [ref=f2e94] + - paragraph [ref=f2e95]: 0.0 g eaten · 70.0 g goal + - paragraph [ref=f2e96]: 70.0 g remaining + - region [ref=f2e136]: + - generic [ref=f2e137]: + - heading "Fat" [level=4] [ref=f2e138] + - button "Close" [active] [ref=f2e139] [cursor=pointer]: × + - paragraph [ref=f2e140]: Supports hormone production, cell function and absorption of certain vitamins. + - strong [ref=f2e141]: "Good sources:" + - list [ref=f2e142]: + - listitem [ref=f2e143]: + - strong [ref=f2e144]: Nuts + - text: ": walnuts, almonds, cashews" + - listitem [ref=f2e145]: + - strong [ref=f2e146]: Seeds + - text: ": chia, flaxseed, sunflower seeds" + - listitem [ref=f2e147]: + - strong [ref=f2e148]: Oils + - text: ": olive oil, rapeseed oil" + - listitem [ref=f2e149]: + - strong [ref=f2e150]: Avocado + - listitem [ref=f2e151]: + - strong [ref=f2e152]: Oily fish + - text: ": salmon, mackerel, sardines" + - listitem [ref=f2e153]: + - strong [ref=f2e154]: Dairy and butter + - text: ": cheese, cream, butter" + - paragraph [ref=f2e155]: Unsaturated fats are generally preferable to saturated fats. + - article [ref=f2e97]: + - button "About Fibre" [ref=f2e98] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e99]: "?" + - progressbar "Fibre progress" [ref=f2e100]: + - generic [aria-hidden] [ref=f2e101]: 0% + - generic [ref=f2e102]: + - heading "Fibre" [level=3] [ref=f2e103] + - paragraph [ref=f2e104]: 0.0 g eaten · 40.0 g goal + - paragraph [ref=f2e105]: 40.0 g remaining + - region [ref=f2e106]: + - heading "Export food diary" [level=2] [ref=f2e107] + - paragraph [ref=f2e108]: Download your logged entries as CSV. + - generic [ref=f2e109]: + - link "Current week CSV" [ref=f2e110] [cursor=pointer]: + - /url: /food/export/week/ + - link "Current month CSV" [ref=f2e111] [cursor=pointer]: + - /url: /food/export/month/ \ No newline at end of file diff --git a/.playwright-mcp/page-2026-10-11T13-19-39-057Z.yml b/.playwright-mcp/page-2026-10-11T13-19-39-057Z.yml new file mode 100644 index 0000000..ce0564e --- /dev/null +++ b/.playwright-mcp/page-2026-10-11T13-19-39-057Z.yml @@ -0,0 +1,140 @@ +- generic [ref=f2e2]: + - banner [ref=f2e3]: + - generic [ref=f2e4]: + - button "Open menu" [ref=f2e131] [cursor=pointer] + - link "Tasknest home" [ref=f2e5] [cursor=pointer]: + - /url: / + - generic [aria-hidden] [ref=f2e6]: ✓ + - generic [ref=f2e7]: tasknest + - main [ref=f2e21]: + - generic [ref=f2e23]: + - generic [ref=f2e24]: + - generic [ref=f2e25]: + - paragraph [ref=f2e26]: Food diary + - heading "Sunday 11 October 2026" [level=1] [ref=f2e27] + - navigation "Diary dates" [ref=f2e28]: + - link "Previous day" [ref=f2e29] [cursor=pointer]: + - /url: /food/?date=2026-10-10 + - text: ← + - link "Today" [ref=f2e30] [cursor=pointer]: + - /url: /food/ + - link "Next day" [ref=f2e31] [cursor=pointer]: + - /url: /food/?date=2026-10-12 + - text: → + - generic [ref=f2e32]: + - generic [ref=f2e33]: + - region [ref=f2e34]: + - generic [ref=f2e35]: + - generic [ref=f2e36]: + - heading "Breakfast" [level=2] [ref=f2e37] + - paragraph [ref=f2e38]: 0 kcal + - link "Add food to Breakfast" [ref=f2e39] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=breakfast + - text: + + - paragraph [ref=f2e40]: Nothing logged yet. + - region [ref=f2e41]: + - generic [ref=f2e42]: + - generic [ref=f2e43]: + - heading "Lunch" [level=2] [ref=f2e44] + - paragraph [ref=f2e45]: 0 kcal + - link "Add food to Lunch" [ref=f2e46] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=lunch + - text: + + - paragraph [ref=f2e47]: Nothing logged yet. + - region [ref=f2e48]: + - generic [ref=f2e49]: + - generic [ref=f2e50]: + - heading "Dinner" [level=2] [ref=f2e51] + - paragraph [ref=f2e52]: 0 kcal + - link "Add food to Dinner" [ref=f2e53] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=dinner + - text: + + - paragraph [ref=f2e54]: Nothing logged yet. + - region [ref=f2e55]: + - generic [ref=f2e56]: + - generic [ref=f2e57]: + - heading "Snacks" [level=2] [ref=f2e58] + - paragraph [ref=f2e59]: 0 kcal + - link "Add food to Snacks" [ref=f2e60] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11&meal=snacks + - text: + + - paragraph [ref=f2e61]: Nothing logged yet. + - link "Add food" [ref=f2e62] [cursor=pointer]: + - /url: /food/add/?date=2026-10-11 + - complementary "Daily nutrition summary" [ref=f2e63]: + - generic [ref=f2e64]: + - heading "Calories" [level=2] [ref=f2e65] + - paragraph [ref=f2e66]: 2000 kcal remaining + - progressbar "Calories eaten" [ref=f2e67] + - paragraph [ref=f2e68]: "0 kcal eaten · Goal: 2000 kcal" + - region "Daily nutrition goals" [ref=f2e69]: + - article [ref=f2e70]: + - button "About Protein" [ref=f2e71] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e72]: "?" + - progressbar "Protein progress" [ref=f2e73]: + - generic [aria-hidden] [ref=f2e74]: 0% + - generic [ref=f2e75]: + - heading "Protein" [level=3] [ref=f2e76] + - paragraph [ref=f2e77]: 0.0 g eaten · 100.0 g goal + - paragraph [ref=f2e78]: 100.0 g remaining + - article [ref=f2e79]: + - button "About Carbohydrates" [ref=f2e80] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e81]: "?" + - progressbar "Carbohydrates progress" [ref=f2e82]: + - generic [aria-hidden] [ref=f2e83]: 0% + - generic [ref=f2e84]: + - heading "Carbohydrates" [level=3] [ref=f2e85] + - paragraph [ref=f2e86]: 0.0 g eaten · 250.0 g goal + - paragraph [ref=f2e87]: 250.0 g remaining + - article [ref=f2e88]: + - button "About Fat" [ref=f2e89] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e90]: "?" + - progressbar "Fat progress" [ref=f2e91]: + - generic [aria-hidden] [ref=f2e92]: 0% + - generic [ref=f2e93]: + - heading "Fat" [level=3] [ref=f2e94] + - paragraph [ref=f2e95]: 0.0 g eaten · 70.0 g goal + - paragraph [ref=f2e96]: 70.0 g remaining + - article [ref=f2e97]: + - button "About Fibre" [expanded] [ref=f2e98] [cursor=pointer]: + - generic [aria-hidden] [ref=f2e99]: "?" + - progressbar "Fibre progress" [ref=f2e100]: + - generic [aria-hidden] [ref=f2e101]: 0% + - generic [ref=f2e102]: + - heading "Fibre" [level=3] [ref=f2e103] + - paragraph [ref=f2e104]: 0.0 g eaten · 40.0 g goal + - paragraph [ref=f2e105]: 40.0 g remaining + - region [ref=f2e156]: + - generic [ref=f2e157]: + - heading "Fibre" [level=4] [ref=f2e158] + - button "Close" [active] [ref=f2e159] [cursor=pointer]: × + - paragraph [ref=f2e160]: Supports digestion, gut health and feelings of fullness. + - strong [ref=f2e161]: "Good sources:" + - list [ref=f2e162]: + - listitem [ref=f2e163]: + - strong [ref=f2e164]: Legumes + - text: ": lentils, kidney beans, chickpeas" + - listitem [ref=f2e165]: + - strong [ref=f2e166]: Whole grains + - text: ": oats, wholemeal bread, barley" + - listitem [ref=f2e167]: + - strong [ref=f2e168]: Seeds + - text: ": chia seeds, flaxseed" + - listitem [ref=f2e169]: + - strong [ref=f2e170]: Fruit + - text: ": raspberries, pears, apples with skin" + - listitem [ref=f2e171]: + - strong [ref=f2e172]: Vegetables + - text: ": broccoli, carrots, Brussels sprouts" + - listitem [ref=f2e173]: + - strong [ref=f2e174]: Nuts + - text: ": almonds, pistachios" + - paragraph [ref=f2e175]: Increase fibre gradually and drink enough fluids. + - region [ref=f2e106]: + - heading "Export food diary" [level=2] [ref=f2e107] + - paragraph [ref=f2e108]: Download your logged entries as CSV. + - generic [ref=f2e109]: + - link "Current week CSV" [ref=f2e110] [cursor=pointer]: + - /url: /food/export/week/ + - link "Current month CSV" [ref=f2e111] [cursor=pointer]: + - /url: /food/export/month/ \ No newline at end of file diff --git a/main/MCP.md b/main/MCP.md index 4c55980..6a38b9d 100644 --- a/main/MCP.md +++ b/main/MCP.md @@ -47,10 +47,37 @@ Before reconnecting ChatGPT, verify the public endpoints: `/.well-known/oauth-pr Open **Settings → API tokens → Connect an AI assistant**. For ChatGPT, use the public MCP URL and OAuth sign-in. ChatGPT must be able to reach the HTTPS URL and its OAuth metadata. For Open WebUI or another bearer-token client, create a personal token with only the scopes needed, choose Streamable HTTP, and enter the same MCP URL and token as a bearer credential. The helper's password field is local to the browser and clears when the page is left; it does not submit the token to the helper. Revoke a token from Settings when it is no longer needed. -The server exposes 12 tools for food diary and inventory reads and changes. `food_attach_image` and `food_log_with_image` accept a ChatGPT file object via `image_file` or base64 data via `image_base64`. Images must be JPEG, PNG, or WebP and at most 5 MiB. A client-supplied file URL must use HTTPS and an allowed host. The API performs image validation and ownership checks. Creation tools accept an `idempotency_key`; reuse the same key and arguments when retrying a request. `food_log_with_image` reports whether the entry was created even if its later attachment upload fails. +The server exposes 16 tools for food diary, product catalogue, and inventory reads and changes. `food_attach_image` and `food_log_with_image` accept a ChatGPT file object via `image_file` or base64 data via `image_base64`. Images must be JPEG, PNG, or WebP and at most 5 MiB. A client-supplied file URL must use HTTPS and an allowed host. The API performs image validation and ownership checks. Creation tools accept an `idempotency_key`; reuse the same key and arguments when retrying a request. `food_log_with_image` reports whether the entry was created even if its later attachment upload fails. `food_get_today` accepts an optional `date` in `YYYY-MM-DD` format. Omit it for the user's local today; pass a calendar date to read another day, such as yesterday. The HTTP API supports the same parameter on `GET /api/v1/food/today/?date=YYYY-MM-DD`. +## Product discovery and grocery photographs + +Image interpretation belongs to the AI client. For a grocery photograph, identify the visible products and any readable barcodes, brands, package sizes, quantities, and storage locations, then send structured data to TaskNest. Unreadable details should remain unknown. + +1. Call `food_lookup_product` with a name or barcode. It searches the authenticated user's products and, by default, Open Food Facts. It never saves search results. Exact barcodes take precedence. `include_open_food_facts: false` limits the lookup to local products. A result has `source`, `confidence`, and either a local `product_id` or an external `external_id`/barcode. +2. When the user selects an external candidate, call `food_import_product` with its barcode. It uses the existing Open Food Facts cache and returns a local `product_id`. An unknown barcode returns a structured failure; the caller can offer manual creation. If data is incomplete, missing nutrition stays unknown. +3. For a product absent from both catalogues, call `food_create_product` with only observed facts. It accepts products without barcodes or nutrition. If a likely duplicate exists, it returns `needs_review` and candidates instead of making a duplicate. +4. Call `inventory_add` with a local `product_id` for one item, or `inventory_import_groceries` for up to 20 groceries. The batch resolves local matches, can import confident Open Food Facts matches, and can create manual products when `create_missing_products` is true. It adds a separate inventory row for each successful item; existing stock is not incremented. A batch idempotency key is required; reuse the same key and payload on retry. + +For ambiguous candidates, ask the user to select one or supply more identifying details. Report batch item statuses individually: `added`, `needs_review`, or `skipped`. A batch can return `partial_success`; successful items remain added while failed items do not leave partial product or inventory writes. A changed payload with the same idempotency key returns a conflict. + +Example tool arguments: + +```json +{"query":"Milbona Volle Chocolademelk","brand":"Milbona","limit":10,"include_open_food_facts":true} +``` + +```json +{"product":{"name":"Volle Chocolademelk","brand":"Milbona","package_quantity":"1000","package_unit":"ml"},"idempotency_key":"product-chocolate-milk-1"} +``` + +```json +{"items":[{"name":"Volle Chocolademelk","brand":"Milbona","quantity":2,"package_quantity":"1000","package_unit":"ml","location":"Koelkast"},{"name":"Crème fraîche","quantity":1,"location":"Koelkast"}],"create_missing_products":true,"idempotency_key":"grocery-import-2026-10-09"} +``` + +Product package size is stored as a numeric amount and unit alongside the existing display text. Inventory `quantity` counts packages. A single opened package can store `remaining_amount`; mixed packages with different remaining contents should be separate inventory rows. The batch import does not infer consumption from a photograph. + The OAuth consent page displays the requested scopes. OAuth access tokens are user-specific API tokens, and token revocation also revokes the matching OAuth grant. For production, use HTTPS and set the issuer and MCP URLs to the actual public hosts before connecting a client. Dynamic client registration is disabled; clients use OAuth Client ID Metadata Documents (CIMD). ChatGPT's document offers both `none` and `private_key_jwt`; this server selects `none` with PKCE because the installed Django OAuth Toolkit supports public CIMD clients only. Clients that do not explicitly offer `none` are rejected. ## Verify diff --git a/main/food/api.py b/main/food/api.py index 1a10611..b24cb69 100644 --- a/main/food/api.py +++ b/main/food/api.py @@ -23,6 +23,9 @@ from .models import (ApiIdempotencyRecord, FoodLogAttachment, FoodLogEntry, Food InventoryCategory, InventoryLocation, KitchenInventoryItem, MealType, PersonalAccessToken, Unit) from .services.logging import apply_product_snapshot +from .services.openfoodfacts import OpenFoodFactsError +from .services.product_resolution import (create_manual, external_matches, import_off, + local_matches, match_data) SCOPES = {'food:read', 'food:write', 'inventory:read', 'inventory:write'} NUTRIENTS = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g') @@ -183,6 +186,8 @@ def _product_data(product): if isinstance(data[name], Decimal): data[name] = str(data[name]) data['id'] = str(product.api_id) + data['package_amount'] = str(product.package_amount) if product.package_amount is not None else None + data['package_unit'] = product.package_unit or None data['portions'] = [{'label': p.label, 'amount': str(p.amount), 'unit': p.unit, 'is_default': p.is_default} for p in product.portions.all()] return data @@ -194,6 +199,7 @@ def _inventory_data(item): 'barcode': item.product.barcode, 'quantity': item.quantity, 'location': item.location.name, 'category': item.category.name if item.category else None, 'notes': item.notes, 'opened': item.opened, + 'remaining_amount': str(item.remaining_amount) if item.remaining_amount is not None else None, 'best_before': item.best_before.isoformat() if item.best_before else None, 'added_at': item.added_at.isoformat(), 'updated_at': item.updated_at.isoformat()} @@ -233,11 +239,17 @@ def today(request): .select_related('product').prefetch_related('attachments')) meals = {meal: [_entry_data(e) for e in entries if e.meal == meal] for meal in MealType.values} totals = {name: str(sum((getattr(e, name) or Decimal('0') for e in entries), Decimal('0'))) - for name in NUTRIENTS} + for name in NUTRIENTS if name != 'fibre_g'} + fibre_values = [entry.fibre_g for entry in entries if entry.fibre_g is not None] + fibre_incomplete = len(fibre_values) != len(entries) + totals['fibre_g'] = str(sum(fibre_values, Decimal('0'))) if fibre_values or not entries else None goals = UserSettings.objects.filter(user=request.api_user).first() goal_data = {name: str(getattr(goals, name)) if goals and getattr(goals, name) is not None else None - for name in ('daily_calorie_goal', 'carbohydrate_goal_g', 'protein_goal_g', 'fat_goal_g')} - return JsonResponse({'date': day.isoformat(), 'meals': meals, 'totals': totals, 'goals': goal_data}) + for name in ('daily_calorie_goal', 'carbohydrate_goal_g', 'protein_goal_g', 'fat_goal_g', 'fibre_goal_g')} + if goals is None: + goal_data['fibre_goal_g'] = '40.0' + return JsonResponse({'date': day.isoformat(), 'meals': meals, 'totals': totals, + 'fibre_incomplete': fibre_incomplete, 'goals': goal_data}) @api_view(None, ('GET',)) @@ -258,6 +270,185 @@ def products(request): return JsonResponse(page) +@api_view('food:read', ('GET',)) +def product_lookup(request): + query = request.GET.get('query', '').strip() + brand = request.GET.get('brand', '').strip() + barcode = request.GET.get('barcode', '').strip() + package_value = request.GET.get('package_quantity') + package_unit = request.GET.get('package_unit', '') + if package_value is not None: + from .services.product_resolution import _amount + package_amount = _amount(package_value, 'package_quantity') + else: + package_amount = None + if (package_amount is None) != (not package_unit) or package_unit not in ('', 'g', 'ml'): + raise ValueError('Package quantity and unit must be supplied together.') + if len(query) > 100 or len(brand) > 255 or (barcode and (not barcode.isascii() or not barcode.isdigit() or len(barcode) > 64)): + raise ValueError('Invalid product search.') + if not query and not barcode: + raise ValueError('Provide a query or barcode.') + try: + limit = int(request.GET.get('limit', 10)) + except ValueError: + raise ValueError('Invalid limit.') from None + if not 1 <= limit <= 20: + raise ValueError('Limit must be between 1 and 20.') + local = local_matches(request.api_user, query, brand, barcode, package_amount, package_unit, + limit, include_partial=True) + if barcode and local and local[0]['confidence'] == 'exact_barcode': + return JsonResponse({'matches': local, 'external_error': None}) + matches = list(local) + external_error = None + if request.GET.get('include_open_food_facts', 'true').lower() in ('true', 'false'): + include_off = request.GET.get('include_open_food_facts', 'true').lower() == 'true' + else: + raise ValueError('include_open_food_facts must be true or false.') + if include_off and len(matches) < limit and not any(m['confidence'] in ('exact_barcode', 'exact_details') for m in matches): + try: + matches.extend(external_matches(request.api_user, query, barcode, brand, package_amount, + package_unit, limit-len(matches))) + except OpenFoodFactsError as exc: + external_error = str(exc) + return JsonResponse({'matches': matches[:limit], 'external_error': external_error}) + + +@api_view('food:write', ('POST',)) +def product_create(request): + data = _json(request) + def create(): + product, status, candidates = create_manual(request.api_user, data) + if status == 'needs_review': + return JsonResponse({'status': status, 'candidates': candidates}) + return JsonResponse({'status': status, 'product_id': str(product.api_id), 'product': _product_data(product)}, + status=201 if status == 'created' else 200) + return _idempotent(request, data, create) + + +@api_view('food:write', ('POST',)) +def product_import(request): + data = _json(request) + if set(data) != {'barcode'}: + raise ValueError('Provide an Open Food Facts barcode.') + def create(): + existing = FoodProduct.objects.filter(owner=request.api_user, barcode=data['barcode']).first() + try: + product = import_off(request.api_user, data['barcode']) + except OpenFoodFactsError as exc: + return error('external_unavailable', str(exc), 503) + if product is None: + return error('external_product_not_found', 'Open Food Facts product not found.', 404) + return JsonResponse({'status': 'reused' if existing else 'imported', + 'product_id': str(product.api_id), 'product': _product_data(product)}, + status=200 if existing else 201) + return _idempotent(request, data, create) + + +@api_view({'POST': 'inventory:write'}, ('POST',)) +def inventory_import_groceries(request): + if 'food:write' not in request.api_token.scopes: + return error('insufficient_scope', 'Missing food:write scope.', 403) + if not request.headers.get('Idempotency-Key'): + return error('idempotency_key_required', 'Provide an Idempotency-Key for a grocery import.') + data = _json(request) + if set(data) - {'items', 'create_missing_products'} or not isinstance(data.get('items'), list) or not 1 <= len(data['items']) <= 20: + raise ValueError('Provide between 1 and 20 grocery items.') + create_missing = data.get('create_missing_products', False) + if not isinstance(create_missing, bool): + raise ValueError('create_missing_products must be a boolean.') + + def create(): + results = [] + for index, raw in enumerate(data['items']): + if not isinstance(raw, dict): + results.append({'index': index, 'status': 'skipped', 'reason': 'Item must be an object.'}) + continue + try: + with transaction.atomic(): + result = _import_one_grocery(request, raw, create_missing) + except (ValueError, ValidationError) as exc: + result = {'status': 'skipped', 'reason': str(exc)} + except OpenFoodFactsError as exc: + result = {'status': 'skipped', 'reason': str(exc)} + results.append({'index': index, 'name': raw.get('name'), **result}) + added = sum(row['status'] == 'added' for row in results) + review = sum(row['status'] == 'needs_review' for row in results) + return JsonResponse({'status': 'success' if added == len(results) else 'partial_success' if added else 'no_items_added', + 'created': added, 'skipped': len(results)-added-review, 'needs_review': review, + 'items': results}) + return _idempotent(request, data, create) + + +def _import_one_grocery(request, raw, create_missing): + allowed = {'product_id', 'name', 'brand', 'barcode', 'quantity', 'package_quantity', 'package_unit', + 'nutrition_per_100', 'location', 'category', 'notes', 'opened', 'best_before'} + if set(raw) - allowed: + raise ValueError('Unknown grocery fields.') + if len(str(raw.get('notes', ''))) > 2000: + raise ValueError('Notes are too long.') + product = None + product_status = 'reused' + if raw.get('product_id'): + if any(raw.get(key) is not None for key in ('name', 'brand', 'barcode', 'package_quantity', + 'package_unit', 'nutrition_per_100')): + raise ValueError('Provide product_id or product details, not both.') + product = FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(raw['product_id'])).first() + if not product: + raise ValueError('Product not found.') + else: + name, brand, barcode = raw.get('name', ''), raw.get('brand', ''), raw.get('barcode', '') + if not isinstance(name, str) or not isinstance(brand, str) or not isinstance(barcode, str) or not name.strip(): + raise ValueError('A product name is required.') + if len(name) > 255 or len(brand) > 255 or len(barcode) > 64: + raise ValueError('Product details are too long.') + amount = raw.get('package_quantity') + if amount is not None: + from .services.product_resolution import _amount + amount = _amount(amount, 'package_quantity') + unit = raw.get('package_unit') or '' + if (amount is None) != (not unit) or unit not in ('', 'g', 'ml'): + raise ValueError('Package quantity and unit must be supplied together.') + local = local_matches(request.api_user, name.strip(), brand.strip(), barcode.strip(), amount, unit) + exact = [m for m in local if m['confidence'] == 'exact_barcode' or + (not barcode and m['confidence'] == 'exact_details')] + if len(exact) == 1: + product = FoodProduct.objects.get(owner=request.api_user, api_id=exact[0]['product_id']) + elif local: + return {'status': 'needs_review', 'reason': 'Multiple or uncertain local matches.', 'candidates': local} + elif barcode: + try: + product = import_off(request.api_user, barcode) + except OpenFoodFactsError: + product = None + if product: + product_status = 'imported' + if product is None and not barcode and name.strip() and brand.strip() and amount is not None: + try: + matches = external_matches(request.api_user, name.strip(), brand=brand.strip(), amount=amount, unit=unit) + except OpenFoodFactsError: + matches = [] + exact = [m for m in matches if m['confidence'] == 'exact_details'] + if len(exact) == 1: + product = import_off(request.api_user, exact[0]['barcode']) + product_status = 'imported' + elif matches: + return {'status': 'needs_review', 'reason': 'Open Food Facts matches require selection.', 'candidates': matches} + if product is None: + if not create_missing: + return {'status': 'needs_review', 'reason': 'No confirmed product. Select or create one.'} + product, product_status, candidates = create_manual(request.api_user, { + key: raw[key] for key in ('name', 'brand', 'barcode', 'package_quantity', 'package_unit', 'nutrition_per_100') if key in raw}) + if product is None: + return {'status': 'needs_review', 'reason': 'Possible duplicate product.', 'candidates': candidates} + inventory_data = {key: raw[key] for key in ('quantity', 'location', 'category', 'notes', 'opened', 'best_before') if key in raw} + inventory_data['product_id'] = str(product.api_id) + item, failure = _save_inventory(request, inventory_data) + if failure: + raise ValueError('Unable to add inventory item.') + return {'status': 'added', 'product_id': str(product.api_id), 'product_status': product_status, + 'inventory_item_id': str(item.api_id), 'quantity_incremented': False} + + def _save_entry(request, data, entry=None): creating = entry is None if creating: @@ -358,7 +549,7 @@ def inventory_list(request): def _save_inventory(request, data, item=None): if item is None: item = KitchenInventoryItem(user=request.api_user) - allowed = {'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'best_before'} + allowed = {'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'best_before', 'remaining_amount'} if set(data) - allowed: raise ValueError('Unknown inventory fields.') if 'product_id' in data: @@ -387,6 +578,9 @@ def _save_inventory(request, data, item=None): if not isinstance(data['opened'], bool): raise ValueError('opened must be a boolean.') item.opened = data['opened'] + if 'remaining_amount' in data: + item.remaining_amount = (_decimal(data['remaining_amount'], 'remaining_amount') + if data['remaining_amount'] is not None else None) if 'best_before' in data: item.best_before = _date(data['best_before'], request.api_user) if data['best_before'] else None if not item.product_id or not item.location_id: diff --git a/main/food/api_schema.py b/main/food/api_schema.py index 819a98f..91c2c25 100644 --- a/main/food/api_schema.py +++ b/main/food/api_schema.py @@ -36,6 +36,17 @@ INVENTORY = {'type': 'object', 'properties': { 'product_id': {'type': 'string', 'format': 'uuid'}, 'quantity': {'type': 'integer', 'minimum': 1}, 'location': {'type': 'string'}, 'category': {'type': 'string'}, 'notes': {'type': 'string'}, 'opened': {'type': 'boolean'}, 'best_before': {'type': ['string', 'null'], 'format': 'date'}, + 'remaining_amount': {'type': ['string', 'null'], 'description': 'Only for one opened package with known size'}, +}} +PRODUCT = {'type': 'object', 'required': ['name'], 'properties': { + 'name': {'type': 'string', 'maxLength': 255}, 'brand': {'type': 'string', 'maxLength': 255}, + 'barcode': {'type': ['string', 'null']}, 'package_quantity': {'type': ['string', 'number', 'null']}, + 'package_unit': {'type': ['string', 'null'], 'enum': ['g', 'ml', None]}, + 'nutrition_per_100': {'type': ['object', 'null']}, 'source': {'type': 'string', 'enum': ['manual']}, +}} +GROCERIES = {'type': 'object', 'required': ['items'], 'properties': { + 'items': {'type': 'array', 'minItems': 1, 'maxItems': 20, 'items': {'type': 'object'}}, + 'create_missing_products': {'type': 'boolean'}, }} UPLOAD = {'type': 'object', 'required': ['image'], 'properties': { 'image': {'type': 'string', 'format': 'binary'}, 'caption': {'type': 'string'}, @@ -51,6 +62,10 @@ def schema(request): 'paths': { '/food/today/': {'get': operation('Food log for an optional local calendar date, defaulting to today', 'food:read')}, '/food/products/': {'get': operation('Search own food products', 'food:read')}, + '/food/products/lookup/': {'get': operation('Look up local and optional Open Food Facts product candidates', 'food:read')}, + '/food/products/create/': {'post': operation('Create or reuse an owned manual food product', 'food:write', PRODUCT)}, + '/food/products/import/': {'post': operation('Import a selected Open Food Facts barcode', 'food:write', + {'type': 'object', 'required': ['barcode'], 'properties': {'barcode': {'type': 'string'}}})}, '/food/log/': {'post': operation('Create food log entry', 'food:write', ENTRY)}, '/food/log/{id}/': { 'get': operation('Read own entry', 'food:read'), @@ -64,6 +79,8 @@ def schema(request): 'get': operation('Search own inventory', 'inventory:read'), 'post': operation('Create inventory item', 'inventory:write', INVENTORY), }, + '/kitchen/import-groceries/': {'post': operation('Import up to 20 groceries with per-item results', + 'inventory:write + food:write', GROCERIES)}, '/kitchen/items/{id}/': { 'get': operation('Read own inventory item', 'inventory:read'), 'patch': operation('Update own inventory item', 'inventory:write', INVENTORY), @@ -82,6 +99,16 @@ def schema(request): 'description': 'Local calendar date; defaults to today in the user time zone.', 'schema': {'type': 'string', 'format': 'date'}, }] + document['paths']['/food/products/lookup/']['get']['parameters'] = [ + {'name': name, 'in': 'query', 'required': False, 'schema': schema} for name, schema in ( + ('query', {'type': 'string'}), ('barcode', {'type': 'string'}), ('brand', {'type': 'string'}), + ('package_quantity', {'type': 'number'}), ('package_unit', {'type': 'string', 'enum': ['g', 'ml']}), + ('limit', {'type': 'integer', 'minimum': 1, 'maximum': 20}), + ('include_open_food_facts', {'type': 'boolean'}))] + document['paths']['/kitchen/import-groceries/']['post']['parameters'] = [{ + 'name': 'Idempotency-Key', 'in': 'header', 'required': True, + 'schema': {'type': 'string', 'maxLength': 128}, + }] document['paths']['/food/attachments/{id}/file/']['get']['responses']['200'] = { 'description': 'Owned image bytes', 'content': {mime: {'schema': {'type': 'string', 'format': 'binary'}} diff --git a/main/food/api_urls.py b/main/food/api_urls.py index 2c1d9ea..0204543 100644 --- a/main/food/api_urls.py +++ b/main/food/api_urls.py @@ -6,11 +6,15 @@ urlpatterns = [ path('schema/', api_schema.schema), path('food/today/', api.today), path('food/products/', api.products), + path('food/products/lookup/', api.product_lookup), + path('food/products/create/', api.product_create), + path('food/products/import/', api.product_import), path('food/log/', api.log_create), path('food/log//', api.log_item), path('food/log//attachments/', api.attachment_create), path('food/attachments//file/', api.attachment_file), path('food/attachments//', api.attachment_delete), path('kitchen/items/', api.inventory_collection), + path('kitchen/import-groceries/', api.inventory_import_groceries), path('kitchen/items//', api.inventory_item), ] diff --git a/main/food/migrations/0005_package_contents.py b/main/food/migrations/0005_package_contents.py new file mode 100644 index 0000000..7c28c52 --- /dev/null +++ b/main/food/migrations/0005_package_contents.py @@ -0,0 +1,36 @@ +import re +from decimal import Decimal + +from django.core.validators import MinValueValidator +from django.db import migrations, models + + +def backfill_package_size(apps, schema_editor): + Product = apps.get_model('food', 'FoodProduct') + for product in Product.objects.filter(package_amount__isnull=True).exclude(package_quantity='').iterator(): + match = re.fullmatch(r'\s*(\d+(?:[.,]\d+)?)\s*(kg|g|ml|l)\s*', product.package_quantity, re.IGNORECASE) + if not match: + continue + amount = Decimal(match.group(1).replace(',', '.')) + unit = match.group(2).lower() + if unit in ('kg', 'l'): + amount *= 1000 + unit = 'g' if unit == 'kg' else 'ml' + if 0 < amount <= Decimal('9999999.999'): + Product.objects.filter(pk=product.pk).update(package_amount=amount, package_unit=unit) + + +class Migration(migrations.Migration): + dependencies = [('food', '0004_foodlogentry_api_id_foodlogentry_created_via_and_more')] + + operations = [ + migrations.AddField(model_name='foodproduct', name='package_amount', + field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, + validators=[MinValueValidator(0.001)])), + migrations.AddField(model_name='foodproduct', name='package_unit', + field=models.CharField(blank=True, choices=[('g', 'g'), ('ml', 'ml')], max_length=2)), + migrations.AddField(model_name='kitcheninventoryitem', name='remaining_amount', + field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, + validators=[MinValueValidator(0)])), + migrations.RunPython(backfill_package_size, migrations.RunPython.noop), + ] diff --git a/main/food/models.py b/main/food/models.py index 9613839..2ea37e6 100644 --- a/main/food/models.py +++ b/main/food/models.py @@ -35,6 +35,8 @@ class FoodProduct(models.Model): brand = models.CharField(max_length=255, blank=True) image_url = models.URLField(blank=True) package_quantity = models.CharField(max_length=100, blank=True) + package_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE) + package_unit = models.CharField(max_length=2, choices=Unit.choices, blank=True) serving_size_text = models.CharField(max_length=100, blank=True) serving_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE) serving_unit = models.CharField(max_length=2, choices=Unit.choices, blank=True) @@ -169,6 +171,7 @@ class KitchenInventoryItem(models.Model): category = models.ForeignKey(InventoryCategory, on_delete=models.PROTECT, null=True, blank=True) notes = models.TextField(blank=True) opened = models.BooleanField(default=False) + remaining_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) best_before = models.DateField(null=True, blank=True) archived_at = models.DateTimeField(null=True, blank=True) added_at = models.DateTimeField(auto_now_add=True) @@ -176,6 +179,10 @@ class KitchenInventoryItem(models.Model): def clean(self): super().clean() + if self.remaining_amount is not None and (not self.product_id or self.quantity != 1 or not self.opened or + not self.product.package_amount or + self.remaining_amount > self.product.package_amount): + raise ValidationError({'remaining_amount': 'Remaining contents require one opened package with a known package size.'}) if self.user_id and self.product_id and self.product.owner_id != self.user_id: raise ValidationError({'product': 'Choose one of your own products.'}) if self.user_id and self.location_id and self.location.user_id != self.user_id: diff --git a/main/food/services/diary.py b/main/food/services/diary.py index 3be01f0..76ea918 100644 --- a/main/food/services/diary.py +++ b/main/food/services/diary.py @@ -5,6 +5,7 @@ from django.utils import timezone from django.utils.dateparse import parse_date from food.models import FoodLogEntry, MealType +from food.services.nutrient_help import nutrient_guidance from planner.models import UserSettings from planner.timezones import localdate_for_user @@ -22,12 +23,15 @@ def selected_date(request): return day -def diary_context(user, day): +def diary_context(user, day, language='en'): goals, _ = UserSettings.objects.get_or_create(user=user) entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product') .prefetch_related('attachments').defer('product__raw_data')) totals = {name: sum((getattr(entry, name) or ZERO for entry in entries), ZERO) for name in ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g')} + fibre_values = [entry.fibre_g for entry in entries if entry.fibre_g is not None] + fibre_incomplete = len(fibre_values) != len(entries) + totals['fibre_g'] = sum(fibre_values, ZERO) if fibre_values or not entries else None meals = [] for key, label in MealType.choices: items = [entry for entry in entries if entry.meal == key] @@ -35,16 +39,22 @@ def diary_context(user, day): 'calories': sum((entry.calories_kcal or ZERO for entry in items), ZERO)}) macros = [] for label, name, goal, color in ( - ('Carbohydrates', 'carbohydrates_g', goals.carbohydrate_goal_g, 'pink'), ('Protein', 'protein_g', goals.protein_goal_g, 'blue'), + ('Carbohydrates', 'carbohydrates_g', goals.carbohydrate_goal_g, 'pink'), ('Fat', 'fat_g', goals.fat_goal_g, 'orange'), + ('Fibre', 'fibre_g', goals.fibre_goal_g, 'green'), ): eaten = totals[name] - macros.append({'label': label, 'eaten': eaten, 'goal': goal, 'remaining': goal - eaten if goal is not None else None, - 'percent': min(100, int(eaten * 100 / goal)) if goal else None, 'color': color}) + incomplete = name == 'fibre_g' and fibre_incomplete + macros.append({'label': label, 'slug': name, 'guidance': nutrient_guidance(name, language), + 'eaten': eaten, 'goal': goal, + 'remaining': goal - eaten if goal is not None and eaten is not None and not incomplete else None, + 'percent': min(100, int(eaten * 100 / goal)) if goal and eaten is not None else None, + 'color': color, 'incomplete': incomplete}) calorie_goal = goals.daily_calorie_goal calories = totals['calories_kcal'] return {'day': day, 'previous_day': day - timedelta(days=1), 'next_day': day + timedelta(days=1), - 'meals': meals, 'totals': totals, 'macros': macros, 'calorie_goal': calorie_goal, + 'meals': meals, 'totals': totals, 'macros': macros, 'help_language': language, + 'calorie_goal': calorie_goal, 'calorie_remaining': Decimal(calorie_goal) - calories if calorie_goal is not None else None, 'calorie_percent': min(100, int(calories * 100 / calorie_goal)) if calorie_goal else 0} diff --git a/main/food/services/nutrient_help.py b/main/food/services/nutrient_help.py new file mode 100644 index 0000000..c5072e1 --- /dev/null +++ b/main/food/services/nutrient_help.py @@ -0,0 +1,76 @@ +"""Static, bilingual guidance for the food diary nutrient cards.""" + +GUIDANCE = { + 'protein_g': { + 'en': ('Helps build and maintain muscles and supports recovery.', [ + ('Poultry', 'chicken breast, turkey'), ('Fish', 'tuna, salmon, cod'), + ('Eggs', ''), ('Dairy', 'skyr, quark (kwark), cottage cheese'), + ('Legumes', 'lentils, chickpeas, beans'), + ('Plant proteins', 'tofu, tempeh, edamame')], ''), + 'nl': ('Helpt spieren opbouwen en behouden en ondersteunt herstel.', [ + ('Gevogelte', 'kipfilet, kalkoen'), ('Vis', 'tonijn, zalm, kabeljauw'), + ('Eieren', ''), ('Zuivel', 'skyr, kwark, hüttenkäse'), + ('Peulvruchten', 'linzen, kikkererwten, bonen'), + ('Plantaardige eiwitten', 'tofu, tempeh, edamame')], ''), + }, + 'carbohydrates_g': { + 'en': ('Provide energy for your brain, muscles and everyday activity.', [ + ('Whole grains', 'oats, wholemeal bread, brown rice'), + ('Starchy foods', 'potatoes, pasta, rice'), + ('Fruit', 'bananas, apples, berries'), + ('Legumes', 'beans, lentils, chickpeas'), + ('Vegetables', 'sweetcorn, peas')], + 'Whole grains and fibre-rich carbohydrate sources are generally preferable to highly refined options.'), + 'nl': ('Geven energie voor je hersenen, spieren en dagelijkse activiteiten.', [ + ('Volkoren granen', 'havermout, volkorenbrood, zilvervliesrijst'), + ('Zetmeelrijke producten', 'aardappelen, pasta, rijst'), + ('Fruit', 'bananen, appels, bessen'), + ('Peulvruchten', 'bonen, linzen, kikkererwten'), + ('Groenten', 'suikermaïs, erwten')], + 'Volkoren en vezelrijke koolhydraatbronnen hebben doorgaans de voorkeur boven sterk geraffineerde producten.'), + }, + 'fat_g': { + 'en': ('Supports hormone production, cell function and absorption of certain vitamins.', [ + ('Nuts', 'walnuts, almonds, cashews'), + ('Seeds', 'chia, flaxseed, sunflower seeds'), + ('Oils', 'olive oil, rapeseed oil'), ('Avocado', ''), + ('Oily fish', 'salmon, mackerel, sardines'), + ('Dairy and butter', 'cheese, cream, butter')], + 'Unsaturated fats are generally preferable to saturated fats.'), + 'nl': ('Ondersteunt de hormoonproductie, celfunctie en opname van bepaalde vitamines.', [ + ('Noten', 'walnoten, amandelen, cashewnoten'), + ('Zaden', 'chiazaad, lijnzaad, zonnebloempitten'), + ('Oliën', 'olijfolie, koolzaadolie'), ('Avocado', ''), + ('Vette vis', 'zalm, makreel, sardines'), + ('Zuivel en boter', 'kaas, room, boter')], + 'Onverzadigde vetten hebben doorgaans de voorkeur boven verzadigde vetten.'), + }, + 'fibre_g': { + 'en': ('Supports digestion, gut health and feelings of fullness.', [ + ('Legumes', 'lentils, kidney beans, chickpeas'), + ('Whole grains', 'oats, wholemeal bread, barley'), + ('Seeds', 'chia seeds, flaxseed'), + ('Fruit', 'raspberries, pears, apples with skin'), + ('Vegetables', 'broccoli, carrots, Brussels sprouts'), + ('Nuts', 'almonds, pistachios')], + 'Increase fibre gradually and drink enough fluids.'), + 'nl': ('Ondersteunt de spijsvertering, darmgezondheid en een vol gevoel.', [ + ('Peulvruchten', 'linzen, kidneybonen, kikkererwten'), + ('Volkoren granen', 'havermout, volkorenbrood, gerst'), + ('Zaden', 'chiazaad, lijnzaad'), + ('Fruit', 'frambozen, peren, appels met schil'), + ('Groenten', 'broccoli, wortels, spruitjes'), + ('Noten', 'amandelen, pistachenoten')], + 'Verhoog je vezelinname geleidelijk en drink voldoende.'), + }, +} + + +def nutrient_guidance(slug, language): + explanation, sources, tip = GUIDANCE[slug]['nl' if language.startswith('nl') else 'en'] + titles = {'protein_g': 'Eiwitten', 'carbohydrates_g': 'Koolhydraten', + 'fat_g': 'Vetten', 'fibre_g': 'Vezels'} + return {'title': titles[slug] if language.startswith('nl') else { + 'protein_g': 'Protein', 'carbohydrates_g': 'Carbohydrates', + 'fat_g': 'Fat', 'fibre_g': 'Fibre'}[slug], + 'explanation': explanation, 'sources': sources, 'tip': tip} diff --git a/main/food/services/openfoodfacts.py b/main/food/services/openfoodfacts.py index b2e15ea..0ff1f8d 100644 --- a/main/food/services/openfoodfacts.py +++ b/main/food/services/openfoodfacts.py @@ -68,6 +68,15 @@ def map_product(data): match = re.search(r'(?i)(\d+(?:[.,]\d+)?)\s*(g|ml)\b', serving_text) serving_amount = _decimal(match.group(1).replace(',', '.')) if match else None serving_unit = match.group(2).lower() if match else '' + package_text = str(data.get('quantity') or '')[:100] + package_match = re.fullmatch(r'\s*(\d+(?:[.,]\d+)?)\s*(kg|g|ml|l)\s*', package_text, re.IGNORECASE) + package_amount = _decimal(package_match.group(1).replace(',', '.')) if package_match else None + package_unit = package_match.group(2).lower() if package_match else '' + if package_amount is not None and package_unit in ('kg', 'l'): + package_amount *= 1000 + package_unit = 'g' if package_unit == 'kg' else 'ml' + if package_amount is not None and package_amount <= 0: + package_amount = None image_url = str(data.get('image_front_small_url') or data.get('image_front_url') or '') try: parsed_image = urlparse(image_url) @@ -78,7 +87,9 @@ def map_product(data): image_url = '' return {'barcode': code[:64], 'product_name': name[:255], 'brand': str(data.get('brands') or '')[:255], 'image_url': image_url[:200], - 'package_quantity': str(data.get('quantity') or '')[:100], 'serving_size_text': serving_text, + 'package_quantity': package_text, 'package_amount': package_amount, + 'package_unit': package_unit if package_amount is not None else '', + 'serving_size_text': serving_text, 'serving_amount': serving_amount, 'serving_unit': serving_unit, 'base_unit': Unit.MILLILITRE if serving_unit == 'ml' else Unit.GRAM, **values} @@ -148,7 +159,7 @@ def cached_product(user, barcode, *, refresh=False): return product raise mapped = map_product(data) - if not mapped: + if not mapped or mapped['barcode'] != barcode: return product mapped['source'] = FoodProduct.Source.OPEN_FOOD_FACTS mapped['fetched_at'] = timezone.now() diff --git a/main/food/services/product_resolution.py b/main/food/services/product_resolution.py new file mode 100644 index 0000000..e7fe65b --- /dev/null +++ b/main/food/services/product_resolution.py @@ -0,0 +1,171 @@ +"""Owner-scoped product matching and creation shared by the HTTP API.""" +import re +from decimal import Decimal, InvalidOperation + +from django.contrib.auth import get_user_model +from django.db import transaction +from django.db.models import Q + +from food.models import FoodProduct, Unit +from food.services.openfoodfacts import cached_product, cached_search + +NUTRITION_FIELDS = { + 'calories_kcal': 'energy_kcal_100', 'carbohydrates_g': 'carbohydrates_100', + 'protein_g': 'protein_100', 'fat_g': 'fat_100', 'saturated_fat_g': 'saturated_fat_100', + 'sugars_g': 'sugars_100', 'fibre_g': 'fibre_100', 'salt_g': 'salt_100', +} + + +def _name(value, field, limit, required=False): + if not isinstance(value, str): + raise ValueError(f'{field} must be text.') + cleaned = ' '.join(value.split()) + if len(cleaned) > limit or (required and not cleaned): + raise ValueError(f'Invalid {field}.') + return cleaned + + +def _amount(value, field, positive=True): + if isinstance(value, bool): + raise ValueError(f'Invalid {field}.') + try: + amount = Decimal(str(value)) + except (InvalidOperation, TypeError, ValueError): + raise ValueError(f'Invalid {field}.') from None + if not amount.is_finite() or amount < 0 or (positive and amount == 0) or amount > Decimal('9999999.999'): + raise ValueError(f'Invalid {field}.') + return amount + + +def package_size(product): + if product.package_amount is not None: + return product.package_amount, product.package_unit + match = re.fullmatch(r'\s*(\d+(?:[.,]\d+)?)\s*(g|ml)\s*', product.package_quantity, re.IGNORECASE) + if match: + return Decimal(match.group(1).replace(',', '.')), match.group(2).lower() + return None, '' + + +def match_data(product, confidence, source=None): + amount, unit = package_size(product) + return {'product_id': str(product.api_id), 'source': source or product.source, + 'external_id': product.barcode if product.source == FoodProduct.Source.OPEN_FOOD_FACTS else None, + 'name': product.product_name, 'brand': product.brand, 'barcode': product.barcode or None, + 'package_quantity': str(amount) if amount is not None else None, 'package_unit': unit or None, + 'nutrition_per_100': {field: str(getattr(product, model_field)) if getattr(product, model_field) is not None else None + for field, model_field in NUTRITION_FIELDS.items()}, 'confidence': confidence} + + +def _same_package(product, amount, unit): + existing_amount, existing_unit = package_size(product) + return amount is None or (existing_amount == amount and existing_unit == unit) + + +def local_matches(user, name='', brand='', barcode='', amount=None, unit='', limit=10, include_partial=False): + qs = FoodProduct.objects.filter(owner=user) + if barcode: + exact = qs.filter(barcode=barcode).first() + if exact: + return [match_data(exact, 'exact_barcode')] + if not name: + return [] + if include_partial: + for token in name.split(): + qs = qs.filter(Q(product_name__icontains=token) | Q(brand__icontains=token)) + else: + qs = qs.filter(product_name__iexact=name) + candidates = list(qs.order_by('pk')[:100]) + if brand: + candidates = [p for p in candidates if p.brand.casefold() == brand.casefold()] + if amount is not None and not include_partial: + candidates = [p for p in candidates if _same_package(p, amount, unit)] + candidates.sort(key=lambda p: (p.product_name.casefold() != name.casefold(), + p.brand.casefold() != brand.casefold() if brand else False, + not _same_package(p, amount, unit), p.pk)) + return [match_data(p, 'exact_details' if p.product_name.casefold() == name.casefold() and + brand and p.brand.casefold() == brand.casefold() and amount is not None and + _same_package(p, amount, unit) else 'candidate') for p in candidates[:limit]] + + +def external_matches(user, query='', barcode='', brand='', amount=None, unit='', limit=10): + if barcode: + # A lookup must never mutate the product catalogue. Search results are read-only. + from food.services.openfoodfacts import OpenFoodFactsClient, _rate_limit, map_product + _rate_limit(user.pk, 'product', 10) + raw = OpenFoodFactsClient().get_product(barcode) + products = [map_product(raw)] if raw else [] + else: + products = cached_search(user, query)[:20] + matches = [] + for product in products: + if not product: + continue + if barcode and product['barcode'] != barcode: + continue + package_amount = product.get('package_amount') + package_unit = product.get('package_unit') or None + exact = bool(barcode and product['barcode'] == barcode) + details = bool(query and brand and amount is not None and + product['product_name'].casefold() == query.casefold() and + product['brand'].casefold() == brand.casefold() and + package_amount == amount and package_unit == unit) + matches.append({'product_id': None, 'source': 'open_food_facts', 'external_id': product['barcode'], + 'name': product['product_name'], 'brand': product['brand'], 'barcode': product['barcode'], + 'package_quantity': str(package_amount) if package_amount is not None else None, + 'package_unit': package_unit, + 'nutrition_per_100': {field: str(product[model_field]) if product.get(model_field) is not None else None + for field, model_field in NUTRITION_FIELDS.items()}, + 'confidence': 'exact_barcode' if exact else 'exact_details' if details else 'candidate'}) + matches.sort(key=lambda item: ( + 0 if item['confidence'] == 'exact_barcode' else 1 if item['confidence'] == 'exact_details' else 2, + item['name'].casefold() != query.casefold() if query else False, + item['brand'].casefold() != brand.casefold() if brand else False, + Decimal(item['package_quantity']) != amount if amount is not None and item['package_quantity'] else bool(amount))) + return matches[:limit] + + +def create_manual(user, data): + allowed = {'name', 'brand', 'barcode', 'package_quantity', 'package_unit', 'nutrition_per_100', 'source'} + if set(data) - allowed or data.get('source', 'manual') != 'manual': + raise ValueError('Invalid manual product fields.') + name = _name(data.get('name'), 'name', 255, True) + brand = _name(data.get('brand', ''), 'brand', 255) + barcode = _name(data.get('barcode') or '', 'barcode', 64) + if barcode and not re.fullmatch(r'[0-9]{1,64}', barcode): + raise ValueError('Barcode must be numeric.') + amount = data.get('package_quantity') + unit = data.get('package_unit') or '' + if (amount is None) != (not unit) or (unit and unit not in Unit.values): + raise ValueError('Package quantity and unit must be supplied together.') + amount = _amount(amount, 'package_quantity') if amount is not None else None + nutrition = data.get('nutrition_per_100') or {} + if not isinstance(nutrition, dict) or set(nutrition) - NUTRITION_FIELDS.keys(): + raise ValueError('Invalid nutrition fields.') + nutrients = {model_field: _amount(value, field, False) if value is not None else None + for field, model_field in NUTRITION_FIELDS.items() for value in [nutrition.get(field)]} + with transaction.atomic(): + # Serialize concurrent creates for one owner, including products without barcodes. + get_user_model().objects.select_for_update().get(pk=user.pk) + if barcode: + existing = FoodProduct.objects.filter(owner=user, barcode=barcode).first() + if existing: + return existing, 'reused', [] + exact = local_matches(user, name, brand, '', amount, unit, 20) + if exact: + if len(exact) == 1 and not barcode and (amount is not None or not exact[0]['package_quantity']): + return FoodProduct.objects.get(api_id=exact[0]['product_id']), 'reused', [] + return None, 'needs_review', exact + product = FoodProduct(owner=user, product_name=name, brand=brand, barcode=barcode, + package_quantity=f'{amount:g} {unit}' if amount is not None else '', + package_amount=amount, package_unit=unit, base_unit=unit or Unit.GRAM, + source=FoodProduct.Source.MANUAL, **nutrients) + product.full_clean() + product.save() + return product, 'created', [] + + +def import_off(user, barcode): + if not isinstance(barcode, str) or not re.fullmatch(r'[0-9]{1,64}', barcode): + raise ValueError('Enter a numeric Open Food Facts barcode.') + product = cached_product(user, barcode) + return product diff --git a/main/food/static/food/food.css b/main/food/static/food/food.css index 40bcd86..c16db1e 100644 --- a/main/food/static/food/food.css +++ b/main/food/static/food/food.css @@ -26,12 +26,38 @@ body[data-theme="dark"]{--food-surface:#202923;--food-border:#3b473f;--food-ink: .food-macro p,.food-product-list small{color:var(--food-muted)} body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317} -/* Keep the three macro summaries on one compact row on phones. */ +/* Four goals fit the existing nutrition sidebar in a compact two-column grid. */ +.food-macros{grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem} +.food-macro{display:flex;flex-direction:column;align-items:center;gap:.25rem;min-width:0;margin:0;padding:.7rem .3rem;text-align:center} +.food-ring{width:54px;height:54px;margin:0} +.food-ring span{width:42px;height:42px;font-size:.75rem} +.food-macro h3{font-size:.82rem;line-height:1.15;margin:0;white-space:nowrap} +.food-macro p{font-size:.72rem;line-height:1.2;margin:.1rem 0;overflow-wrap:anywhere} +.food-macro--green{--accent:var(--food-green)} + +/* Keep the four nutrition goals readable on phones. */ @media(max-width:760px){ - .food-macros{grid-template-columns:repeat(3,minmax(0,1fr));gap:.4rem} - .food-macro{display:flex;flex-direction:column;align-items:center;gap:.35rem;min-width:0;padding:.55rem .25rem;text-align:center} - .food-ring{width:48px;height:48px;margin:0} - .food-ring span{width:38px;height:38px;font-size:.7rem} - .food-macro h3{font-size:.8rem;line-height:1.15;margin:0;overflow-wrap:anywhere} - .food-macro p{font-size:.7rem;line-height:1.2;margin:.1rem 0;overflow-wrap:anywhere} + .food-macros{grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem} + .food-macro{display:flex;flex-direction:column;align-items:center;gap:.25rem;min-width:0;padding:.7rem .3rem;text-align:center} + .food-ring{width:54px;height:54px;margin:0} + .food-ring span{width:42px;height:42px;font-size:.75rem} + .food-macro h3{font-size:.82rem;line-height:1.15;margin:0;white-space:nowrap} + .food-macro p{font-size:.72rem;line-height:1.2;margin:.1rem 0;overflow-wrap:anywhere} } + +/* Nutrient guidance sits above the card content and stays within the viewport. */ +.food-macro{position:relative;padding-top:2.8rem} +.food-help-trigger{position:absolute;top:.25rem;right:.25rem;display:grid;place-items:center;width:44px;height:44px;padding:0;border:0;background:transparent;color:var(--food-ink);cursor:pointer} +.food-help-trigger span{display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--food-muted);border-radius:50%;font:700 .85rem/1 inherit} +.food-help-trigger:hover span,.food-help-trigger[aria-expanded="true"] span{background:var(--food-progress-track)} +.food-help-trigger:focus-visible,.food-help-close:focus-visible{outline:2px solid var(--food-green);outline-offset:2px;border-radius:.4rem} +.food-help-popover{position:fixed;z-index:100;width:min(320px,calc(100vw - 24px));max-height:calc(100dvh - 24px);overflow:auto;padding:1rem;text-align:left;background:var(--food-surface);color:var(--food-ink);border:1px solid var(--food-border);border-radius:1rem;box-shadow:0 12px 32px #0008;font-size:.9rem;line-height:1.4} +.food-help-popover[hidden]{display:none} +.food-help-heading{display:flex;align-items:center;justify-content:space-between;gap:1rem} +.food-help-heading h4{margin:0;font-size:1.05rem} +.food-help-close{display:grid;place-items:center;flex:none;width:44px;height:44px;padding:0;border:0;background:transparent;color:var(--food-ink);font-size:1.5rem;cursor:pointer} +.food-help-popover p{margin:.45rem 0 .75rem;color:var(--food-ink)} +.food-help-popover ul{margin:.4rem 0;padding-left:1.25rem} +.food-help-popover li{margin:.25rem 0} +.food-help-popover .food-help-tip{margin-top:.75rem;color:var(--food-muted)} +@media(max-width:600px){.food-help-popover{top:auto!important;left:12px!important;right:12px;bottom:max(12px,env(safe-area-inset-bottom));width:auto;max-height:min(70dvh,560px)}} diff --git a/main/food/static/food/nutrient_help.js b/main/food/static/food/nutrient_help.js new file mode 100644 index 0000000..287ed63 --- /dev/null +++ b/main/food/static/food/nutrient_help.js @@ -0,0 +1,54 @@ +(() => { + let active = null; + + function close(restoreFocus = false) { + if (!active) return; + const { trigger, popover } = active; + popover.hidden = true; + trigger.setAttribute('aria-expanded', 'false'); + active = null; + if (restoreFocus && trigger.isConnected) trigger.focus(); + } + + function position(trigger, popover) { + if (window.matchMedia('(max-width: 600px)').matches) { + popover.style.left = ''; + popover.style.top = ''; + return; + } + const rect = trigger.getBoundingClientRect(); + const width = popover.getBoundingClientRect().width; + const left = Math.max(12, Math.min(rect.right - width, window.innerWidth - width - 12)); + const below = rect.bottom + 8; + const height = popover.getBoundingClientRect().height; + const top = below + height <= window.innerHeight - 12 + ? below : Math.max(12, rect.top - height - 8); + popover.style.left = `${left}px`; + popover.style.top = `${top}px`; + } + + document.addEventListener('click', (event) => { + const trigger = event.target.closest('[data-food-help-trigger]'); + if (trigger) { + if (active?.trigger === trigger) { close(); return; } + close(); + const popover = document.getElementById(trigger.getAttribute('aria-controls')); + if (!popover) return; + popover.hidden = false; + trigger.setAttribute('aria-expanded', 'true'); + active = { trigger, popover }; + position(trigger, popover); + popover.querySelector('[data-food-help-close]').focus(); + return; + } + if (event.target.closest('[data-food-help-close]')) { close(true); return; } + if (active && !active.popover.contains(event.target)) close(); + }); + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape' && active) { event.preventDefault(); close(true); } + }); + window.addEventListener('resize', () => { + if (active) position(active.trigger, active.popover); + }); + document.addEventListener('htmx:beforeSwap', () => close()); +})(); diff --git a/main/food/templates/food/diary.html b/main/food/templates/food/diary.html index 3eb413f..e1085b9 100644 --- a/main/food/templates/food/diary.html +++ b/main/food/templates/food/diary.html @@ -2,6 +2,7 @@ {% load static %} {% block title %}Food · Tasknest{% endblock %} {% block content %} - + {% include 'food/partials/diary_content.html' %} + {% endblock %} diff --git a/main/food/templates/food/partials/diary_content.html b/main/food/templates/food/partials/diary_content.html index d5fa076..c4dc25c 100644 --- a/main/food/templates/food/partials/diary_content.html +++ b/main/food/templates/food/partials/diary_content.html @@ -23,7 +23,17 @@ diff --git a/main/food/templates/food/tokens.html b/main/food/templates/food/tokens.html index 3aca1ac..16438dd 100644 --- a/main/food/templates/food/tokens.html +++ b/main/food/templates/food/tokens.html @@ -20,15 +20,15 @@
-

Your tokens

+

Active tokens

{% for token in tokens %}

{{ token.name }}

Permissions: {{ token.scopes|join:", " }} · Created: {{ token.created_at|date:"SHORT_DATETIME_FORMAT" }} · Last used: {{ token.last_used_at|date:"SHORT_DATETIME_FORMAT"|default:"Never" }}

-

Status: {% if token.revoked_at %}Revoked{% elif token.expires_at and token.expires_at <= now %}Expired{% else %}Active{% endif %}{% if token.expires_at %} · Expires: {{ token.expires_at|date:"SHORT_DATETIME_FORMAT" }}{% endif %}

- {% if not token.revoked_at %}
{% csrf_token %}
{% endif %} +

Status: Active{% if token.expires_at %} · Expires: {{ token.expires_at|date:"SHORT_DATETIME_FORMAT" }}{% endif %}

+
{% csrf_token %}
- {% empty %}

No API tokens yet.

{% endfor %} + {% empty %}

No active API tokens.

{% endfor %}

Connect an AI assistant

diff --git a/main/food/test_api.py b/main/food/test_api.py index 194156c..9ac13aa 100644 --- a/main/food/test_api.py +++ b/main/food/test_api.py @@ -1,6 +1,7 @@ import hashlib import io import json +from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timedelta, timezone as py_timezone from decimal import Decimal from unittest.mock import patch @@ -8,12 +9,14 @@ from unittest.mock import patch from PIL import Image from django.contrib.auth import get_user_model from django.core.files.uploadedfile import SimpleUploadedFile -from django.test import TestCase, override_settings +from django.test import Client, TestCase, TransactionTestCase, override_settings +from django.db import connection from django.utils import timezone from planner.models import UserSettings from .api import create_token from .models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem, PersonalAccessToken +from .services.openfoodfacts import OpenFoodFactsError class FoodApiTests(TestCase): @@ -105,6 +108,118 @@ class FoodApiTests(TestCase): with patch('planner.timezones.timezone.now', return_value=datetime(2026, 1, 1, 1, tzinfo=py_timezone.utc)): self.assertEqual(self.call('get', '/api/v1/food/today/').json()['date'], '2025-12-31') + def test_product_lookup_create_and_duplicate_protection(self): + local = self.call('get', '/api/v1/food/products/lookup/?barcode=123456&include_open_food_facts=false') + self.assertEqual(local.json()['matches'], []) + payload = {'name': 'Oat milk', 'brand': 'Example', 'barcode': '123456', + 'package_quantity': '1000', 'package_unit': 'ml'} + first = self.call('post', '/api/v1/food/products/create/', payload, HTTP_IDEMPOTENCY_KEY='new-oats') + self.assertEqual(first.status_code, 201, first.content) + self.assertEqual(first.json()['product']['package_amount'], '1000') + self.assertIsNone(first.json()['product']['energy_kcal_100']) + match = self.call('get', '/api/v1/food/products/lookup/?barcode=123456') + self.assertEqual(match.json()['matches'][0]['confidence'], 'exact_barcode') + self.assertEqual(match.json()['matches'][0]['product_id'], first.json()['product_id']) + by_name = self.call('get', '/api/v1/food/products/lookup/?query=Oat&brand=Example&package_quantity=1000&package_unit=ml&include_open_food_facts=false') + self.assertEqual(by_name.json()['matches'][0]['product_id'], first.json()['product_id']) + exact_name = self.call('get', '/api/v1/food/products/lookup/?query=Oat%20milk&brand=Example&package_quantity=1000&package_unit=ml&include_open_food_facts=false') + self.assertEqual(exact_name.json()['matches'][0]['confidence'], 'exact_details') + again = self.call('post', '/api/v1/food/products/create/', {**payload, 'name': 'Changed name'}) + self.assertEqual(again.json()['status'], 'reused') + self.assertEqual(FoodProduct.objects.filter(owner=self.a).count(), 2) + self.assertEqual(FoodProduct.objects.get(owner=self.a, barcode='123456').product_name, 'Oat milk') + conflict = self.call('post', '/api/v1/food/products/create/', {**payload, 'brand': 'Other'}, + HTTP_IDEMPOTENCY_KEY='new-oats') + self.assertEqual(conflict.status_code, 409) + self.assertEqual(self.call('post', '/api/v1/food/products/create/', + {'name': 'Bad', 'package_quantity': '-1', 'package_unit': 'g'}).status_code, 400) + self.assertEqual(self.call('post', '/api/v1/food/products/create/', + {'name': 'Bad', 'nutrition_per_100': {'calories_kcal': '-1'}}).status_code, 400) + + @patch('food.services.openfoodfacts.OpenFoodFactsClient.get_product') + def test_open_food_facts_lookup_and_import(self, get_product): + sample = {'code': '87654321', 'product_name': 'Yoghurt', 'brands': 'Example', + 'quantity': '500 g', 'nutriments': {'energy-kcal_100g': 60}} + get_product.return_value = sample + lookup = self.call('get', '/api/v1/food/products/lookup/?barcode=87654321').json() + self.assertEqual(lookup['matches'][0]['source'], 'open_food_facts') + self.assertEqual(FoodProduct.objects.filter(owner=self.a).count(), 1) + imported = self.call('post', '/api/v1/food/products/import/', {'barcode': '87654321'}) + self.assertEqual(imported.status_code, 201, imported.content) + self.assertEqual(imported.json()['product']['package_amount'], '500.000') + self.assertIsNone(imported.json()['product']['protein_100']) + self.assertEqual(self.call('post', '/api/v1/food/products/import/', {'barcode': '87654321'}).json()['status'], 'reused') + get_product.return_value = None + self.assertEqual(self.call('post', '/api/v1/food/products/import/', {'barcode': '999999'}).status_code, 404) + get_product.side_effect = OpenFoodFactsError('Open Food Facts is temporarily unavailable.') + self.assertEqual(self.call('get', '/api/v1/food/products/lookup/?barcode=999999').json()['external_error'], + 'Open Food Facts is temporarily unavailable.') + + def test_batch_grocery_partial_success_and_idempotency(self): + payload = {'create_missing_products': True, 'items': [ + {'name': 'Loose apples', 'quantity': 2, 'location': 'Fridge'}, + {'name': 'Broken', 'quantity': -1, 'location': 'Fridge'}, + ]} + first = self.call('post', '/api/v1/kitchen/import-groceries/', payload, HTTP_IDEMPOTENCY_KEY='groceries-1') + self.assertEqual(first.status_code, 200, first.content) + self.assertEqual(first.json()['status'], 'partial_success') + self.assertEqual([row['status'] for row in first.json()['items']], ['added', 'skipped']) + self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a).count(), 1) + self.assertEqual(FoodProduct.objects.filter(owner=self.a).count(), 2) + second = self.call('post', '/api/v1/kitchen/import-groceries/', payload, HTTP_IDEMPOTENCY_KEY='groceries-1') + self.assertEqual(second.json(), first.json()) + self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a).count(), 1) + self.assertEqual(self.call('post', '/api/v1/kitchen/import-groceries/', + {**payload, 'items': [{'name': 'Pears', 'location': 'Fridge'}]}, + HTTP_IDEMPOTENCY_KEY='groceries-1').status_code, 409) + self.assertEqual(self.call('post', '/api/v1/kitchen/import-groceries/', + {'items': [{'product_id': str(self.product_b.api_id), 'location': 'Fridge'}]}, + HTTP_IDEMPOTENCY_KEY='other-user-product').json()['items'][0]['status'], 'skipped') + + def test_ambiguous_product_requires_review_and_partial_contents_require_one_package(self): + FoodProduct.objects.create(owner=self.a, product_name='Yoghurt', brand='Store A', + package_quantity='500 g', package_amount=Decimal('500'), package_unit='g') + FoodProduct.objects.create(owner=self.a, product_name='Yoghurt', brand='Store B', + package_quantity='500 g', package_amount=Decimal('500'), package_unit='g') + candidates = self.call('post', '/api/v1/food/products/create/', {'name': 'Yoghurt'}) + self.assertEqual(candidates.json()['status'], 'needs_review') + self.assertEqual(len(candidates.json()['candidates']), 2) + self.assertEqual(FoodProduct.objects.filter(owner=self.a, product_name='Yoghurt').count(), 2) + product = FoodProduct.objects.filter(owner=self.a, brand='Store A').first() + invalid = self.call('post', '/api/v1/kitchen/items/', {'product_id': str(product.api_id), + 'quantity': 2, 'location': 'Fridge', 'opened': True, 'remaining_amount': '350'}) + self.assertEqual(invalid.status_code, 400) + valid = self.call('post', '/api/v1/kitchen/items/', {'product_id': str(product.api_id), + 'quantity': 1, 'location': 'Fridge', 'opened': True, 'remaining_amount': '350'}) + self.assertEqual(valid.status_code, 201, valid.content) + self.assertEqual(valid.json()['remaining_amount'], '350') + + def test_barcode_mismatch_does_not_reuse_similar_product(self): + FoodProduct.objects.create(owner=self.a, product_name='Milk', brand='Example', barcode='11111', + package_amount=Decimal('1000'), package_unit='ml', package_quantity='1000 ml') + create = self.call('post', '/api/v1/food/products/create/', {'name': 'Milk', 'brand': 'Example', + 'barcode': '22222', 'package_quantity': '1000', 'package_unit': 'ml'}) + self.assertEqual(create.json()['status'], 'needs_review') + with patch('food.services.openfoodfacts.OpenFoodFactsClient.get_product', return_value=None): + response = self.call('post', '/api/v1/kitchen/import-groceries/', {'create_missing_products': True, + 'items': [{'name': 'Milk', 'brand': 'Example', 'barcode': '22222', + 'package_quantity': '1000', 'package_unit': 'ml', 'location': 'Fridge'}]}, + HTTP_IDEMPOTENCY_KEY='different-milk-barcode') + self.assertEqual(response.json()['items'][0]['status'], 'needs_review') + self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a).count(), 0) + + def test_new_tools_respect_scopes_and_owner_isolation(self): + _, food_read = create_token(self.a, 'Food read', ['food:read']) + self.assertEqual(self.call('get', '/api/v1/food/products/lookup/?query=Pasta&include_open_food_facts=false', token=food_read).status_code, 200) + self.assertEqual(self.call('post', '/api/v1/food/products/create/', {'name': 'New'}, + token=food_read).status_code, 403) + _, inventory_write = create_token(self.a, 'Inventory write', ['inventory:write']) + self.assertEqual(self.call('post', '/api/v1/kitchen/import-groceries/', + {'items': [{'name': 'New', 'location': 'Fridge'}], 'create_missing_products': True}, + token=inventory_write).status_code, 403) + lookup = self.call('get', '/api/v1/food/products/lookup/?query=Private&include_open_food_facts=false') + self.assertEqual(lookup.json()['matches'], []) + def test_food_diary_accepts_specific_date(self): entry = FoodLogEntry.objects.create(user=self.a, date=datetime(2026, 1, 2).date(), meal='breakfast', product_name_snapshot='Oats', amount=Decimal('100'), unit='g', calories_kcal=Decimal('120')) @@ -112,11 +227,24 @@ class FoodApiTests(TestCase): self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['date'], '2026-01-02') self.assertEqual(response.json()['meals']['breakfast'][0]['id'], str(entry.api_id)) - self.assertEqual(response.json()['totals']['calories_kcal'], '120') + self.assertEqual(response.json()['totals']['calories_kcal'], '120.000') self.assertEqual(self.call('get', '/api/v1/food/today/?date=2026-01-03').json()['meals']['breakfast'], []) for invalid in ('', 'yesterday', '2026-02-30', '2026-1-2'): self.assertEqual(self.call('get', f'/api/v1/food/today/?date={invalid}').status_code, 400) + def test_fibre_api_totals_preserve_unknown_values(self): + FoodLogEntry.objects.create(user=self.a, date=timezone.localdate(), meal='breakfast', + product_name_snapshot='Unknown fibre', amount=Decimal('100'), unit='g') + response = self.call('get', '/api/v1/food/today/').json() + self.assertEqual(response['goals']['fibre_goal_g'], '40.0') + self.assertIsNone(response['totals']['fibre_g']) + self.assertTrue(response['fibre_incomplete']) + FoodLogEntry.objects.create(user=self.a, date=timezone.localdate(), meal='lunch', + product_name_snapshot='Known fibre', amount=Decimal('100'), unit='g', fibre_g=Decimal('6.5')) + response = self.call('get', '/api/v1/food/today/').json() + self.assertEqual(response['totals']['fibre_g'], '6.500') + self.assertTrue(response['fibre_incomplete']) + @override_settings(MEDIA_ROOT='/tmp/tasknest-api-test-media') def test_attachment_validation_and_isolation(self): entry = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '1', 'unit': 'g', @@ -162,8 +290,34 @@ class FoodApiTests(TestCase): self.assertEqual(self.client.post(f'/food/settings/tokens/{created.pk}/revoke/').status_code, 302) created.refresh_from_db() self.assertIsNotNone(created.revoked_at) + self.assertNotContains(self.client.get('/food/settings/tokens/'), 'Revoke Phone') + self.assertTrue(PersonalAccessToken.objects.filter(pk=created.pk).exists()) + create_token(self.a, 'Expired token', ['food:read'], timezone.now() - timedelta(days=1)) + self.assertNotContains(self.client.get('/food/settings/tokens/'), 'Expired token') def test_api_fallback_errors_are_json(self): response = self.call('get', '/api/v1/does-not-exist/') self.assertEqual(response.status_code, 404) self.assertEqual(response['Content-Type'], 'application/json') + + +class ConcurrentProductCreationTests(TransactionTestCase): + def test_concurrent_manual_creation_reuses_one_product(self): + if connection.vendor == 'sqlite': + self.skipTest('SQLite does not support select_for_update row locking.') + user = get_user_model().objects.create_user('concurrent-products', password='test') + _, secret = create_token(user, 'Product create', ['food:write']) + payload = json.dumps({'name': 'Milk', 'brand': 'Example', + 'package_quantity': '1000', 'package_unit': 'ml'}) + + def create(_): + client = Client() + response = client.post('/api/v1/food/products/create/', data=payload, + content_type='application/json', HTTP_AUTHORIZATION=f'Bearer {secret}') + return response.status_code, response.json() + + with ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(create, range(2))) + self.assertEqual(sorted(status for status, _ in results), [200, 201]) + self.assertEqual(results[0][1]['product_id'], results[1][1]['product_id']) + self.assertEqual(FoodProduct.objects.filter(owner=user).count(), 1) diff --git a/main/food/test_csv_export.py b/main/food/test_csv_export.py index 9f04864..feb8abc 100644 --- a/main/food/test_csv_export.py +++ b/main/food/test_csv_export.py @@ -69,6 +69,6 @@ class FoodExportTests(TestCase): for index in range(8): FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.LUNCH, product=self.product, product_name_snapshot=f'Food {index}', amount=100, unit=Unit.GRAM) - with self.assertNumQueries(2): + with self.assertNumQueries(3): context = diary_context(self.user, date(2026, 10, 3)) self.assertEqual(len(context['meals'][1]['entries']), 8) diff --git a/main/food/test_openfoodfacts.py b/main/food/test_openfoodfacts.py index 6f4be94..1ef4d62 100644 --- a/main/food/test_openfoodfacts.py +++ b/main/food/test_openfoodfacts.py @@ -32,9 +32,18 @@ class OpenFoodFactsTests(TestCase): self.assertEqual(mapped['serving_amount'], Decimal('300.000')) self.assertEqual(mapped['energy_kcal_100'], Decimal('58.000')) self.assertIsNone(mapped['fat_100']) + self.assertIsNone(mapped['fibre_100']) unsafe = dict(SAMPLE, image_front_url='https://example.com/track.png') self.assertEqual(map_product(unsafe)['image_url'], '') + @patch.object(OpenFoodFactsClient, 'get_product') + def test_fibre_survives_import_and_cached_barcode_lookup(self, get_product): + get_product.return_value = {**SAMPLE, 'nutriments': {**SAMPLE['nutriments'], 'fiber_100g': 2.7}} + product = cached_product(self.user, SAMPLE['code']) + self.assertEqual(product.fibre_100, Decimal('2.700')) + self.assertEqual(cached_product(self.user, SAMPLE['code']).fibre_100, Decimal('2.700')) + get_product.assert_called_once() + @patch.object(OpenFoodFactsClient, 'get_product') def test_fresh_cached_barcode_avoids_http(self, get_product): product = FoodProduct.objects.create(owner=self.user, barcode=SAMPLE['code'], diff --git a/main/food/tests.py b/main/food/tests.py index 25747d0..898762a 100644 --- a/main/food/tests.py +++ b/main/food/tests.py @@ -28,6 +28,64 @@ class FoodFoundationTests(TestCase): self.product.refresh_from_db() self.assertIsNone(self.product.energy_kcal_100) self.assertIsNone(self.product.protein_100) + self.assertIsNone(self.product.fibre_100) + + def test_default_and_custom_fibre_goal(self): + from planner.forms import FoodGoalForm + + self.client.force_login(self.user) + profile = UserSettings.objects.create(user=self.user) + self.assertEqual(profile.fibre_goal_g, Decimal('40')) + response = self.client.get(reverse('planner:user-settings')) + self.assertContains(response, 'Daily fibre goal (g)') + response = self.client.post(reverse('planner:user-settings'), {'section': 'food', + 'daily_calorie_goal': '2000', 'carbohydrate_goal_g': '250', 'protein_goal_g': '100', + 'fat_goal_g': '70', 'fibre_goal_g': '35.5'}) + self.assertEqual(response.status_code, 302) + profile.refresh_from_db() + self.assertEqual(profile.fibre_goal_g, Decimal('35.5')) + self.assertEqual(profile.protein_goal_g, Decimal('100')) + self.assertContains(self.client.get(reverse('planner:user-settings')), 'value="35.5"') + self.assertFalse(FoodGoalForm(data={'fibre_goal_g': '-1'}).is_valid()) + + def test_fibre_snapshots_scale_and_unknown_is_not_zero(self): + from .services.logging import apply_product_snapshot + + self.product.fibre_100 = Decimal('3.2') + self.product.save(update_fields=['fibre_100']) + entry = FoodLogEntry(user=self.user, date=date(2026, 10, 3), meal=MealType.BREAKFAST, + amount=Decimal('250'), unit=Unit.GRAM) + apply_product_snapshot(entry, self.product) + self.assertEqual(entry.fibre_g, Decimal('8.000')) + entry.full_clean() + entry.save() + self.product.fibre_100 = None + self.product.save(update_fields=['fibre_100']) + old = FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.LUNCH, + product_name_snapshot='Legacy food', amount=Decimal('100'), unit=Unit.GRAM) + context = diary_context(self.user, date(2026, 10, 3)) + self.assertIsNone(old.fibre_g) + self.assertEqual(context['totals']['fibre_g'], Decimal('8.000')) + fibre = context['macros'][3] + self.assertTrue(fibre['incomplete']) + self.assertEqual(fibre['percent'], 20) + self.assertIsNone(fibre['remaining']) + self.assertEqual(FoodLogEntry.objects.get(pk=entry.pk).fibre_g, Decimal('8.000')) + + def test_fibre_totals_and_over_goal(self): + UserSettings.objects.create(user=self.user, fibre_goal_g=Decimal('40')) + for value in ('25', '20'): + FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.SNACKS, + product_name_snapshot='Known fibre', amount=Decimal('100'), unit=Unit.GRAM, + fibre_g=Decimal(value)) + context = diary_context(self.user, date(2026, 10, 3)) + self.assertEqual(context['totals']['fibre_g'], Decimal('45')) + fibre = context['macros'][3] + self.assertEqual(fibre['percent'], 100) + self.assertEqual(fibre['remaining'], Decimal('-5')) + self.assertFalse(fibre['incomplete']) + self.client.force_login(self.user) + self.assertContains(self.client.get(reverse('food:diary'), {'date': '2026-10-03'}), '5.0 g over target') def test_favourite_and_portion_uniqueness(self): FoodFavourite.objects.create(user=self.user, product=self.product) @@ -106,7 +164,7 @@ class FoodFoundationTests(TestCase): self.assertEqual(context['calorie_remaining'], Decimal('-35')) self.assertEqual(context['meals'][0]['calories'], Decimal('80')) self.assertEqual(context['meals'][2]['calories'], Decimal('55')) - self.assertEqual(context['macros'][0]['percent'], None) + self.assertEqual(context['macros'][1]['percent'], None) self.client.force_login(self.user) response = self.client.get(reverse('food:diary'), {'date': '2026-10-03'}) self.assertContains(response, '35 kcal over goal') diff --git a/main/food/token_views.py b/main/food/token_views.py index 6f9aa8e..7871c5a 100644 --- a/main/food/token_views.py +++ b/main/food/token_views.py @@ -2,6 +2,7 @@ from datetime import datetime, time, timedelta from django import forms from django.contrib.auth.decorators import login_required +from django.db.models import Q from django.shortcuts import get_object_or_404, redirect, render from django.utils import timezone from django.views.decorators.http import require_http_methods, require_POST @@ -42,10 +43,11 @@ def tokens(request): expires_at = timezone.make_aware(datetime.combine(expiry + timedelta(days=1), time.min), timezone_for_user(request.user)) if expiry else None _, new_token = create_token(request.user, form.cleaned_data['name'], form.cleaned_data['scopes'], expires_at) form = TokenForm(user=request.user) + now = timezone.now() return render(request, 'food/tokens.html', { 'form': form, 'new_token': new_token, - 'tokens': PersonalAccessToken.objects.filter(user=request.user).order_by('-created_at'), - 'now': timezone.now(), + 'tokens': PersonalAccessToken.objects.filter(user=request.user, revoked_at__isnull=True) + .filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now)).order_by('-created_at'), }) diff --git a/main/food/views.py b/main/food/views.py index 1dcfc74..357c022 100644 --- a/main/food/views.py +++ b/main/food/views.py @@ -14,6 +14,7 @@ from django.db.models import Max from django.db import transaction from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse +from django.utils.translation import get_language_from_request from django.views.decorators.http import require_GET, require_http_methods, require_POST from django.views.decorators.cache import never_cache @@ -131,7 +132,8 @@ def _save_entry(form, user, day, product): def _diary_response(request, day): if request.headers.get('HX-Request') == 'true': - response = render(request, 'food/partials/diary_content.html', diary_context(request.user, day)) + response = render(request, 'food/partials/diary_content.html', + diary_context(request.user, day, get_language_from_request(request))) response['HX-Push-Url'] = f"{reverse('food:diary')}?date={day.isoformat()}" return response return redirect(f"{reverse('food:diary')}?date={day.isoformat()}") @@ -142,7 +144,8 @@ def diary(request): day, error = _day(request) if error: return error - return render(request, 'food/diary.html', diary_context(request.user, day)) + return render(request, 'food/diary.html', + diary_context(request.user, day, get_language_from_request(request))) @login_required diff --git a/main/mcp_server/server.py b/main/mcp_server/server.py index 78aa507..9ca1415 100644 --- a/main/mcp_server/server.py +++ b/main/mcp_server/server.py @@ -80,6 +80,32 @@ class FoodUpdate(BaseModel): date: str | None = None +class ProductInput(BaseModel): + name: str + brand: str = '' + barcode: str | None = None + package_quantity: Decimal | None = None + package_unit: Literal['g', 'ml'] | None = None + nutrition_per_100: dict[str, Decimal | None] | None = None + source: Literal['manual'] = 'manual' + + +class GroceryInput(BaseModel): + product_id: str | None = None + name: str | None = None + brand: str | None = None + barcode: str | None = None + quantity: int = 1 + package_quantity: Decimal | None = None + package_unit: Literal['g', 'ml'] | None = None + nutrition_per_100: dict[str, Decimal | None] | None = None + location: str = '' + category: str | None = None + notes: str = '' + opened: bool = False + best_before: str | None = None + + class InventoryUpdate(BaseModel): product_id: str | None = None quantity: int | None = Field(default=None, ge=1) @@ -87,6 +113,7 @@ class InventoryUpdate(BaseModel): category: str | None = None notes: str | None = None opened: bool | None = None + remaining_amount: Decimal | None = Field(default=None, ge=0) best_before: str | None = None @@ -142,13 +169,13 @@ def _entry(entry): return {'id': entry['id'], 'name': entry['product_name_snapshot'], 'meal': entry['meal'], 'date': entry['date'], 'amount': entry['amount'], 'unit': entry['unit'], 'calories_kcal': entry['calories_kcal'], 'carbohydrates_g': entry['carbohydrates_g'], - 'protein_g': entry['protein_g'], 'fat_g': entry['fat_g'], + 'protein_g': entry['protein_g'], 'fat_g': entry['fat_g'], 'fibre_g': entry['fibre_g'], 'attachments': [{'id': a['id'], 'caption': a['caption']} for a in entry.get('attachments', [])]} def _inventory(item): return {key: item.get(key) for key in ('id', 'product_id', 'product_name', 'brand', 'barcode', - 'quantity', 'location', 'category', 'opened', 'best_before', 'notes')} + 'quantity', 'location', 'category', 'opened', 'best_before', 'notes', 'remaining_amount')} def _key(value): @@ -232,10 +259,12 @@ def create_server() -> MCPServer: entries = {meal: [_entry(item) for item in items] for meal, items in data['meals'].items()} goals = data.get('goals', {}) mapping = {'calories_kcal': 'daily_calorie_goal', 'carbohydrates_g': 'carbohydrate_goal_g', - 'protein_g': 'protein_goal_g', 'fat_g': 'fat_goal_g'} + 'protein_g': 'protein_goal_g', 'fat_g': 'fat_goal_g', 'fibre_g': 'fibre_goal_g'} remaining = {name: str(Decimal(goals[goal]) - Decimal(data['totals'][name])) - for name, goal in mapping.items() if goals.get(goal) is not None} - return {'date': data['date'], 'meals': entries, 'totals': data['totals'], 'goals': goals, 'remaining': remaining} + for name, goal in mapping.items() if goals.get(goal) is not None and + data['totals'][name] is not None and not (name == 'fibre_g' and data.get('fibre_incomplete'))} + return {'date': data['date'], 'meals': entries, 'totals': data['totals'], 'goals': goals, + 'remaining': remaining, 'fibre_incomplete': data.get('fibre_incomplete', False)} @server.tool(structured_output=True, description='Search the authenticated user’s saved TaskNest food products before logging a known food. Returns serving sizes, portions, and nutrition per 100 g/ml. Does not change data.') async def food_search_products(query: str, limit: int = 20) -> dict[str, Any]: @@ -245,6 +274,35 @@ def create_server() -> MCPServer: 'protein_100', 'fat_100', 'fibre_100', 'sugars_100', 'salt_100', 'portions') return {'count': data['count'], 'products': [{k: item.get(k) for k in fields} for item in data['results']]} + @server.tool(structured_output=True, description='Find food product candidates in your saved products and optionally Open Food Facts. Read only: never saves a search result. Exact barcodes rank first; ambiguous matches are candidates for user selection. External lookup may be unavailable.') + async def food_lookup_product(query: str = '', barcode: str | None = None, brand: str = '', + package_quantity: Decimal | None = None, + package_unit: Literal['g', 'ml'] | None = None, + limit: int = 10, include_open_food_facts: bool = True) -> dict[str, Any]: + params = {'query': query, 'barcode': barcode or '', 'brand': brand, 'limit': limit, + 'include_open_food_facts': str(include_open_food_facts).lower()} + if package_quantity is not None: + params['package_quantity'] = str(package_quantity) + if package_unit is not None: + params['package_unit'] = package_unit + return await api_request('GET', 'food/products/lookup/', params=params) + + @server.tool(structured_output=True, description='Create a manual food product owned by the authenticated user from supplied facts. No external lookup. Missing nutrition remains unknown; possible duplicates require review. Returns a product_id when created or reused. Reuse idempotency_key on retries.') + async def food_create_product(product: ProductInput, idempotency_key: str | None = None) -> dict[str, Any]: + key = _key(idempotency_key) + data = await api_request('POST', 'food/products/create/', + payload=product.model_dump(mode='json', exclude_none=True), idempotency_key=key) + return {**data, 'idempotency_key': key} + + @server.tool(structured_output=True, description='Save a selected Open Food Facts product by numeric barcode into your product catalogue. Changes data; uses the configured cached external import. Does not invent missing nutrition. Returns a local product_id, or a structured not-found/error response. Reuse idempotency_key on retries.') + async def food_import_product(barcode: str, idempotency_key: str | None = None) -> dict[str, Any]: + key = _key(idempotency_key) + try: + data = await api_request('POST', 'food/products/import/', payload={'barcode': barcode}, idempotency_key=key) + except ToolError as exc: + return {'status': 'failed', 'reason': str(exc), 'idempotency_key': key} + return {**data, 'idempotency_key': key} + @server.tool(structured_output=True, description='Create one food log entry for the authenticated user. For known foods, search TaskNest products first and use product_id; do not fabricate nutrition when reliable product data exists. For a user-requested estimated meal, product_name and estimated nutrition are allowed. Uses the user’s local date unless date is supplied. Reuse idempotency_key on retries.') async def food_log(food: FoodInput, idempotency_key: str | None = None) -> dict[str, Any]: key = _key(idempotency_key) @@ -307,6 +365,15 @@ def create_server() -> MCPServer: item = await api_request('POST', 'kitchen/items/', payload=payload, idempotency_key=key) return {'success': True, 'item': _inventory(item), 'idempotency_key': key} + @server.tool(structured_output=True, description='Add up to 20 groceries to your inventory in one operation. Resolves owned products, may query Open Food Facts, optionally creates manual products from supplied facts, and adds separate inventory rows. Ambiguous matches require review; each item reports success or failure. Does not interpret images. Reuse idempotency_key with the same payload on retries; changed payloads conflict.') + async def inventory_import_groceries(items: list[GroceryInput], idempotency_key: str, + create_missing_products: bool = False) -> dict[str, Any]: + key = _key(idempotency_key) + data = await api_request('POST', 'kitchen/import-groceries/', payload={ + 'items': [item.model_dump(mode='json', exclude_none=True) for item in items], + 'create_missing_products': create_missing_products}, idempotency_key=key) + return {**data, 'idempotency_key': key} + @server.tool(structured_output=True, description='Update only the supplied fields of one inventory item belonging to the authenticated user. Changes existing data.') async def inventory_update(item_id: str, changes: InventoryUpdate) -> dict[str, Any]: item = await api_request('PATCH', f'kitchen/items/{item_id}/', payload=changes.model_dump(mode='json', exclude_unset=True)) diff --git a/main/mcp_server/tests.py b/main/mcp_server/tests.py index 99b145a..30ad653 100644 --- a/main/mcp_server/tests.py +++ b/main/mcp_server/tests.py @@ -157,13 +157,19 @@ class McpHttpTests(LiveServerTestCase): async def check(client): names = {tool.name for tool in (await client.list_tools()).tools} - self.assertEqual(len(names), 12) + self.assertEqual(len(names), 16) + self.assertTrue({'food_lookup_product', 'food_create_product', 'food_import_product', + 'inventory_import_groceries'} <= names) today = (await client.call_tool('food_get_today')).structured_content self.assertEqual(today['meals']['lunch'], []) yesterday = (await client.call_tool('food_get_today', {'date': previous_day.isoformat()})).structured_content self.assertEqual(yesterday['date'], previous_day.isoformat()) self.assertEqual(yesterday['meals']['breakfast'][0]['name'], 'Yesterday oats') - self.assertEqual(yesterday['totals']['calories_kcal'], '120') + self.assertEqual(yesterday['totals']['calories_kcal'], '120.000') + self.assertEqual(yesterday['goals']['fibre_goal_g'], '40.0') + self.assertIsNone(yesterday['totals']['fibre_g']) + self.assertTrue(yesterday['fibre_incomplete']) + self.assertNotIn('fibre_g', yesterday['remaining']) self.assertTrue((await client.call_tool('food_get_today', {'date': 'yesterday'})).is_error) products = (await client.call_tool('food_search_products', {'query': 'Pasta'})).structured_content self.assertEqual(products['count'], 1) @@ -231,3 +237,21 @@ class McpHttpTests(LiveServerTestCase): self.assertEqual((await client.call_tool('food_get_today')).structured_content['meals']['lunch'][0]['name'], 'Private rice') self.assertEqual((await client.call_tool('inventory_list')).structured_content['count'], 1) asyncio.run(self._client(self.b_secret, other)) + + def test_product_creation_and_grocery_batch_tools(self): + async def check(client): + lookup = (await client.call_tool('food_lookup_product', { + 'query': 'Pasta', 'include_open_food_facts': False})).structured_content + self.assertEqual(lookup['matches'][0]['product_id'], str(self.a_product.api_id)) + created = (await client.call_tool('food_create_product', {'product': { + 'name': 'Oat milk', 'package_quantity': '1000', 'package_unit': 'ml'}, + 'idempotency_key': 'mcp-product-oat'})).structured_content + self.assertEqual(created['status'], 'created') + batch_args = {'items': [{'product_id': created['product_id'], 'quantity': 2, 'location': 'Fridge'}], + 'idempotency_key': 'mcp-groceries-oat'} + batch = (await client.call_tool('inventory_import_groceries', batch_args)).structured_content + self.assertEqual(batch['items'][0]['status'], 'added') + again = (await client.call_tool('inventory_import_groceries', batch_args)).structured_content + self.assertEqual(again['items'][0]['inventory_item_id'], batch['items'][0]['inventory_item_id']) + self.assertEqual((await client.call_tool('inventory_list')).structured_content['count'], 1) + asyncio.run(self._client(self.secret, check)) diff --git a/main/planner/forms.py b/main/planner/forms.py index 8c1134b..2e4ead3 100644 --- a/main/planner/forms.py +++ b/main/planner/forms.py @@ -172,18 +172,20 @@ class HydrationGoalForm(forms.ModelForm): class FoodGoalForm(forms.ModelForm): class Meta: model = UserSettings - fields = ('daily_calorie_goal', 'carbohydrate_goal_g', 'protein_goal_g', 'fat_goal_g') + fields = ('daily_calorie_goal', 'carbohydrate_goal_g', 'protein_goal_g', 'fat_goal_g', 'fibre_goal_g') labels = { 'daily_calorie_goal': 'Daily calorie goal (kcal)', 'carbohydrate_goal_g': 'Daily carbohydrate target (g)', 'protein_goal_g': 'Daily protein target (g)', 'fat_goal_g': 'Daily fat target (g)', + 'fibre_goal_g': 'Daily fibre goal (g)', } widgets = { 'daily_calorie_goal': forms.NumberInput(attrs={'min': 0, 'step': 1}), 'carbohydrate_goal_g': forms.NumberInput(attrs={'min': 0, 'step': '0.1'}), 'protein_goal_g': forms.NumberInput(attrs={'min': 0, 'step': '0.1'}), 'fat_goal_g': forms.NumberInput(attrs={'min': 0, 'step': '0.1'}), + 'fibre_goal_g': forms.NumberInput(attrs={'min': 0, 'step': '0.1'}), } diff --git a/main/planner/management/commands/seed_demo.py b/main/planner/management/commands/seed_demo.py index 9b0af4a..a81ed8b 100644 --- a/main/planner/management/commands/seed_demo.py +++ b/main/planner/management/commands/seed_demo.py @@ -119,6 +119,7 @@ class Command(BaseCommand): profile.carbohydrate_goal_g = Decimal('250.0') profile.protein_goal_g = Decimal('100.0') profile.fat_goal_g = Decimal('70.0') + profile.fibre_goal_g = Decimal('40.0') profile.ntfy_url = '' profile.ntfy_enabled = False profile.ntfy_last_tested_at = None diff --git a/main/planner/migrations/0020_usersettings_fibre_goal_g.py b/main/planner/migrations/0020_usersettings_fibre_goal_g.py new file mode 100644 index 0000000..c97fb77 --- /dev/null +++ b/main/planner/migrations/0020_usersettings_fibre_goal_g.py @@ -0,0 +1,12 @@ +from django.core.validators import MinValueValidator +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [('planner', '0019_usersettings_carbohydrate_goal_g_and_more')] + + operations = [ + migrations.AddField(model_name='usersettings', name='fibre_goal_g', + field=models.DecimalField(decimal_places=1, max_digits=7, default=40, + validators=[MinValueValidator(0)])), + ] diff --git a/main/planner/models.py b/main/planner/models.py index 510b037..cef2274 100644 --- a/main/planner/models.py +++ b/main/planner/models.py @@ -124,6 +124,7 @@ class UserSettings(models.Model): carbohydrate_goal_g = models.DecimalField(max_digits=7, decimal_places=1, null=True, blank=True, validators=[MinValueValidator(0)]) protein_goal_g = models.DecimalField(max_digits=7, decimal_places=1, null=True, blank=True, validators=[MinValueValidator(0)]) fat_goal_g = models.DecimalField(max_digits=7, decimal_places=1, null=True, blank=True, validators=[MinValueValidator(0)]) + fibre_goal_g = models.DecimalField(max_digits=7, decimal_places=1, default=40, validators=[MinValueValidator(0)]) ntfy_url = models.URLField(blank=True) ntfy_enabled = models.BooleanField(default=False) ntfy_last_tested_at = models.DateTimeField(null=True, blank=True) diff --git a/main/planner/tests.py b/main/planner/tests.py index c49ad95..f52f9e5 100644 --- a/main/planner/tests.py +++ b/main/planner/tests.py @@ -1061,6 +1061,7 @@ class DemoSeedCommandTests(TestCase): self.assertEqual(profile.carbohydrate_goal_g, 250) self.assertEqual(profile.protein_goal_g, 100) self.assertEqual(profile.fat_goal_g, 70) + self.assertEqual(profile.fibre_goal_g, 40) self.assertFalse(profile.ntfy_enabled) today = localdate_for_user(demo) self.assertEqual(FoodLogEntry.objects.filter(user=demo, date=today).count(), 6)