Enhancements
This commit is contained in:
+11
-1
@@ -1,6 +1,6 @@
|
||||
# TaskNest Food and Kitchen API v1
|
||||
|
||||
The API is intended for a future thin MCP adapter. It is available under `/api/v1/`; machine-readable OpenAPI 3.1 is at `/api/v1/schema/`. No MCP server or interactive production API UI is included.
|
||||
The API is available under `/api/v1/`; machine-readable OpenAPI 3.1 is at `/api/v1/schema/`. The MCP server uses these endpoints. There is no interactive production API UI.
|
||||
|
||||
## Authentication and permissions
|
||||
|
||||
@@ -21,6 +21,10 @@ Each resource lookup filters by the token owner. An unknown UUID and another use
|
||||
| DELETE | `/food/attachments/{id}/` | `food:write` | Delete an owned image |
|
||||
| GET/POST | `/kitchen/items/` | read/write | Search/list or create inventory item |
|
||||
| GET/PATCH/DELETE | `/kitchen/items/{id}/` | read/write | Own inventory item |
|
||||
| GET | `/hydration/daily/?date=YYYY-MM-DD` | `food:read` | Combined total, manual and Food Diary contributions, goal, and remaining amount |
|
||||
| POST | `/hydration/manual/` | `food:write` | Standalone fluid entry; optional `Idempotency-Key` |
|
||||
| PATCH/DELETE | `/hydration/manual/{id}/` | `food:write` | Correct or remove an owned manual fluid entry |
|
||||
| GET/PATCH | `/hydration/settings/` | read/write | Automatic counting, liquid foods, breakdown, manual adjustments, and beverage rules |
|
||||
|
||||
Collection responses use `count`, `limit`, `offset`, and `results`. The default limit is 30 and maximum is 100; `offset` is capped at 10,000. Product and inventory search checks name, brand, and barcode; inventory search also checks location and category. `GET /food/today/` is naturally bounded by one day.
|
||||
|
||||
@@ -32,6 +36,12 @@ For attachment upload, send multipart `image` and optional `caption`. JPEG, PNG,
|
||||
|
||||
POST creation routes accept an optional `Idempotency-Key` header. Repeating the same token, route, key, and body returns the stored result and creates no second record. Reusing a key with a different body or route returns 409. Keys are per token. JSON errors use `{"error":{"code":"...","message":"..."}}`; validation may include `details`. Common codes include `invalid_token`, `expired_token`, `insufficient_scope`, `entry_not_found`, `product_not_found`, `inventory_item_not_found`, `image_too_large`, and `unsupported_image_type`.
|
||||
|
||||
## Hydration accounting
|
||||
|
||||
Food Diary entries saved in millilitres can count toward hydration automatically. Each entry stores its eligible volume, counting factor, and classification source, so later product edits do not rewrite past totals. Grams are never converted to millilitres. Soup counting is off by default. Users can override a product's drink classification from the Food Diary. Manual entry timestamps use the user's local date; food contributions use the Food Diary date. Web and API food logging use the same calculation, so clients do not need a second hydration call.
|
||||
|
||||
For a packaged inventory item, `PATCH /kitchen/items/{id}/` may set `remaining_amount` to an absolute value from zero through its current remaining amount. A reduction uses the existing inventory consumption service; zero archives that package from active inventory. `opened`, `notes`, and other metadata can be sent in the same request. Increasing stock or exceeding the package capacity is rejected. Quantity validation errors return `error.details.field` and `error.details.reason`.
|
||||
|
||||
## Example requests
|
||||
|
||||
```sh
|
||||
|
||||
+5
-1
@@ -47,10 +47,12 @@ 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 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.
|
||||
The server exposes tools for food diary, product catalogue, inventory, and hydration 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`.
|
||||
|
||||
`hydration_get_daily` returns combined fluid intake, manual and Food Diary contributions, the daily goal, and remaining amount. `hydration_log`, `hydration_update`, and `hydration_delete` manage standalone manual entries. Use an `idempotency_key` with `hydration_log` when retrying. `hydration_settings_get` and `hydration_settings_update` configure automatic Food Diary counting and optional beverage rules. The Food Diary tools count eligible millilitre drinks during the food write; no additional hydration tool call is needed.
|
||||
|
||||
## 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.
|
||||
@@ -66,6 +68,8 @@ For ambiguous candidates, ask the user to select one or supply more identifying
|
||||
|
||||
`inventory_get_stock` returns owned products, remaining totals, and individual packages. Use a product ID for a definite match; a text query returns candidates. `inventory_preview_consumption` is read only and shows package deductions and any shortage. `inventory_consume` requires a product ID, positive decimal amount, compatible unit, and idempotency key. It uses opened packages first, then best-before date and age. Set `allow_partial` only after the user explicitly accepts a shortage. `inventory_undo_consumption` records a reversal when the affected package quantities have not changed. All four tools enforce the existing inventory read or write scopes through the HTTP API.
|
||||
|
||||
`inventory_update` accepts an absolute `remaining_amount` for one owned package. Reductions use the same consumption service as `inventory_consume`; zero archives the package. It can update `opened` and `notes` in the same request. A rejected quantity returns `success: false` with `error.details.field` and `error.details.reason`.
|
||||
|
||||
Example tool arguments:
|
||||
|
||||
```json
|
||||
|
||||
+200
-8
@@ -5,6 +5,7 @@ import json
|
||||
import secrets
|
||||
from django.conf import settings
|
||||
from decimal import Decimal
|
||||
from datetime import datetime
|
||||
from functools import wraps
|
||||
from uuid import UUID
|
||||
|
||||
@@ -17,12 +18,14 @@ from django.utils import timezone
|
||||
from django.utils.dateparse import parse_date, parse_time
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
|
||||
from planner.models import UserSettings
|
||||
from planner.timezones import localdate_for_user
|
||||
from planner.models import UserSettings, WaterIntakeEntry
|
||||
from planner.timezones import localdate_for_user, timezone_for_user
|
||||
from .models import (ApiIdempotencyRecord, FoodLogAttachment, FoodLogEntry, FoodProduct,
|
||||
InventoryCategory, InventoryLocation, KitchenInventoryItem,
|
||||
MealType, PersonalAccessToken, Unit)
|
||||
from .services.logging import apply_product_snapshot
|
||||
from .services.hydration import sync_food_hydration, validate_rules
|
||||
from planner.services.hydration import daily_hydration
|
||||
from .services.openfoodfacts import OpenFoodFactsError
|
||||
from .services.product_resolution import (create_manual, external_matches, import_off,
|
||||
local_matches, match_data)
|
||||
@@ -170,6 +173,11 @@ def _entry_data(entry):
|
||||
data.update(id=str(entry.api_id), date=entry.date.isoformat(),
|
||||
time=entry.time.isoformat() if entry.time else None,
|
||||
product_id=str(entry.product.api_id) if entry.product_id else None,
|
||||
beverage_volume_ml=(str(entry.beverage_volume_ml) if entry.beverage_volume_ml is not None else None),
|
||||
hydration_amount_ml=str(entry.hydration_amount_ml),
|
||||
hydration_factor=str(entry.hydration_factor_snapshot),
|
||||
hydration_kind=entry.hydration_kind or None,
|
||||
hydration_source=entry.hydration_source or None,
|
||||
attachments=[_attachment_data(item) for item in entry.attachments.all()],
|
||||
created_at=entry.created_at.isoformat(), updated_at=entry.updated_at.isoformat())
|
||||
for name in ('amount', *NUTRIENTS):
|
||||
@@ -187,6 +195,8 @@ def _product_data(product):
|
||||
if isinstance(data[name], Decimal):
|
||||
data[name] = str(data[name])
|
||||
data['id'] = str(product.api_id)
|
||||
data.update(is_beverage=product.is_beverage, hydration_enabled=product.hydration_enabled,
|
||||
hydration_factor=str(product.hydration_factor), hydration_source=product.hydration_source)
|
||||
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,
|
||||
@@ -204,6 +214,7 @@ def _inventory_data(item):
|
||||
'original_amount': str(item.original_amount) if item.original_amount is not None else None,
|
||||
'unit': item.inventory_unit or 'packs', 'status': item.package_status,
|
||||
'best_before': item.best_before.isoformat() if item.best_before else None,
|
||||
'archived_at': item.archived_at.isoformat() if item.archived_at else None,
|
||||
'added_at': item.added_at.isoformat(), 'updated_at': item.updated_at.isoformat()}
|
||||
|
||||
|
||||
@@ -503,6 +514,7 @@ def _save_entry(request, data, entry=None):
|
||||
for name in MANUAL_FIELDS:
|
||||
if name in data:
|
||||
setattr(entry, name, _decimal(data[name], name) if data[name] is not None else None)
|
||||
sync_food_hydration(entry)
|
||||
entry.full_clean()
|
||||
entry.save()
|
||||
return entry, None
|
||||
@@ -635,16 +647,68 @@ def inventory_detail(request, identifier):
|
||||
|
||||
@api_view('inventory:write', ('PATCH', 'DELETE'))
|
||||
def inventory_change(request, identifier):
|
||||
item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier,
|
||||
archived_at__isnull=True).select_related('product', 'location', 'category').first()
|
||||
if item is None:
|
||||
return error('inventory_item_not_found', 'Inventory item not found.', 404)
|
||||
if request.method == 'DELETE':
|
||||
item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier,
|
||||
archived_at__isnull=True).first()
|
||||
if item is None:
|
||||
return error('inventory_item_not_found', 'Inventory item not found.', 404)
|
||||
item.archived_at = timezone.now()
|
||||
item.save(update_fields=('archived_at', 'updated_at'))
|
||||
return JsonResponse({'deleted': True})
|
||||
item, failure = _save_inventory(request, _json(request), item)
|
||||
return failure or JsonResponse(_inventory_data(item))
|
||||
data = _json(request)
|
||||
try:
|
||||
with transaction.atomic():
|
||||
# Serialize absolute remaining-amount updates with stock consumption.
|
||||
type(request.api_user).objects.select_for_update().get(pk=request.api_user.pk)
|
||||
item = KitchenInventoryItem.objects.select_for_update().filter(
|
||||
user=request.api_user, api_id=identifier, archived_at__isnull=True,
|
||||
).select_related('product', 'location', 'category').first()
|
||||
if item is None:
|
||||
return error('inventory_item_not_found', 'Inventory item not found.', 404)
|
||||
remaining = data.get('remaining_amount', item.remaining_amount)
|
||||
if 'remaining_amount' in data and remaining is not None:
|
||||
try:
|
||||
remaining = _decimal(remaining, 'remaining_amount')
|
||||
except ValueError as exc:
|
||||
return _inventory_validation('remaining_amount', str(exc))
|
||||
if item.original_amount is None or item.remaining_amount is None:
|
||||
return _inventory_validation('remaining_amount', 'This item has no known package amount.')
|
||||
if remaining > item.original_amount:
|
||||
return _inventory_validation('remaining_amount', 'Amount exceeds the package capacity.')
|
||||
if remaining != remaining.quantize(Decimal('.001')):
|
||||
return _inventory_validation('remaining_amount', 'Use at most three decimal places.')
|
||||
if remaining > item.remaining_amount:
|
||||
return _inventory_validation('remaining_amount', 'Increasing remaining stock is not supported.')
|
||||
if remaining < item.remaining_amount:
|
||||
conflicting = set(data) & {'product_id', 'quantity', 'original_amount', 'unit'}
|
||||
if conflicting:
|
||||
return _inventory_validation(sorted(conflicting)[0],
|
||||
'Change package identity or size separately from consumption.')
|
||||
if data.get('opened') is False and remaining > 0:
|
||||
return _inventory_validation('opened', 'A partly used package must be opened.')
|
||||
from .services.inventory_consumption import StockError, consume
|
||||
try:
|
||||
consume(request.api_user, item.product, item.remaining_amount - remaining,
|
||||
item.inventory_unit, package_id=item.api_id, source='mcp',
|
||||
description=str(data.get('notes') or '')[:255])
|
||||
except StockError as exc:
|
||||
return _inventory_validation('remaining_amount', str(exc))
|
||||
item.refresh_from_db()
|
||||
data = {key: value for key, value in data.items() if key != 'remaining_amount'}
|
||||
elif 'remaining_amount' in data:
|
||||
return _inventory_validation('remaining_amount', 'Use a number between zero and the package capacity.')
|
||||
item, failure = _save_inventory(request, data, item)
|
||||
return failure or JsonResponse(_inventory_data(item))
|
||||
except (ValueError, ValidationError) as exc:
|
||||
if isinstance(exc, ValidationError) and hasattr(exc, 'message_dict'):
|
||||
field, messages = next(iter(exc.message_dict.items()))
|
||||
return _inventory_validation(field, '; '.join(messages))
|
||||
return _inventory_validation('inventory', '; '.join(exc.messages) if isinstance(exc, ValidationError) else str(exc))
|
||||
|
||||
|
||||
def _inventory_validation(field, reason):
|
||||
return error('invalid_inventory_update', 'Inventory update rejected.', 400,
|
||||
{'field': field, 'reason': reason})
|
||||
|
||||
|
||||
@api_view('food:write', ('POST',))
|
||||
@@ -815,3 +879,131 @@ def inventory_undo(request, identifier):
|
||||
return JsonResponse({'transaction_id': str(reversal.pk), 'reverses': str(reversal.reverses_id)})
|
||||
except (StockError, ValueError) as exc:
|
||||
return error('cannot_undo', str(exc))
|
||||
|
||||
|
||||
def _water_data(entry):
|
||||
return {'id': str(entry.api_id), 'amount_ml': str(entry.amount_ml),
|
||||
'beverage_type': entry.beverage_type, 'recorded_at': entry.recorded_at.isoformat(),
|
||||
'source': 'manual'}
|
||||
|
||||
|
||||
def _water_amount(value):
|
||||
amount = _decimal(value, 'amount_ml', positive=True)
|
||||
if amount > 3000 or amount != amount.quantize(Decimal('.001')):
|
||||
raise ValueError('Amount must be at most 3000 ml with up to three decimal places.')
|
||||
return amount
|
||||
|
||||
|
||||
def _water_timestamp(value, user):
|
||||
if not value:
|
||||
return timezone.now()
|
||||
try:
|
||||
parsed = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
|
||||
except ValueError:
|
||||
raise ValueError('Use an ISO 8601 timestamp.') from None
|
||||
if timezone.is_naive(parsed):
|
||||
parsed = timezone.make_aware(parsed, timezone_for_user(user))
|
||||
return parsed
|
||||
|
||||
|
||||
@api_view('food:read', ('GET',))
|
||||
def hydration_daily(request):
|
||||
value = request.GET.get('date')
|
||||
day = parse_date(value) if value else localdate_for_user(request.api_user)
|
||||
if day is None or (value and day.isoformat() != value):
|
||||
return error('invalid_date', 'Use YYYY-MM-DD.')
|
||||
result = daily_hydration(request.api_user, day)
|
||||
return JsonResponse({key: value.isoformat() if key == 'date' else str(value)
|
||||
for key, value in result.items()})
|
||||
|
||||
|
||||
@api_view('food:write', ('POST',))
|
||||
def hydration_log(request):
|
||||
data = _json(request)
|
||||
if not UserSettings.objects.get_or_create(user=request.api_user)[0].allow_manual_hydration_adjustments:
|
||||
return error('manual_hydration_disabled', 'Manual hydration is disabled.', 403)
|
||||
allowed = {'amount_ml', 'beverage_type', 'recorded_at'}
|
||||
if set(data) - allowed:
|
||||
return error('invalid_fields', 'Unknown hydration fields.')
|
||||
amount = _water_amount(data.get('amount_ml'))
|
||||
beverage_type = str(data.get('beverage_type', 'water')).strip().lower()
|
||||
if not beverage_type or len(beverage_type) > 32:
|
||||
return error('invalid_beverage_type', 'Invalid beverage type.')
|
||||
recorded_at = _water_timestamp(data.get('recorded_at'), request.api_user)
|
||||
key = request.headers.get('Idempotency-Key', '')
|
||||
|
||||
def create():
|
||||
if key:
|
||||
previous = WaterIntakeEntry.objects.filter(user=request.api_user, idempotency_key=key).first()
|
||||
if previous:
|
||||
if previous.amount_ml != amount or previous.beverage_type != beverage_type or (
|
||||
data.get('recorded_at') and previous.recorded_at != recorded_at):
|
||||
return error('idempotency_conflict', 'Key was used for another hydration entry.', 409)
|
||||
return JsonResponse(_water_data(previous))
|
||||
entry = WaterIntakeEntry.objects.create(user=request.api_user, amount_ml=amount,
|
||||
beverage_type=beverage_type, recorded_at=recorded_at, idempotency_key=key)
|
||||
return JsonResponse(_water_data(entry), status=201)
|
||||
|
||||
return _idempotent(request, data, create)
|
||||
|
||||
|
||||
@api_view('food:write', ('PATCH', 'DELETE'))
|
||||
def hydration_manual_entry(request, identifier):
|
||||
entry = WaterIntakeEntry.objects.filter(user=request.api_user, api_id=identifier).first()
|
||||
if entry is None:
|
||||
return error('hydration_entry_not_found', 'Manual hydration entry not found.', 404)
|
||||
if not UserSettings.objects.get_or_create(user=request.api_user)[0].allow_manual_hydration_adjustments:
|
||||
return error('manual_hydration_disabled', 'Manual hydration is disabled.', 403)
|
||||
if request.method == 'DELETE':
|
||||
entry.delete()
|
||||
return JsonResponse({'deleted': True})
|
||||
data = _json(request)
|
||||
if set(data) - {'amount_ml', 'beverage_type', 'recorded_at'}:
|
||||
return error('invalid_fields', 'Unknown hydration fields.')
|
||||
if 'amount_ml' in data:
|
||||
entry.amount_ml = _water_amount(data['amount_ml'])
|
||||
if 'beverage_type' in data:
|
||||
entry.beverage_type = str(data['beverage_type']).strip().lower()
|
||||
if not entry.beverage_type or len(entry.beverage_type) > 32:
|
||||
return error('invalid_beverage_type', 'Invalid beverage type.')
|
||||
if 'recorded_at' in data:
|
||||
entry.recorded_at = _water_timestamp(data['recorded_at'], request.api_user)
|
||||
entry.full_clean()
|
||||
entry.save()
|
||||
return JsonResponse(_water_data(entry))
|
||||
|
||||
|
||||
def _hydration_settings_data(settings):
|
||||
return {'daily_water_goal_ml': settings.daily_water_goal_ml,
|
||||
'auto_count_food_drinks': settings.auto_count_food_drinks,
|
||||
'include_liquid_foods': settings.include_liquid_foods,
|
||||
'show_hydration_breakdown': settings.show_hydration_breakdown,
|
||||
'allow_manual_hydration_adjustments': settings.allow_manual_hydration_adjustments,
|
||||
'hydration_beverage_rules': settings.hydration_beverage_rules}
|
||||
|
||||
|
||||
@api_view({'GET': 'food:read', 'PATCH': 'food:write'}, ('GET', 'PATCH'))
|
||||
def hydration_settings(request):
|
||||
settings = UserSettings.objects.get_or_create(user=request.api_user)[0]
|
||||
if request.method == 'GET':
|
||||
return JsonResponse(_hydration_settings_data(settings))
|
||||
data = _json(request)
|
||||
allowed = set(_hydration_settings_data(settings))
|
||||
if set(data) - allowed:
|
||||
return error('invalid_fields', 'Unknown hydration settings.')
|
||||
for field in ('auto_count_food_drinks', 'include_liquid_foods', 'show_hydration_breakdown',
|
||||
'allow_manual_hydration_adjustments'):
|
||||
if field in data:
|
||||
if not isinstance(data[field], bool):
|
||||
return error('invalid_setting', f'{field} must be true or false.')
|
||||
setattr(settings, field, data[field])
|
||||
if 'daily_water_goal_ml' in data:
|
||||
goal = data['daily_water_goal_ml']
|
||||
if isinstance(goal, bool) or not isinstance(goal, int) or not 250 <= goal <= 10000:
|
||||
return error('invalid_goal', 'Daily goal must be 250 to 10000 ml.')
|
||||
settings.daily_water_goal_ml = goal
|
||||
if 'hydration_beverage_rules' in data:
|
||||
settings.hydration_beverage_rules = validate_rules(data['hydration_beverage_rules'])
|
||||
settings.full_clean()
|
||||
settings.save()
|
||||
return JsonResponse(_hydration_settings_data(settings))
|
||||
|
||||
@@ -51,6 +51,20 @@ GROCERIES = {'type': 'object', 'required': ['items'], 'properties': {
|
||||
UPLOAD = {'type': 'object', 'required': ['image'], 'properties': {
|
||||
'image': {'type': 'string', 'format': 'binary'}, 'caption': {'type': 'string'},
|
||||
}}
|
||||
HYDRATION_MANUAL = {'type': 'object', 'properties': {
|
||||
'amount_ml': {'type': 'string', 'description': 'Positive decimal, at most 3000 ml'},
|
||||
'beverage_type': {'type': 'string'},
|
||||
'recorded_at': {'type': 'string', 'format': 'date-time',
|
||||
'description': 'Defaults to now; naive values use the user time zone'},
|
||||
}}
|
||||
HYDRATION_SETTINGS = {'type': 'object', 'properties': {
|
||||
'daily_water_goal_ml': {'type': 'integer', 'minimum': 250, 'maximum': 10000},
|
||||
**{name: {'type': 'boolean'} for name in (
|
||||
'auto_count_food_drinks', 'include_liquid_foods', 'show_hydration_breakdown',
|
||||
'allow_manual_hydration_adjustments')},
|
||||
'hydration_beverage_rules': {'type': 'object', 'description':
|
||||
'Optional beverage type rules with enabled and factor (0 to 1) keys.'},
|
||||
}}
|
||||
|
||||
|
||||
@require_GET
|
||||
@@ -90,6 +104,16 @@ def schema(request):
|
||||
'/kitchen/consumption/preview/': {'post': operation('Preview package deductions without changing stock', 'inventory:read')},
|
||||
'/kitchen/consumption/': {'post': operation('Consume stock atomically with Idempotency-Key', 'inventory:write')},
|
||||
'/kitchen/consumption/{id}/undo/': {'post': operation('Undo a safe consumption transaction', 'inventory:write')},
|
||||
'/hydration/daily/': {'get': operation('Combined manual and Food Diary fluid totals for a user local date', 'food:read')},
|
||||
'/hydration/manual/': {'post': operation('Create standalone fluid entry with optional Idempotency-Key', 'food:write', HYDRATION_MANUAL)},
|
||||
'/hydration/manual/{id}/': {
|
||||
'patch': operation('Correct own manual fluid entry', 'food:write', HYDRATION_MANUAL),
|
||||
'delete': operation('Delete own manual fluid entry', 'food:write'),
|
||||
},
|
||||
'/hydration/settings/': {
|
||||
'get': operation('Read hydration settings', 'food:read'),
|
||||
'patch': operation('Update hydration settings', 'food:write', HYDRATION_SETTINGS),
|
||||
},
|
||||
},
|
||||
}
|
||||
for path, methods in document['paths'].items():
|
||||
@@ -106,6 +130,11 @@ def schema(request):
|
||||
'description': 'Local calendar date; defaults to today in the user time zone.',
|
||||
'schema': {'type': 'string', 'format': 'date'},
|
||||
}]
|
||||
document['paths']['/hydration/daily/']['get']['parameters'] = [{
|
||||
'name': 'date', 'in': 'query', 'required': False,
|
||||
'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'}),
|
||||
|
||||
@@ -21,4 +21,8 @@ urlpatterns = [
|
||||
path('kitchen/consumption/preview/', api.inventory_preview),
|
||||
path('kitchen/consumption/', api.inventory_consume),
|
||||
path('kitchen/consumption/<uuid:identifier>/undo/', api.inventory_undo),
|
||||
path('hydration/daily/', api.hydration_daily),
|
||||
path('hydration/manual/', api.hydration_log),
|
||||
path('hydration/manual/<uuid:identifier>/', api.hydration_manual_entry),
|
||||
path('hydration/settings/', api.hydration_settings),
|
||||
]
|
||||
|
||||
@@ -141,6 +141,16 @@ class FoodLogForm(forms.ModelForm):
|
||||
return data
|
||||
|
||||
|
||||
class FoodProductHydrationForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = FoodProduct
|
||||
fields = ('is_beverage', 'hydration_enabled', 'hydration_factor')
|
||||
labels = {'is_beverage': 'Count as a beverage',
|
||||
'hydration_enabled': 'Include in hydration totals',
|
||||
'hydration_factor': 'Fluid counting factor (0 to 1)'}
|
||||
widgets = {'hydration_factor': forms.NumberInput(attrs={'min': 0, 'max': 1, 'step': '.001'})}
|
||||
|
||||
|
||||
class InventoryItemForm(forms.ModelForm):
|
||||
location_name = forms.CharField(max_length=100, label='Location', widget=forms.TextInput(attrs={'list': 'inventory-locations', 'autocomplete': 'off'}))
|
||||
category_name = forms.CharField(max_length=100, required=False, label='My category', widget=forms.TextInput(attrs={'list': 'inventory-categories', 'autocomplete': 'off'}))
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
from decimal import Decimal
|
||||
|
||||
import django.core.validators
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [('food', '0007_inventory_reversal_state')]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(model_name='foodproduct', name='is_beverage', field=models.BooleanField(default=False)),
|
||||
migrations.AddField(model_name='foodproduct', name='hydration_enabled', field=models.BooleanField(default=True)),
|
||||
migrations.AddField(model_name='foodproduct', name='hydration_factor', field=models.DecimalField(
|
||||
decimal_places=3, default=1, max_digits=4,
|
||||
validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(1)])),
|
||||
migrations.AddField(model_name='foodproduct', name='hydration_source', field=models.CharField(
|
||||
choices=[('manual', 'Manual'), ('product_metadata', 'Product metadata'), ('inferred', 'Inferred')],
|
||||
default='inferred', max_length=16)),
|
||||
migrations.AddField(model_name='foodlogentry', name='beverage_volume_ml', field=models.DecimalField(
|
||||
blank=True, decimal_places=3, max_digits=10, null=True,
|
||||
validators=[django.core.validators.MinValueValidator(0)])),
|
||||
migrations.AddField(model_name='foodlogentry', name='hydration_amount_ml', field=models.DecimalField(
|
||||
decimal_places=3, default=0, max_digits=10, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
migrations.AddField(model_name='foodlogentry', name='hydration_factor_snapshot', field=models.DecimalField(
|
||||
decimal_places=3, default=0, max_digits=4, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
migrations.AddField(model_name='foodlogentry', name='hydration_kind', field=models.CharField(blank=True, max_length=24)),
|
||||
migrations.AddField(model_name='foodlogentry', name='hydration_source', field=models.CharField(blank=True, max_length=16)),
|
||||
]
|
||||
@@ -0,0 +1,34 @@
|
||||
import re
|
||||
from decimal import Decimal
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
PATTERNS = (
|
||||
('water', r'water'), ('juice', r'juice|sap|limonade|lemonade'),
|
||||
('milk', r'milk|melk|chocolademelk'),
|
||||
('coffee', r'coffee|koffie|espresso|cappuccino|latte'),
|
||||
('tea', r'tea|thee'), ('smoothie', r'smoothie|shake'),
|
||||
('other_drink', r'soda|cola|drink|drank|bier|beer|wine|wijn'),
|
||||
)
|
||||
|
||||
|
||||
def backfill_food_drinks(apps, schema_editor):
|
||||
Entry = apps.get_model('food', 'FoodLogEntry')
|
||||
for entry in Entry.objects.filter(unit='ml', hydration_source='').iterator():
|
||||
name = entry.product_name_snapshot.casefold()
|
||||
kind = next((kind for kind, words in PATTERNS
|
||||
if re.search(rf'(?<!\w)(?:{words})(?!\w)', name)), '')
|
||||
if not kind:
|
||||
Entry.objects.filter(pk=entry.pk).update(hydration_source='inferred')
|
||||
continue
|
||||
amount = Decimal(entry.amount)
|
||||
Entry.objects.filter(pk=entry.pk).update(beverage_volume_ml=amount,
|
||||
hydration_amount_ml=amount, hydration_factor_snapshot=Decimal('1'),
|
||||
hydration_kind=kind, hydration_source='inferred')
|
||||
Entry.objects.filter(hydration_source='').update(hydration_source='inferred')
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [('food', '0008_food_hydration'), ('planner', '0021_automatic_hydration')]
|
||||
operations = [migrations.RunPython(backfill_food_drinks, migrations.RunPython.noop)]
|
||||
+10
-1
@@ -2,7 +2,7 @@ import uuid
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import MinValueValidator
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
from django.db import models
|
||||
from django.db.models import Q
|
||||
from django.utils import timezone
|
||||
@@ -38,6 +38,10 @@ class FoodProduct(models.Model):
|
||||
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)
|
||||
is_beverage = models.BooleanField(default=False)
|
||||
hydration_enabled = models.BooleanField(default=True)
|
||||
hydration_factor = models.DecimalField(max_digits=4, decimal_places=3, default=1, validators=[MinValueValidator(0), MaxValueValidator(1)])
|
||||
hydration_source = models.CharField(max_length=16, choices=[('manual', 'Manual'), ('product_metadata', 'Product metadata'), ('inferred', 'Inferred')], default='inferred')
|
||||
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)
|
||||
@@ -76,6 +80,11 @@ class FoodLogEntry(models.Model):
|
||||
portion_label_snapshot = models.CharField(max_length=100, blank=True)
|
||||
amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE)
|
||||
unit = models.CharField(max_length=2, choices=Unit.choices)
|
||||
beverage_volume_ml = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
hydration_amount_ml = models.DecimalField(max_digits=10, decimal_places=3, default=0, validators=NON_NEGATIVE)
|
||||
hydration_factor_snapshot = models.DecimalField(max_digits=4, decimal_places=3, default=0, validators=NON_NEGATIVE)
|
||||
hydration_kind = models.CharField(max_length=24, blank=True)
|
||||
hydration_source = models.CharField(max_length=16, blank=True)
|
||||
calories_kcal = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
carbohydrates_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
protein_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Snapshot a food entry's eligible drink volume when it is saved."""
|
||||
|
||||
import re
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from planner.models import UserSettings
|
||||
|
||||
|
||||
ZERO = Decimal('0')
|
||||
ONE = Decimal('1')
|
||||
ML = Decimal('0.001')
|
||||
DRINK_WORDS = {
|
||||
'water': r'water|sparkling water|mineral water',
|
||||
'juice': r'juice|sap|limonade|lemonade',
|
||||
'milk': r'milk|melk|chocolademelk|chocolate milk',
|
||||
'coffee': r'coffee|koffie|espresso|cappuccino|latte',
|
||||
'tea': r'tea|thee',
|
||||
'smoothie': r'smoothie|shake',
|
||||
'soup': r'soup|soep|bouillon|broth',
|
||||
'other_drink': r'soda|cola|drink|drank|bier|beer|wine|wijn',
|
||||
}
|
||||
|
||||
|
||||
def beverage_kind(name, categories=''):
|
||||
text = f'{name} {categories}'.casefold()
|
||||
for kind, words in DRINK_WORDS.items():
|
||||
if re.search(rf'(?<!\w)(?:{words})(?!\w)', text):
|
||||
return kind
|
||||
if re.search(r'(?<!\w)(?:beverages|drinks|boissons|dranken)(?!\w)', categories.casefold()):
|
||||
return 'other_drink'
|
||||
return ''
|
||||
|
||||
|
||||
def validate_rules(rules):
|
||||
if not isinstance(rules, dict) or set(rules) - set(DRINK_WORDS):
|
||||
raise ValueError('Rules must use supported beverage types.')
|
||||
clean = {}
|
||||
for kind, rule in rules.items():
|
||||
if not isinstance(rule, dict) or set(rule) - {'enabled', 'factor'}:
|
||||
raise ValueError('Each beverage rule needs enabled and/or factor.')
|
||||
item = {}
|
||||
if 'enabled' in rule:
|
||||
if not isinstance(rule['enabled'], bool):
|
||||
raise ValueError('Rule enabled must be true or false.')
|
||||
item['enabled'] = rule['enabled']
|
||||
if 'factor' in rule:
|
||||
try:
|
||||
factor = Decimal(str(rule['factor']))
|
||||
except (InvalidOperation, TypeError):
|
||||
raise ValueError('Invalid hydration factor.') from None
|
||||
if not factor.is_finite() or factor < 0 or factor > 1 or factor != factor.quantize(ML):
|
||||
raise ValueError('Hydration factor must be between 0 and 1 with at most three decimals.')
|
||||
item['factor'] = str(factor)
|
||||
clean[kind] = item
|
||||
return clean
|
||||
|
||||
|
||||
def sync_food_hydration(entry):
|
||||
"""Use saved classification on edits, so later product edits do not rewrite history."""
|
||||
previous = None
|
||||
if entry.pk:
|
||||
previous = type(entry).objects.filter(pk=entry.pk, user=entry.user).only(
|
||||
'hydration_source', 'hydration_kind', 'hydration_factor_snapshot').first()
|
||||
if previous and previous.hydration_source:
|
||||
kind, source, factor = (previous.hydration_kind, previous.hydration_source,
|
||||
previous.hydration_factor_snapshot)
|
||||
else:
|
||||
product = entry.product if entry.product_id else None
|
||||
name = product.product_name if product else entry.product_name_snapshot
|
||||
categories = (str(product.raw_data.get('categories', '')) if product and
|
||||
isinstance(product.raw_data, dict) else '')
|
||||
kind = beverage_kind(name, categories)
|
||||
source = 'product_metadata' if product and categories and kind else 'inferred'
|
||||
if product and product.hydration_source == 'manual':
|
||||
source = 'manual'
|
||||
kind = kind or 'other_drink'
|
||||
enabled = product.is_beverage and product.hydration_enabled
|
||||
else:
|
||||
enabled = bool(kind) and (product.hydration_enabled if product else True)
|
||||
settings = UserSettings.objects.get_or_create(user=entry.user)[0]
|
||||
if kind == 'soup' and not settings.include_liquid_foods and source != 'manual':
|
||||
enabled = False
|
||||
rule = settings.hydration_beverage_rules.get(kind, {})
|
||||
if rule.get('enabled') is False:
|
||||
enabled = False
|
||||
factor = ((product.hydration_factor if product else ONE) *
|
||||
Decimal(str(rule.get('factor', '1')))) if enabled else ZERO
|
||||
factor = factor.quantize(ML)
|
||||
if not enabled:
|
||||
kind = kind if kind == 'soup' else ''
|
||||
entry.hydration_kind = kind
|
||||
entry.hydration_source = source
|
||||
entry.hydration_factor_snapshot = factor
|
||||
# Food Diary nutrition units do not imply density. Only millilitres qualify.
|
||||
entry.beverage_volume_ml = entry.amount if entry.unit == 'ml' and factor > 0 else None
|
||||
entry.hydration_amount_ml = (entry.beverage_volume_ml * factor).quantize(ML) if entry.beverage_volume_ml else ZERO
|
||||
return entry
|
||||
@@ -63,3 +63,4 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317}
|
||||
@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)}}
|
||||
|
||||
.inventory-product-card{display:grid;gap:.8rem}.inventory-product-heading{display:flex;align-items:center;gap:1rem;min-width:0}.inventory-product-heading img{width:68px;height:68px;object-fit:contain;background:white;border-radius:.6rem}.inventory-product-heading h2{margin:0}.inventory-product-heading p{margin:.25rem 0;overflow-wrap:anywhere}.inventory-packages summary,.inventory-use summary{cursor:pointer;min-height:44px;align-content:center;font-weight:650}.inventory-package-list{display:grid;gap:.65rem;margin:.6rem 0}.inventory-package{display:flex;align-items:center;gap:.8rem;padding:.65rem;border:1px solid var(--food-border);border-radius:.7rem;min-width:0}.inventory-package>div:last-child{min-width:0}.inventory-package p{margin:.2rem 0}.inventory-package small{color:var(--food-muted)}.inventory-package-fill{flex:none;position:relative;width:42px;height:64px;border:2px solid var(--food-muted);border-radius:.3rem;overflow:hidden;background:var(--food-progress-track)}.inventory-package-fill span{position:absolute;bottom:0;left:0;right:0;background:var(--food-green);transition:height .25s ease}.inventory-use-form{display:flex;flex-wrap:wrap;gap:.6rem;align-items:end}.inventory-use-form label{display:grid;gap:.25rem;flex:1;min-width:100px}.inventory-use-form input,.inventory-use-form select{max-width:100%;min-height:44px}.inventory-use-form button{min-height:44px}.inventory-preview{border:1px solid var(--food-border);border-radius:.7rem;padding:.8rem;margin-top:.7rem}.inventory-preview h3{margin:0}.inventory-preview form{display:flex;align-items:center;gap:.6rem;flex-wrap:wrap}.inventory-preview form button,.inventory-history button{min-height:44px}.inventory-preview [role=alert]{color:#e9aa72}.inventory-history ul{padding-left:1.2rem}.inventory-history li{margin:.4rem 0}.inventory-history li form{display:inline-block;margin-left:.5rem}@media(max-width:480px){.inventory-product-heading{align-items:flex-start}.inventory-use-form{display:grid;grid-template-columns:1fr 1fr}.inventory-use-form label:nth-child(3){grid-column:1/-1}.inventory-use-form button{grid-column:1/-1}}@media(prefers-reduced-motion:reduce){.inventory-package-fill span{transition:none}}
|
||||
.food-entry-actions{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:.3rem;flex:none}.food-entry-actions a{display:inline-flex;align-items:center;min-height:44px;padding:.2rem .35rem}.food-entry-actions a:focus-visible{outline:2px solid var(--food-green);outline-offset:2px}@media(max-width:480px){.food-entry{flex-wrap:wrap}.food-entry-actions{width:100%;justify-content:flex-start}}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
{% endwith %}
|
||||
<div><strong>{{ entry.product_name_snapshot }}</strong>{% if entry.brand_snapshot %}<span>{{ entry.brand_snapshot }}</span>{% endif %}<small>{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.portion_label_snapshot %}{{ entry.portion_label_snapshot }} {% endif %}({{ entry.amount|floatformat:-3 }} {{ entry.unit }})</small></div>
|
||||
</div>
|
||||
<a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a>
|
||||
<div class="food-entry-actions"><a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a>{% if entry.product %}<a href="{% url 'food:product-hydration' entry.product.pk %}" aria-label="Drink settings for {{ entry.product_name_snapshot }}">Drink settings</a>{% endif %}</div>
|
||||
</li>
|
||||
{% endfor %}</ul>{% else %}<p class="food-empty">Nothing logged yet.</p>{% endif %}
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Drink settings · Tasknest{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}">
|
||||
<div class="food-form-page"><a href="{% url 'food:diary' %}">← Food diary</a><h1>Drink settings for {{ product.product_name }}</h1><p>Only Food Diary amounts logged in ml count. Existing entries keep their saved contribution.</p><form class="food-card" method="post">{% csrf_token %}{{ form.non_field_errors }}{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save drink settings</button></form></div>
|
||||
{% endblock %}
|
||||
+143
-2
@@ -13,9 +13,9 @@ 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 planner.models import UserSettings, WaterIntakeEntry
|
||||
from .api import create_token
|
||||
from .models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem, PersonalAccessToken
|
||||
from .models import FoodLogEntry, FoodProduct, InventoryConsumption, InventoryLocation, KitchenInventoryItem, PersonalAccessToken
|
||||
from .services.openfoodfacts import OpenFoodFactsError
|
||||
|
||||
|
||||
@@ -87,6 +87,89 @@ class FoodApiTests(TestCase):
|
||||
self.assertEqual(self.call('delete', f'/api/v1/food/log/{identifier}/').status_code, 200)
|
||||
self.assertEqual(self.call('post', '/api/v1/food/log/', {**payload, 'amount': '0'}).status_code, 400)
|
||||
|
||||
def test_drink_contribution_follows_food_entry_and_preserves_snapshot(self):
|
||||
day = timezone.localdate()
|
||||
tomorrow = day + timedelta(days=1)
|
||||
drink = FoodProduct.objects.create(owner=self.a, product_name='Orange juice', base_unit='ml')
|
||||
payload = {'meal': 'lunch', 'amount': '250', 'unit': 'ml', 'product_id': str(drink.api_id),
|
||||
'date': day.isoformat()}
|
||||
first = self.call('post', '/api/v1/food/log/', payload, HTTP_IDEMPOTENCY_KEY='juice-1')
|
||||
self.assertEqual(first.status_code, 201, first.content)
|
||||
self.assertEqual(self.call('post', '/api/v1/food/log/', payload,
|
||||
HTTP_IDEMPOTENCY_KEY='juice-1').status_code, 200)
|
||||
daily = lambda date: self.call('get', f'/api/v1/hydration/daily/?date={date}').json()
|
||||
self.assertEqual(daily(day.isoformat())['food_ml'], '250.000')
|
||||
self.assertEqual(FoodLogEntry.objects.filter(user=self.a).count(), 1)
|
||||
identifier = first.json()['id']
|
||||
drink.product_name = 'Orange food'
|
||||
drink.hydration_factor = Decimal('.5')
|
||||
drink.save()
|
||||
changed = self.call('patch', f'/api/v1/food/log/{identifier}/',
|
||||
{'amount': '300', 'date': tomorrow.isoformat()})
|
||||
self.assertEqual(changed.status_code, 200, changed.content)
|
||||
self.assertEqual(Decimal(daily(day.isoformat())['food_ml']), 0)
|
||||
self.assertEqual(daily(tomorrow.isoformat())['food_ml'], '300.000')
|
||||
self.assertEqual(self.call('delete', f'/api/v1/food/log/{identifier}/').status_code, 200)
|
||||
self.assertEqual(Decimal(daily(tomorrow.isoformat())['food_ml']), 0)
|
||||
|
||||
def test_drink_units_settings_and_manual_hydration_crud(self):
|
||||
drink = FoodProduct.objects.create(owner=self.a, product_name='Milk', base_unit='ml')
|
||||
grams = self.call('post', '/api/v1/food/log/', {'meal': 'breakfast', 'amount': '200',
|
||||
'unit': 'g', 'product_name': 'Milk'})
|
||||
self.assertEqual(grams.status_code, 201, grams.content)
|
||||
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['food_ml']), 0)
|
||||
self.assertEqual(self.call('patch', '/api/v1/hydration/settings/',
|
||||
{'auto_count_food_drinks': False}).status_code, 200)
|
||||
ml = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '200',
|
||||
'unit': 'ml', 'product_id': str(drink.api_id)})
|
||||
self.assertEqual(ml.status_code, 201, ml.content)
|
||||
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['food_ml']), 0)
|
||||
self.call('patch', '/api/v1/hydration/settings/', {'auto_count_food_drinks': True})
|
||||
self.assertEqual(self.call('get', '/api/v1/hydration/daily/').json()['food_ml'], '200.000')
|
||||
first = self.call('post', '/api/v1/hydration/manual/', {'amount_ml': '150.5',
|
||||
'beverage_type': 'water'}, HTTP_IDEMPOTENCY_KEY='manual-1')
|
||||
self.assertEqual(first.status_code, 201, first.content)
|
||||
again = self.call('post', '/api/v1/hydration/manual/', {'amount_ml': '150.5',
|
||||
'beverage_type': 'water'}, HTTP_IDEMPOTENCY_KEY='manual-1')
|
||||
self.assertEqual(again.status_code, 200)
|
||||
self.assertEqual(WaterIntakeEntry.objects.filter(user=self.a).count(), 1)
|
||||
self.assertEqual(self.call('get', '/api/v1/hydration/daily/').json()['total_ml'], '350.500')
|
||||
identifier = first.json()['id']
|
||||
self.assertEqual(self.call('patch', f'/api/v1/hydration/manual/{identifier}/',
|
||||
{'amount_ml': '100'}).status_code, 200)
|
||||
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['manual_ml']), 100)
|
||||
self.assertEqual(self.call('delete', f'/api/v1/hydration/manual/{identifier}/').status_code, 200)
|
||||
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['manual_ml']), 0)
|
||||
|
||||
def test_soup_setting_and_product_override_affect_new_entries_only(self):
|
||||
soup = FoodProduct.objects.create(owner=self.a, product_name='Tomato soup', base_unit='ml')
|
||||
payload = {'meal': 'lunch', 'amount': '200', 'unit': 'ml', 'product_id': str(soup.api_id)}
|
||||
first = self.call('post', '/api/v1/food/log/', payload)
|
||||
self.assertEqual(first.status_code, 201, first.content)
|
||||
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['food_ml']), 0)
|
||||
self.assertEqual(self.call('patch', '/api/v1/hydration/settings/',
|
||||
{'include_liquid_foods': True, 'hydration_beverage_rules': {'soup': {'factor': '0.5'}}}).status_code, 200)
|
||||
second = self.call('post', '/api/v1/food/log/', payload)
|
||||
self.assertEqual(second.status_code, 201, second.content)
|
||||
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['food_ml']), 100)
|
||||
self.assertEqual(self.call('get', f'/api/v1/food/log/{first.json()["id"]}/').json()['hydration_amount_ml'], '0.000')
|
||||
self.client.force_login(self.a)
|
||||
override = self.client.post(f'/food/product/{soup.pk}/hydration/',
|
||||
{'is_beverage': 'on', 'hydration_enabled': 'on', 'hydration_factor': '1.000'})
|
||||
self.assertEqual(override.status_code, 302, override.content)
|
||||
soup.refresh_from_db()
|
||||
self.assertEqual(soup.hydration_source, 'manual')
|
||||
|
||||
def test_hydration_daily_uses_user_local_manual_date(self):
|
||||
UserSettings.objects.create(user=self.a, time_zone='America/Los_Angeles')
|
||||
logged = self.call('post', '/api/v1/hydration/manual/', {'amount_ml': '250',
|
||||
'recorded_at': '2026-01-01T01:00:00+00:00'})
|
||||
self.assertEqual(logged.status_code, 201, logged.content)
|
||||
previous = self.call('get', '/api/v1/hydration/daily/?date=2025-12-31').json()
|
||||
next_day = self.call('get', '/api/v1/hydration/daily/?date=2026-01-01').json()
|
||||
self.assertEqual(Decimal(previous['manual_ml']), 250)
|
||||
self.assertEqual(Decimal(next_day['manual_ml']), 0)
|
||||
|
||||
def test_manual_and_inventory_crud(self):
|
||||
manual = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '1', 'unit': 'g',
|
||||
'product_name': 'Homemade satay', 'calories_kcal': '850'})
|
||||
@@ -195,6 +278,64 @@ class FoodApiTests(TestCase):
|
||||
self.assertEqual(valid.status_code, 201, valid.content)
|
||||
self.assertEqual(valid.json()['remaining_amount'], '350')
|
||||
|
||||
def test_inventory_absolute_partial_updates_and_depletion(self):
|
||||
meatballs = FoodProduct.objects.create(owner=self.a, product_name='Meatballs',
|
||||
package_amount=Decimal('400'), package_unit='g')
|
||||
location = InventoryLocation.objects.create(user=self.a, name='Fridge')
|
||||
item = KitchenInventoryItem.objects.create(user=self.a, product=meatballs, location=location,
|
||||
original_amount=Decimal('400'), remaining_amount=Decimal('400'), inventory_unit='g')
|
||||
path = f'/api/v1/kitchen/items/{item.api_id}/'
|
||||
first = self.call('patch', path, {'opened': True, 'remaining_amount': 280,
|
||||
'notes': 'Used 120 g for dinner.'})
|
||||
self.assertEqual(first.status_code, 200, first.content)
|
||||
self.assertEqual(Decimal(first.json()['remaining_amount']), 280)
|
||||
self.assertEqual(first.json()['notes'], 'Used 120 g for dinner.')
|
||||
self.assertTrue(first.json()['opened'])
|
||||
self.assertEqual(self.call('patch', path, {'remaining_amount': 280}).status_code, 200)
|
||||
self.assertEqual(InventoryConsumption.objects.filter(user=self.a).count(), 1)
|
||||
second = self.call('patch', path, {'remaining_amount': 130})
|
||||
self.assertEqual(second.status_code, 200, second.content)
|
||||
self.assertEqual(Decimal(second.json()['remaining_amount']), 130)
|
||||
self.assertEqual(self.call('get', f'/api/v1/kitchen/stock/?product_id={meatballs.api_id}').json()
|
||||
['products'][0]['totals']['g'], '130.000')
|
||||
too_much = self.call('patch', path, {'remaining_amount': 401})
|
||||
self.assertEqual(too_much.status_code, 400)
|
||||
self.assertEqual(too_much.json()['error']['details']['field'], 'remaining_amount')
|
||||
negative = self.call('patch', path, {'remaining_amount': -1})
|
||||
self.assertEqual(negative.status_code, 400)
|
||||
self.assertEqual(negative.json()['error']['details']['field'], 'remaining_amount')
|
||||
self.assertEqual(self.call('patch', path, {'notes': 'Still in fridge'}).json()['notes'], 'Still in fridge')
|
||||
depleted = self.call('patch', path, {'opened': True, 'remaining_amount': 0,
|
||||
'notes': 'Used final 130 g.'})
|
||||
self.assertEqual(depleted.status_code, 200, depleted.content)
|
||||
self.assertEqual(depleted.json()['status'], 'depleted')
|
||||
self.assertIsNotNone(depleted.json()['archived_at'])
|
||||
self.assertEqual(self.call('get', path).status_code, 404)
|
||||
self.assertEqual(self.call('get', f'/api/v1/kitchen/stock/?product_id={meatballs.api_id}').json()
|
||||
['products'][0]['available'], False)
|
||||
|
||||
def test_inventory_depletes_only_one_identical_cup(self):
|
||||
yoghurt = FoodProduct.objects.create(owner=self.a, product_name='Yoghurt cup',
|
||||
package_amount=Decimal('175'), package_unit='g')
|
||||
location = InventoryLocation.objects.create(user=self.a, name='Fridge')
|
||||
cups = [KitchenInventoryItem.objects.create(user=self.a, product=yoghurt, location=location,
|
||||
original_amount=Decimal('175'), remaining_amount=Decimal('175'), inventory_unit='g')
|
||||
for _ in range(2)]
|
||||
result = self.call('patch', f'/api/v1/kitchen/items/{cups[0].api_id}/',
|
||||
{'opened': True, 'remaining_amount': 0, 'notes': 'Consumed one cup.'})
|
||||
self.assertEqual(result.status_code, 200, result.content)
|
||||
cups[0].refresh_from_db()
|
||||
cups[1].refresh_from_db()
|
||||
self.assertIsNotNone(cups[0].archived_at)
|
||||
self.assertEqual(cups[1].remaining_amount, Decimal('175'))
|
||||
self.assertIsNone(cups[1].archived_at)
|
||||
stock = self.call('get', f'/api/v1/kitchen/stock/?product_id={yoghurt.api_id}').json()['products'][0]
|
||||
self.assertEqual(stock['totals']['g'], '175.000')
|
||||
self.assertEqual(len(stock['packages']), 1)
|
||||
self.assertEqual(stock['packages'][0]['id'], str(cups[1].api_id))
|
||||
self.assertEqual(self.call('patch', f'/api/v1/kitchen/items/{self.item_b.api_id}/',
|
||||
{'remaining_amount': 0}).status_code, 404)
|
||||
|
||||
def test_inventory_stock_preview_consume_idempotency_undo_and_scopes(self):
|
||||
product = FoodProduct.objects.create(owner=self.a, product_name='Stock butter',
|
||||
package_amount=Decimal('250'), package_unit='g')
|
||||
|
||||
@@ -29,5 +29,6 @@ urlpatterns = [
|
||||
path('log/<int:pk>/delete/', views.delete_entry, name='delete'),
|
||||
path('attachments/<uuid:identifier>/file/', views.attachment_file, name='attachment-file'),
|
||||
path('product/<int:pk>/favourite/', views.toggle_favourite, name='toggle-favourite'),
|
||||
path('product/<int:pk>/hydration/', views.product_hydration, name='product-hydration'),
|
||||
path('export/<str:period>/', views.export_csv, name='export'),
|
||||
]
|
||||
|
||||
@@ -24,6 +24,7 @@ from .services.diary import diary_context, selected_date
|
||||
from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search
|
||||
from .services.products import local_products
|
||||
from .services.logging import apply_product_snapshot
|
||||
from .services.hydration import sync_food_hydration
|
||||
from planner.timezones import localdate_for_user
|
||||
|
||||
|
||||
@@ -124,6 +125,7 @@ def _save_entry(form, user, day, product):
|
||||
entry.user = user
|
||||
entry.date = day
|
||||
apply_product_snapshot(entry, product)
|
||||
sync_food_hydration(entry)
|
||||
entry.full_clean()
|
||||
entry.save()
|
||||
_save_custom_portion(form, user, product, entry)
|
||||
@@ -135,6 +137,7 @@ def _diary_response(request, 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()}"
|
||||
response['HX-Trigger'] = 'hydrationChanged'
|
||||
return response
|
||||
return redirect(f"{reverse('food:diary')}?date={day.isoformat()}")
|
||||
|
||||
@@ -366,6 +369,7 @@ def edit_entry(request, pk):
|
||||
for field, original in original_nutrients.items():
|
||||
setattr(updated, field, (original * factor).quantize(Decimal('0.001')) if original is not None else None)
|
||||
with transaction.atomic():
|
||||
sync_food_hydration(updated)
|
||||
updated.full_clean()
|
||||
updated.save()
|
||||
if product:
|
||||
@@ -383,3 +387,18 @@ def delete_entry(request, pk):
|
||||
day = entry.date
|
||||
entry.delete()
|
||||
return _diary_response(request, day)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def product_hydration(request, pk):
|
||||
from .forms import FoodProductHydrationForm
|
||||
|
||||
product = get_object_or_404(FoodProduct, pk=pk, owner=request.user)
|
||||
form = FoodProductHydrationForm(request.POST or None, instance=product)
|
||||
if request.method == 'POST' and form.is_valid():
|
||||
product = form.save(commit=False)
|
||||
product.hydration_source = 'manual'
|
||||
product.save()
|
||||
return redirect('food:diary')
|
||||
return render(request, 'food/product_hydration.html', {'product': product, 'form': form})
|
||||
|
||||
@@ -117,6 +117,15 @@ class InventoryUpdate(BaseModel):
|
||||
best_before: str | None = None
|
||||
|
||||
|
||||
class HydrationSettingsUpdate(BaseModel):
|
||||
daily_water_goal_ml: int | None = None
|
||||
auto_count_food_drinks: bool | None = None
|
||||
include_liquid_foods: bool | None = None
|
||||
show_hydration_breakdown: bool | None = None
|
||||
allow_manual_hydration_adjustments: bool | None = None
|
||||
hydration_beverage_rules: dict[str, dict[str, Any]] | None = None
|
||||
|
||||
|
||||
def _token() -> str:
|
||||
access = get_access_token()
|
||||
if access is None:
|
||||
@@ -135,7 +144,7 @@ def _api_error(response: httpx2.Response) -> ToolError:
|
||||
|
||||
|
||||
async def api_request(method: str, path: str, *, payload=None, params=None, files=None, form=None,
|
||||
idempotency_key=None, token=None):
|
||||
idempotency_key=None, token=None, return_validation=False):
|
||||
headers = {'Authorization': f'Bearer {token or _token()}'}
|
||||
if idempotency_key:
|
||||
headers['Idempotency-Key'] = idempotency_key
|
||||
@@ -146,6 +155,8 @@ async def api_request(method: str, path: str, *, payload=None, params=None, file
|
||||
except (httpx2.RequestError, TimeoutError):
|
||||
raise ToolError('TaskNest is unavailable. Retry with the same idempotency key if this was a creation.') from None
|
||||
if response.status_code >= 400:
|
||||
if return_validation and response.status_code == 400:
|
||||
return response.json()
|
||||
raise _api_error(response)
|
||||
if response.headers.get('content-type', '').startswith('application/json'):
|
||||
return response.json()
|
||||
@@ -175,7 +186,8 @@ def _entry(entry):
|
||||
|
||||
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', 'remaining_amount')}
|
||||
'quantity', 'location', 'category', 'opened', 'best_before', 'notes',
|
||||
'remaining_amount', 'original_amount', 'unit', 'status', 'archived_at')}
|
||||
|
||||
|
||||
def _key(value):
|
||||
@@ -376,7 +388,10 @@ def create_server() -> MCPServer:
|
||||
|
||||
@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))
|
||||
item = await api_request('PATCH', f'kitchen/items/{item_id}/',
|
||||
payload=changes.model_dump(mode='json', exclude_unset=True), return_validation=True)
|
||||
if 'error' in item:
|
||||
return {'success': False, 'error': item['error']}
|
||||
return {'success': True, 'item': _inventory(item)}
|
||||
|
||||
@server.tool(structured_output=True, description='Permanently remove one kitchen inventory item belonging to the authenticated user. This is destructive; require the user’s clear intent.')
|
||||
@@ -410,6 +425,41 @@ def create_server() -> MCPServer:
|
||||
async def inventory_undo_consumption(transaction_id: str) -> dict[str, Any]:
|
||||
return await api_request('POST', f'kitchen/consumption/{transaction_id}/undo/', payload={})
|
||||
|
||||
@server.tool(structured_output=True, description='Read combined daily hydration, separate manual and Food Diary drink contributions, the daily goal, and remaining amount. Optional date is YYYY-MM-DD in the user’s time zone.')
|
||||
async def hydration_get_daily(date: str | None = None) -> dict[str, Any]:
|
||||
return await api_request('GET', 'hydration/daily/', params={'date': date} if date else None)
|
||||
|
||||
@server.tool(structured_output=True, description='Add a standalone manual fluid entry. Food Diary drinks count automatically and need no second call. Reuse the same idempotency key on retries.')
|
||||
async def hydration_log(amount_ml: Decimal, beverage_type: str = 'water',
|
||||
recorded_at: str | None = None, idempotency_key: str | None = None) -> dict[str, Any]:
|
||||
key = _key(idempotency_key)
|
||||
payload = {'amount_ml': str(amount_ml), 'beverage_type': beverage_type}
|
||||
if recorded_at is not None:
|
||||
payload['recorded_at'] = recorded_at
|
||||
data = await api_request('POST', 'hydration/manual/', payload=payload, idempotency_key=key)
|
||||
return {**data, 'idempotency_key': key}
|
||||
|
||||
@server.tool(structured_output=True, description='Correct an owned standalone manual hydration entry by ID. Does not edit Food Diary contributions.')
|
||||
async def hydration_update(entry_id: str, amount_ml: Decimal | None = None,
|
||||
beverage_type: str | None = None, recorded_at: str | None = None) -> dict[str, Any]:
|
||||
changes = {'amount_ml': str(amount_ml) if amount_ml is not None else None,
|
||||
'beverage_type': beverage_type, 'recorded_at': recorded_at}
|
||||
return await api_request('PATCH', f'hydration/manual/{entry_id}/',
|
||||
payload={k: v for k, v in changes.items() if v is not None})
|
||||
|
||||
@server.tool(structured_output=True, description='Delete an owned standalone manual hydration entry. Does not affect Food Diary entries.')
|
||||
async def hydration_delete(entry_id: str) -> dict[str, Any]:
|
||||
return await api_request('DELETE', f'hydration/manual/{entry_id}/')
|
||||
|
||||
@server.tool(structured_output=True, description='Read hydration goal and automatic drink counting settings for the authenticated user.')
|
||||
async def hydration_settings_get() -> dict[str, Any]:
|
||||
return await api_request('GET', 'hydration/settings/')
|
||||
|
||||
@server.tool(structured_output=True, description='Update hydration goal, automatic Food Diary drink counting, liquid-food inclusion, widget breakdown, manual adjustment permission, or beverage-specific rules.')
|
||||
async def hydration_settings_update(changes: HydrationSettingsUpdate) -> dict[str, Any]:
|
||||
return await api_request('PATCH', 'hydration/settings/',
|
||||
payload=changes.model_dump(mode='json', exclude_unset=True))
|
||||
|
||||
return server
|
||||
|
||||
|
||||
|
||||
@@ -118,6 +118,60 @@ class McpHttpTests(LiveServerTestCase):
|
||||
await self._client(self.read_secret, read_only)
|
||||
asyncio.run(check())
|
||||
|
||||
def test_hydration_tools_and_food_logging_share_totals(self):
|
||||
drink = FoodProduct.objects.create(owner=self.a, product_name='Orange juice', base_unit='ml')
|
||||
|
||||
async def check(client):
|
||||
food = await client.call_tool('food_log', {'food': {'meal': 'lunch', 'amount': '200',
|
||||
'unit': 'ml', 'product_id': str(drink.api_id)}})
|
||||
self.assertFalse(food.is_error, food)
|
||||
daily = (await client.call_tool('hydration_get_daily')).structured_content
|
||||
self.assertEqual(daily['food_ml'], '200.000')
|
||||
manual = (await client.call_tool('hydration_log', {'amount_ml': '125',
|
||||
'idempotency_key': 'mcp-hydration-1'})).structured_content
|
||||
self.assertEqual(manual['amount_ml'], '125')
|
||||
again = (await client.call_tool('hydration_log', {'amount_ml': '125',
|
||||
'idempotency_key': 'mcp-hydration-1'})).structured_content
|
||||
self.assertEqual(again['id'], manual['id'])
|
||||
daily = (await client.call_tool('hydration_get_daily')).structured_content
|
||||
self.assertEqual(Decimal(daily['total_ml']), 325)
|
||||
self.assertFalse((await client.call_tool('hydration_delete',
|
||||
{'entry_id': manual['id']})).is_error)
|
||||
self.assertEqual(Decimal((await client.call_tool('hydration_get_daily')).structured_content['total_ml']), 200)
|
||||
|
||||
asyncio.run(self._client(self.secret, check))
|
||||
|
||||
def test_inventory_update_partial_quantity_and_structured_validation(self):
|
||||
product = FoodProduct.objects.create(owner=self.a, product_name='Meatballs',
|
||||
package_amount=Decimal('400'), package_unit='g')
|
||||
location = InventoryLocation.objects.create(user=self.a, name='Fridge')
|
||||
package = KitchenInventoryItem.objects.create(user=self.a, product=product, location=location,
|
||||
original_amount=Decimal('400'), remaining_amount=Decimal('400'), inventory_unit='g')
|
||||
|
||||
async def check(client):
|
||||
changed = (await client.call_tool('inventory_update', {'item_id': str(package.api_id),
|
||||
'changes': {'opened': True, 'remaining_amount': 280,
|
||||
'notes': 'Used 120 g for dinner.'}})).structured_content
|
||||
self.assertTrue(changed['success'])
|
||||
self.assertEqual(Decimal(changed['item']['remaining_amount']), 280)
|
||||
self.assertEqual(changed['item']['unit'], 'g')
|
||||
stock = (await client.call_tool('inventory_get_stock',
|
||||
{'product_id': str(product.api_id)})).structured_content
|
||||
self.assertEqual(stock['products'][0]['totals']['g'], '280.000')
|
||||
invalid = (await client.call_tool('inventory_update', {'item_id': str(package.api_id),
|
||||
'changes': {'remaining_amount': 401}})).structured_content
|
||||
self.assertFalse(invalid['success'])
|
||||
self.assertEqual(invalid['error']['details']['field'], 'remaining_amount')
|
||||
self.assertTrue((await client.call_tool('inventory_update', {'item_id': str(package.api_id),
|
||||
'changes': {'remaining_amount': -1}})).is_error)
|
||||
self.assertTrue((await client.call_tool('inventory_update', {'item_id': str(self.b_item.api_id),
|
||||
'changes': {'notes': 'Unauthorized'}})).is_error)
|
||||
unrelated = (await client.call_tool('inventory_update', {'item_id': str(package.api_id),
|
||||
'changes': {'notes': 'Still in fridge'}})).structured_content
|
||||
self.assertEqual(unrelated['item']['notes'], 'Still in fridge')
|
||||
|
||||
asyncio.run(self._client(self.secret, check))
|
||||
|
||||
def test_oauth_issued_pat_authenticates_mcp(self):
|
||||
application = Application.objects.create(user=self.a, name='Test ChatGPT style client',
|
||||
client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
|
||||
@@ -157,7 +211,7 @@ class McpHttpTests(LiveServerTestCase):
|
||||
|
||||
async def check(client):
|
||||
names = {tool.name for tool in (await client.list_tools()).tools}
|
||||
self.assertEqual(len(names), 20)
|
||||
self.assertEqual(len(names), 26)
|
||||
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
|
||||
|
||||
@@ -164,8 +164,13 @@ class NtfySettingsForm(forms.ModelForm):
|
||||
class HydrationGoalForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = UserSettings
|
||||
fields = ('daily_water_goal_ml',)
|
||||
labels = {'daily_water_goal_ml': 'Daily water goal (ml)'}
|
||||
fields = ('daily_water_goal_ml', 'auto_count_food_drinks', 'include_liquid_foods',
|
||||
'show_hydration_breakdown', 'allow_manual_hydration_adjustments')
|
||||
labels = {'daily_water_goal_ml': 'Daily water goal (ml)',
|
||||
'auto_count_food_drinks': 'Automatically count drinks from Food Diary',
|
||||
'include_liquid_foods': 'Include soups and other liquid foods',
|
||||
'show_hydration_breakdown': 'Show manual and Food Diary breakdown',
|
||||
'allow_manual_hydration_adjustments': 'Allow manual hydration entries'}
|
||||
widgets = {'daily_water_goal_ml': forms.NumberInput(attrs={'min': 250, 'max': 10000, 'step': 1})}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import uuid
|
||||
|
||||
import django.core.validators
|
||||
from django.db import migrations, models
|
||||
from django.db.models import Q
|
||||
|
||||
|
||||
def backfill_water_ids(apps, schema_editor):
|
||||
Entry = apps.get_model('planner', 'WaterIntakeEntry')
|
||||
for entry in Entry.objects.filter(api_id__isnull=True).iterator():
|
||||
Entry.objects.filter(pk=entry.pk).update(api_id=uuid.uuid4())
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [('planner', '0020_usersettings_fibre_goal_g')]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(model_name='usersettings', name='auto_count_food_drinks', field=models.BooleanField(default=True)),
|
||||
migrations.AddField(model_name='usersettings', name='include_liquid_foods', field=models.BooleanField(default=False)),
|
||||
migrations.AddField(model_name='usersettings', name='show_hydration_breakdown', field=models.BooleanField(default=True)),
|
||||
migrations.AddField(model_name='usersettings', name='allow_manual_hydration_adjustments', field=models.BooleanField(default=True)),
|
||||
migrations.AddField(model_name='usersettings', name='hydration_beverage_rules', field=models.JSONField(blank=True, default=dict)),
|
||||
migrations.AddField(model_name='waterintakeentry', name='api_id', field=models.UUIDField(null=True)),
|
||||
migrations.RunPython(backfill_water_ids, migrations.RunPython.noop),
|
||||
migrations.AlterField(model_name='waterintakeentry', name='api_id', field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
migrations.AddField(model_name='waterintakeentry', name='beverage_type', field=models.CharField(default='water', max_length=32)),
|
||||
migrations.AddField(model_name='waterintakeentry', name='idempotency_key', field=models.CharField(blank=True, max_length=128)),
|
||||
migrations.AlterField(model_name='waterintakeentry', name='amount_ml', field=models.DecimalField(
|
||||
decimal_places=3, max_digits=10,
|
||||
validators=[django.core.validators.MinValueValidator(0.001), django.core.validators.MaxValueValidator(3000)])),
|
||||
migrations.AddConstraint(model_name='waterintakeentry', constraint=models.UniqueConstraint(
|
||||
fields=('user', 'idempotency_key'), condition=~Q(idempotency_key=''),
|
||||
name='planner_unique_water_idempotency')),
|
||||
]
|
||||
+12
-1
@@ -1,9 +1,11 @@
|
||||
from datetime import time
|
||||
import uuid
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
from django.db import models
|
||||
from django.db.models import Q
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
@@ -120,6 +122,11 @@ class UserSettings(models.Model):
|
||||
daily_water_goal_ml = models.PositiveIntegerField(
|
||||
default=2000, validators=[MinValueValidator(250), MaxValueValidator(10000)],
|
||||
)
|
||||
auto_count_food_drinks = models.BooleanField(default=True)
|
||||
include_liquid_foods = models.BooleanField(default=False)
|
||||
show_hydration_breakdown = models.BooleanField(default=True)
|
||||
allow_manual_hydration_adjustments = models.BooleanField(default=True)
|
||||
hydration_beverage_rules = models.JSONField(default=dict, blank=True)
|
||||
daily_calorie_goal = models.PositiveIntegerField(null=True, blank=True)
|
||||
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)])
|
||||
@@ -380,13 +387,17 @@ class FastingPause(models.Model):
|
||||
|
||||
|
||||
class WaterIntakeEntry(models.Model):
|
||||
api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='water_entries')
|
||||
amount_ml = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(3000)])
|
||||
amount_ml = models.DecimalField(max_digits=10, decimal_places=3, validators=[MinValueValidator(0.001), MaxValueValidator(3000)])
|
||||
beverage_type = models.CharField(max_length=32, default='water')
|
||||
idempotency_key = models.CharField(max_length=128, blank=True)
|
||||
recorded_at = models.DateTimeField(default=timezone.now, db_index=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ('-recorded_at', '-pk')
|
||||
constraints = [models.UniqueConstraint(fields=('user', 'idempotency_key'), condition=~Q(idempotency_key=''), name='planner_unique_water_idempotency')]
|
||||
|
||||
|
||||
class FastingPeriod(models.Model):
|
||||
|
||||
@@ -1,9 +1,29 @@
|
||||
from datetime import datetime, time, timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from django.utils import timezone
|
||||
|
||||
from planner.models import UserSettings, WaterIntakeEntry
|
||||
from planner.timezones import timezone_for_user
|
||||
from food.models import FoodLogEntry
|
||||
|
||||
|
||||
ZERO = Decimal('0')
|
||||
|
||||
|
||||
def daily_hydration(user, day):
|
||||
zone = timezone_for_user(user)
|
||||
start = timezone.make_aware(datetime.combine(day, time.min), zone)
|
||||
end = timezone.make_aware(datetime.combine(day + timedelta(days=1), time.min), zone)
|
||||
settings = UserSettings.objects.get_or_create(user=user)[0]
|
||||
manual = sum((entry.amount_ml for entry in WaterIntakeEntry.objects.filter(
|
||||
user=user, recorded_at__gte=start, recorded_at__lt=end)), ZERO)
|
||||
food = (sum((entry.hydration_amount_ml for entry in FoodLogEntry.objects.filter(user=user, date=day)), ZERO)
|
||||
if settings.auto_count_food_drinks else ZERO)
|
||||
total = manual + food
|
||||
return {'date': day, 'manual_ml': manual, 'food_ml': food, 'total_ml': total,
|
||||
'goal_ml': settings.daily_water_goal_ml,
|
||||
'remaining_ml': max(ZERO, Decimal(settings.daily_water_goal_ml) - total)}
|
||||
|
||||
|
||||
def hydration_context(user, now=None):
|
||||
@@ -12,11 +32,20 @@ def hydration_context(user, now=None):
|
||||
start = today - timedelta(days=today.weekday())
|
||||
week_start = timezone.make_aware(datetime.combine(start, time.min), zone)
|
||||
week_end = timezone.make_aware(datetime.combine(start + timedelta(days=7), time.min), zone)
|
||||
goal = UserSettings.objects.get_or_create(user=user)[0].daily_water_goal_ml
|
||||
settings = UserSettings.objects.get_or_create(user=user)[0]
|
||||
goal = settings.daily_water_goal_ml
|
||||
entries = WaterIntakeEntry.objects.filter(user=user, recorded_at__gte=week_start, recorded_at__lt=week_end)
|
||||
totals = {start + timedelta(days=i): 0 for i in range(7)}
|
||||
totals = {start + timedelta(days=i): ZERO for i in range(7)}
|
||||
for entry in entries:
|
||||
totals[timezone.localtime(entry.recorded_at, zone).date()] += entry.amount_ml
|
||||
manual_today = totals[today]
|
||||
food_today = ZERO
|
||||
if settings.auto_count_food_drinks:
|
||||
for entry in FoodLogEntry.objects.filter(user=user, date__gte=start,
|
||||
date__lt=start + timedelta(days=7)):
|
||||
totals[entry.date] += entry.hydration_amount_ml
|
||||
if entry.date == today:
|
||||
food_today += entry.hydration_amount_ml
|
||||
total = totals[today]
|
||||
last = entries.filter(
|
||||
recorded_at__gte=timezone.make_aware(datetime.combine(today, time.min), zone),
|
||||
@@ -31,6 +60,9 @@ def hydration_context(user, now=None):
|
||||
'state': state, 'state_label': {'none': 'no water logged', 'partial': 'partial goal', 'goal': 'goal met'}[state],
|
||||
'today': day == today})
|
||||
return {'hydration_total': total, 'hydration_goal': goal, 'hydration_percent': percent,
|
||||
'hydration_manual': manual_today, 'hydration_food': food_today,
|
||||
'hydration_show_breakdown': settings.show_hydration_breakdown,
|
||||
'hydration_allow_manual': settings.allow_manual_hydration_adjustments,
|
||||
'hydration_visual': visual, 'hydration_fill_y': 168 - round(visual * 1.22),
|
||||
'hydration_fill_height': round(visual * 1.22), 'hydration_last': last,
|
||||
'hydration_last_time': timezone.localtime(last.recorded_at, zone).strftime('%H:%M') if last else None,
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
<article id="hydration-widget" class="hydration-widget" aria-labelledby="hydration-heading" aria-live="polite">
|
||||
<article id="hydration-widget" class="hydration-widget" aria-labelledby="hydration-heading" aria-live="polite" hx-get="{% url 'planner:hydration-panel' %}" hx-trigger="hydrationChanged from:body" hx-swap="outerHTML">
|
||||
<p class="eyebrow">Daily hydration</p>
|
||||
<h2 id="hydration-heading">Water</h2>
|
||||
<div class="hydration-widget__main">
|
||||
<div class="hydration-widget__stats">
|
||||
<p class="hydration-widget__total">{{ hydration_total|floatformat:0 }} <span>/ {{ hydration_goal }} ml</span></p>
|
||||
<p>{{ hydration_percent }}% of daily goal</p>
|
||||
{% if hydration_show_breakdown %}<p class="hydration-widget__breakdown">Manual: {{ hydration_manual|floatformat:0 }} ml · Food Diary drinks: {{ hydration_food|floatformat:0 }} ml</p>{% endif %}
|
||||
<div class="hydration-widget__track" role="progressbar" aria-label="Daily water goal" aria-valuenow="{{ hydration_visual }}" aria-valuemin="0" aria-valuemax="100"><span style="width:{{ hydration_visual }}%"></span></div>
|
||||
</div>
|
||||
{% include 'planner/partials/hydration_bottle.html' %}
|
||||
</div>
|
||||
<div class="hydration-widget__actions">
|
||||
{% if hydration_allow_manual %}<div class="hydration-widget__actions">
|
||||
<form method="post" action="{% url 'planner:hydration-add' %}" hx-post="{% url 'planner:hydration-add' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<button type="submit" name="amount_ml" value="250">+250 ml</button><button type="submit" name="amount_ml" value="500">+500 ml</button></form>
|
||||
<details class="hydration-widget__other"><summary>Other</summary><form method="post" action="{% url 'planner:hydration-add' %}" hx-post="{% url 'planner:hydration-add' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<label for="hydration-amount">Amount (ml)</label><input id="hydration-amount" name="amount_ml" type="number" min="1" max="3000" step="1" required inputmode="numeric"><button type="submit">Add</button></form></details>
|
||||
</div>
|
||||
{% if hydration_error %}<p class="hydration-widget__error" role="alert">Enter a whole amount from 1 to 3000 ml.</p>{% endif %}
|
||||
<div class="hydration-widget__info">{% if hydration_last %}<span>Last: {{ hydration_last.amount_ml }} ml at {{ hydration_last_time }}</span><form method="post" action="{% url 'planner:hydration-undo' %}" hx-post="{% url 'planner:hydration-undo' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<button type="submit">Undo last</button></form>{% else %}<span>No water logged today</span>{% endif %}</div>
|
||||
<div class="hydration-widget__info">{% if hydration_last %}<span>Last manual entry: {{ hydration_last.amount_ml|floatformat:0 }} ml at {{ hydration_last_time }}</span><form method="post" action="{% url 'planner:hydration-undo' %}" hx-post="{% url 'planner:hydration-undo' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<button type="submit">Undo last</button></form>{% else %}<span>No manual water logged today</span>{% endif %}</div>
|
||||
{% endif %}
|
||||
<div class="hydration-widget__week"><p>This week</p><div class="hydration-widget__days">{% for day in hydration_days %}<span class="hydration-widget__day hydration-widget__day--{{ day.state }}{% if day.today %} hydration-widget__day--today{% endif %}" title="{{ day.date|date:'l' }}: {{ day.total }} ml, {{ day.state_label }}" aria-label="{{ day.date|date:'l' }}: {{ day.total }} ml, {{ day.state_label }}">{{ day.label }}</span>{% endfor %}</div></div>
|
||||
</article>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<section class="settings-card"><h2>First-run help</h2><p>{% if onboarding_enabled %}The guided tour is ready to continue on your dashboard.{% else %}Help is off. You can run the tour again whenever you want.{% endif %}</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="onboarding"><button class="button" type="submit" name="action" value="restart">Run feature tour</button><button class="text-link" type="submit" name="action" value="disable">Turn help off</button></form></section>
|
||||
<section class="settings-card"><h2>Location & weather</h2><p>Location is optional and private. It is used only to retrieve your forecast.</p><form method="post" data-geolocation-form>{% csrf_token %}<input type="hidden" name="section" value="location">{% for field in profile_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button button--secondary" type="button" data-use-location>Use my current location</button><span data-location-status role="status"></span><button class="button" type="submit">Save location</button></form></section>
|
||||
<section class="settings-card"><h2>Sick Day Mode</h2><p>Temporarily defer routine work while you recover.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="sick-day">{% for field in sick_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Enable Sick Day Mode</strong><small>Give routine tasks a rest while you recover.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save Sick Day settings</button></form></section>
|
||||
<section class="settings-card"><h2>Hydration</h2><p>Set your daily water goal.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="hydration">{% for field in hydration_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save water goal</button></form></section>
|
||||
<section class="settings-card"><h2>Hydration</h2><p>Set your daily fluid goal and how drinks are counted.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="hydration">{% for field in hydration_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save hydration settings</button></form></section>
|
||||
<section class="settings-card"><h2>Food</h2><p>Set optional daily nutrition goals. Exercise calories do not change these goals.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="food">{% for field in food_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save food goals</button></form></section>
|
||||
<section class="settings-card"><h2>API access</h2><p>Create scoped tokens for apps that need access to your food log or kitchen inventory.</p><a class="button" href="{% url 'food:tokens' %}">Manage API tokens</a></section>
|
||||
<section class="settings-card" aria-labelledby="ntfy-title">
|
||||
|
||||
@@ -8,7 +8,7 @@ from .views import (
|
||||
TaskUpdateView, WorkoutCreateView, WorkoutUpdateView, delete_workout, fasting_configure, neck_headache_checkin_panel,
|
||||
fasting_toggle_tracking, fasting_widget, logout_view, register, toggle_task_active, toggle_task_completed,
|
||||
save_neck_headache_checkin, save_sleep_checkin, advance_onboarding, toggle_workout_completed, user_settings, workout_today,
|
||||
bowel_health_panel, save_bowel_health_checkin, toggle_tooth_brushing, hydration_add, hydration_undo, test_ntfy, gitea_activity,
|
||||
bowel_health_panel, save_bowel_health_checkin, toggle_tooth_brushing, hydration_add, hydration_undo, hydration_panel, test_ntfy, gitea_activity,
|
||||
)
|
||||
|
||||
app_name = 'planner'
|
||||
@@ -33,6 +33,7 @@ urlpatterns = [
|
||||
path('teeth/toggle/', toggle_tooth_brushing, name='tooth-brushing-toggle'),
|
||||
path('hydration/add/', hydration_add, name='hydration-add'),
|
||||
path('hydration/undo/', hydration_undo, name='hydration-undo'),
|
||||
path('hydration/panel/', hydration_panel, name='hydration-panel'),
|
||||
path('bowel-health/panel/', bowel_health_panel, name='bowel-health-panel'),
|
||||
path('bowel-health/save/', save_bowel_health_checkin, name='bowel-health-save'),
|
||||
path('check-ins/export/<str:period>/', export_pain_csv, name='pain-export'),
|
||||
|
||||
+12
-2
@@ -14,7 +14,7 @@ from django.urls import reverse, reverse_lazy
|
||||
from django.utils import timezone
|
||||
from django.utils.http import url_has_allowed_host_and_scheme
|
||||
from django.utils.dateparse import parse_date
|
||||
from django.views.decorators.http import require_http_methods, require_POST
|
||||
from django.views.decorators.http import require_GET, require_http_methods, require_POST
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.views.generic import CreateView, DeleteView, DetailView, ListView, TemplateView, UpdateView
|
||||
|
||||
@@ -771,7 +771,7 @@ def user_settings(request):
|
||||
hydration_goal_form = HydrationGoalForm(request.POST, instance=profile)
|
||||
if hydration_goal_form.is_valid():
|
||||
hydration_goal_form.save()
|
||||
messages.success(request, 'Your daily water goal was saved.')
|
||||
messages.success(request, 'Your hydration settings were saved.')
|
||||
return redirect('planner:user-settings')
|
||||
elif section == 'food':
|
||||
food_goal_form = FoodGoalForm(request.POST, instance=profile)
|
||||
@@ -877,6 +877,8 @@ def test_ntfy(request):
|
||||
@login_required
|
||||
@require_POST
|
||||
def hydration_add(request):
|
||||
if not UserSettings.objects.get_or_create(user=request.user)[0].allow_manual_hydration_adjustments:
|
||||
return HttpResponse(status=403)
|
||||
form = WaterIntakeForm(request.POST)
|
||||
if form.is_valid():
|
||||
WaterIntakeEntry.objects.create(user=request.user, amount_ml=form.cleaned_data['amount_ml'])
|
||||
@@ -888,12 +890,20 @@ def hydration_add(request):
|
||||
@login_required
|
||||
@require_POST
|
||||
def hydration_undo(request):
|
||||
if not UserSettings.objects.get_or_create(user=request.user)[0].allow_manual_hydration_adjustments:
|
||||
return HttpResponse(status=403)
|
||||
context = hydration_context(request.user)
|
||||
if context['hydration_last']:
|
||||
context['hydration_last'].delete()
|
||||
return render(request, 'planner/partials/hydration_widget.html', hydration_context(request.user))
|
||||
|
||||
|
||||
@login_required
|
||||
@require_GET
|
||||
def hydration_panel(request):
|
||||
return render(request, 'planner/partials/hydration_widget.html', hydration_context(request.user))
|
||||
|
||||
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def register(request):
|
||||
if request.user.is_authenticated:
|
||||
|
||||
Reference in New Issue
Block a user