Compare commits
2
Commits
400e8254c0
...
000ec834b0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
000ec834b0 | ||
|
|
cb12c23732 |
+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
|
||||
|
||||
+9
-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.
|
||||
@@ -62,6 +64,12 @@ Image interpretation belongs to the AI client. For a grocery photograph, identif
|
||||
|
||||
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.
|
||||
|
||||
## Partial inventory use
|
||||
|
||||
`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
|
||||
|
||||
+324
-12
@@ -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,15 +18,18 @@ 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)
|
||||
from .services.inventory_consumption import FACTORS, StockError, consume as consume_stock, preview as preview_stock, stock as stock_packages, undo as undo_stock
|
||||
|
||||
SCOPES = {'food:read', 'food:write', 'inventory:read', 'inventory:write'}
|
||||
NUTRIENTS = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')
|
||||
@@ -169,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):
|
||||
@@ -186,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,
|
||||
@@ -200,7 +211,10 @@ def _inventory_data(item):
|
||||
'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,
|
||||
'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()}
|
||||
|
||||
|
||||
@@ -500,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
|
||||
@@ -547,9 +562,12 @@ def inventory_list(request):
|
||||
|
||||
|
||||
def _save_inventory(request, data, item=None):
|
||||
creating = item is None
|
||||
was_count_only = item is not None and item.original_amount is None
|
||||
if item is None:
|
||||
item = KitchenInventoryItem(user=request.api_user)
|
||||
allowed = {'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'best_before', 'remaining_amount'}
|
||||
allowed = {'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'best_before', 'remaining_amount',
|
||||
'original_amount', 'unit', 'purchase_batch'}
|
||||
if set(data) - allowed:
|
||||
raise ValueError('Unknown inventory fields.')
|
||||
if 'product_id' in data:
|
||||
@@ -579,14 +597,35 @@ def _save_inventory(request, data, item=None):
|
||||
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)
|
||||
new_remaining = (_decimal(data['remaining_amount'], 'remaining_amount')
|
||||
if data['remaining_amount'] is not None else None)
|
||||
if not creating and new_remaining != item.remaining_amount:
|
||||
raise ValueError('Use inventory consumption or undo to change remaining stock.')
|
||||
item.remaining_amount = new_remaining
|
||||
if 'original_amount' in data:
|
||||
new_original = _decimal(data['original_amount'], 'original_amount') if data['original_amount'] is not None else None
|
||||
if not creating and not was_count_only and new_original != item.original_amount:
|
||||
raise ValueError('Existing package size cannot be changed.')
|
||||
item.original_amount = new_original
|
||||
if 'unit' in data:
|
||||
if not creating and not was_count_only and data['unit'] != item.inventory_unit:
|
||||
raise ValueError('Existing package unit cannot be changed.')
|
||||
item.inventory_unit = str(data['unit'])
|
||||
if 'purchase_batch' in data:
|
||||
item.purchase_batch = str(data['purchase_batch'])[:100]
|
||||
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:
|
||||
raise ValueError('product_id and location are required.')
|
||||
if creating and item.original_amount is None and item.product.package_amount:
|
||||
item.original_amount, item.inventory_unit = item.product.package_amount, item.product.package_unit
|
||||
if item.original_amount is not None and item.remaining_amount is None:
|
||||
item.remaining_amount = item.original_amount
|
||||
item.full_clean()
|
||||
item.save()
|
||||
if creating or (was_count_only and item.original_amount is not None):
|
||||
from .services.inventory_consumption import materialize_packages
|
||||
materialize_packages(item)
|
||||
return item, None
|
||||
|
||||
|
||||
@@ -601,20 +640,75 @@ def inventory_create(request):
|
||||
|
||||
@api_view('inventory:read', ('GET',))
|
||||
def inventory_detail(request, identifier):
|
||||
item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier).select_related('product', 'location', 'category').first()
|
||||
item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier,
|
||||
archived_at__isnull=True).select_related('product', 'location', 'category').first()
|
||||
return JsonResponse(_inventory_data(item)) if item else error('inventory_item_not_found', 'Inventory item not found.', 404)
|
||||
|
||||
|
||||
@api_view('inventory:write', ('PATCH', 'DELETE'))
|
||||
def inventory_change(request, identifier):
|
||||
item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier).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.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',))
|
||||
@@ -695,3 +789,221 @@ def inventory_item(request, identifier):
|
||||
if request.method == 'GET':
|
||||
return inventory_detail.__wrapped__(request, identifier)
|
||||
return inventory_change.__wrapped__(request, identifier)
|
||||
|
||||
|
||||
def _stock_product(request, identifier):
|
||||
return FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(identifier)).first()
|
||||
|
||||
|
||||
def _stock_result(plan):
|
||||
return {'requested': str(plan['requested']), 'unit': plan['unit'],
|
||||
'available': str(plan['total']), 'shortage': str(plan['shortage']),
|
||||
'deductions': [{'package_id': str(row['package'].api_id),
|
||||
'amount': str(row['amount']), 'unit': row['unit'],
|
||||
'before': str(row['before']), 'after': str(row['after'])}
|
||||
for row in plan['deductions']]}
|
||||
|
||||
|
||||
@api_view('inventory:read', ('GET',))
|
||||
def inventory_stock(request):
|
||||
identifier = request.GET.get('product_id')
|
||||
if identifier:
|
||||
product = _stock_product(request, identifier)
|
||||
if product is None:
|
||||
return error('product_not_found', 'Product not found.', 404)
|
||||
products = [product]
|
||||
else:
|
||||
query = request.GET.get('query', '').strip()[:100]
|
||||
if not query:
|
||||
return error('product_required', 'Provide product_id or query.')
|
||||
products = list(FoodProduct.objects.filter(owner=request.api_user,
|
||||
inventory_items__archived_at__isnull=True).filter(
|
||||
Q(product_name__icontains=query) | Q(barcode=query)).distinct()[:20])
|
||||
result = []
|
||||
location = request.GET.get('location_id')
|
||||
for product in products:
|
||||
packages = stock_packages(request.api_user, product, location)
|
||||
groups = {}
|
||||
for item in packages:
|
||||
unit = item.inventory_unit or 'packs'
|
||||
amount = item.remaining_amount if item.remaining_amount is not None else Decimal(item.quantity)
|
||||
dimension, factor = FACTORS[unit]
|
||||
base_unit = {'mass': 'g', 'volume': 'ml'}.get(dimension, unit)
|
||||
groups[base_unit] = groups.get(base_unit, Decimal(0)) + amount * factor
|
||||
result.append({'product_id': str(product.api_id), 'product_name': product.product_name,
|
||||
'totals': {unit: str(amount) for unit, amount in groups.items()},
|
||||
'available': any(amount > 0 for amount in groups.values()),
|
||||
'packages': [_inventory_data(item) for item in packages]})
|
||||
return JsonResponse({'count': len(result), 'products': result})
|
||||
|
||||
|
||||
@api_view('inventory:read', ('POST',))
|
||||
def inventory_preview(request):
|
||||
try:
|
||||
data = _json(request)
|
||||
product = _stock_product(request, data['product_id'])
|
||||
if product is None:
|
||||
return error('product_not_found', 'Product not found.', 404)
|
||||
plan = preview_stock(request.api_user, product, data['amount'], data['unit'], data.get('package_id'))
|
||||
return JsonResponse(_stock_result(plan))
|
||||
except (StockError, KeyError, ValueError) as exc:
|
||||
return error('invalid_consumption', str(exc))
|
||||
|
||||
|
||||
@api_view('inventory:write', ('POST',))
|
||||
def inventory_consume(request):
|
||||
try:
|
||||
data = _json(request)
|
||||
product = _stock_product(request, data['product_id'])
|
||||
if product is None:
|
||||
return error('product_not_found', 'Product not found.', 404)
|
||||
key = request.headers.get('Idempotency-Key', '')
|
||||
if not key:
|
||||
return error('idempotency_key_required', 'Provide an Idempotency-Key.')
|
||||
operation = consume_stock(request.api_user, product, data['amount'], data['unit'],
|
||||
package_id=data.get('package_id'), source='mcp',
|
||||
source_reference=data.get('source_reference', ''),
|
||||
description=data.get('description', ''), idempotency_key=key,
|
||||
allow_partial=data.get('allow_partial') is True)
|
||||
return JsonResponse({'transaction_id': str(operation.pk), 'amount': str(operation.amount),
|
||||
'unit': operation.unit, 'deductions': [{'package_id': str(line.package.api_id),
|
||||
'amount': str(line.amount), 'unit': line.unit} for line in operation.lines.select_related('package')]})
|
||||
except (StockError, KeyError, ValueError) as exc:
|
||||
return error('invalid_consumption', str(exc))
|
||||
|
||||
|
||||
@api_view('inventory:write', ('POST',))
|
||||
def inventory_undo(request, identifier):
|
||||
try:
|
||||
reversal = undo_stock(request.api_user, 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
|
||||
@@ -86,6 +100,20 @@ def schema(request):
|
||||
'patch': operation('Update own inventory item', 'inventory:write', INVENTORY),
|
||||
'delete': operation('Delete own inventory item', 'inventory:write'),
|
||||
},
|
||||
'/kitchen/stock/': {'get': operation('Read product stock and packages', 'inventory:read')},
|
||||
'/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():
|
||||
@@ -94,11 +122,19 @@ def schema(request):
|
||||
'schema': {'type': 'string', 'format': 'uuid'}}]
|
||||
if 'post' in methods:
|
||||
methods['post']['responses']['201'] = methods['post']['responses'].pop('200')
|
||||
for path in ('/kitchen/consumption/preview/', '/kitchen/consumption/',
|
||||
'/kitchen/consumption/{id}/undo/'):
|
||||
document['paths'][path]['post']['responses']['200'] = document['paths'][path]['post']['responses'].pop('201')
|
||||
document['paths']['/food/today/']['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']['/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'}),
|
||||
|
||||
@@ -17,4 +17,12 @@ urlpatterns = [
|
||||
path('kitchen/items/', api.inventory_collection),
|
||||
path('kitchen/import-groceries/', api.inventory_import_groceries),
|
||||
path('kitchen/items/<uuid:identifier>/', api.inventory_item),
|
||||
path('kitchen/stock/', api.inventory_stock),
|
||||
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),
|
||||
]
|
||||
|
||||
+31
-1
@@ -141,22 +141,52 @@ 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'}))
|
||||
|
||||
class Meta:
|
||||
model = KitchenInventoryItem
|
||||
fields = ('quantity', 'opened', 'best_before', 'notes')
|
||||
fields = ('quantity', 'original_amount', 'inventory_unit', 'opened', 'best_before', 'notes')
|
||||
widgets = {'quantity': forms.NumberInput(attrs={'min': 1, 'step': 1}),
|
||||
'original_amount': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}),
|
||||
'best_before': forms.DateInput(attrs={'type': 'date'}),
|
||||
'notes': forms.Textarea(attrs={'rows': 2})}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['inventory_unit'] = forms.ChoiceField(required=False, label='Package unit',
|
||||
choices=[('', 'Count only (unknown size)')] + [(unit, unit) for unit in
|
||||
('mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions')])
|
||||
self.fields['original_amount'].label = 'Amount per package'
|
||||
if self.instance.pk:
|
||||
self.fields['location_name'].initial = self.instance.location.name
|
||||
self.fields['category_name'].initial = self.instance.category.name if self.instance.category else ''
|
||||
self.fields['inventory_unit'].initial = self.instance.inventory_unit
|
||||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
if bool(data.get('original_amount')) != bool(data.get('inventory_unit')):
|
||||
raise forms.ValidationError('Enter both package amount and unit, or leave both blank.')
|
||||
if data.get('original_amount') and self.instance.remaining_amount is None:
|
||||
self.instance.remaining_amount = data['original_amount']
|
||||
if self.instance.pk and self.instance.original_amount and data.get('original_amount') != self.instance.original_amount:
|
||||
raise forms.ValidationError('Existing package sizes cannot be changed after tracking starts.')
|
||||
if self.instance.pk and self.instance.original_amount and data.get('inventory_unit') != self.instance.inventory_unit:
|
||||
raise forms.ValidationError('Existing package units cannot be changed after tracking starts.')
|
||||
if self.instance.pk and self.instance.original_amount and data.get('quantity') != 1:
|
||||
raise forms.ValidationError('A tracked package has a quantity of one.')
|
||||
return data
|
||||
|
||||
def clean_location_name(self):
|
||||
value = ' '.join(self.cleaned_data['location_name'].split())
|
||||
|
||||
+115
-17
@@ -1,4 +1,6 @@
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
import re
|
||||
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.decorators import login_required
|
||||
@@ -11,7 +13,8 @@ from django.utils import timezone
|
||||
from django.views.decorators.http import require_http_methods, require_POST
|
||||
|
||||
from .forms import InventoryItemForm, InventoryManualProductForm
|
||||
from .models import FoodProduct, InventoryCategory, InventoryLocation, KitchenInventoryItem
|
||||
from .models import FoodProduct, InventoryCategory, InventoryConsumption, InventoryLocation, KitchenInventoryItem
|
||||
from .services.inventory_consumption import FACTORS, StockError, consume, materialize_packages, preview, undo
|
||||
from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search
|
||||
from .services.products import local_products
|
||||
|
||||
@@ -44,9 +47,26 @@ def overview(request):
|
||||
'category': ('category__name', 'product__product_name'),
|
||||
'name': ('product__product_name',), 'recent': ('-added_at',),
|
||||
'best_before': (F('best_before').asc(nulls_last=True), 'product__product_name')}
|
||||
items = items.order_by(*orderings.get(sort, orderings['location']))
|
||||
items = list(items.order_by(*orderings.get(sort, orderings['location'])))
|
||||
cards = {}
|
||||
for item in items:
|
||||
native_unit = item.inventory_unit or 'packs'
|
||||
dimension, factor = FACTORS[native_unit]
|
||||
unit = {'mass': 'g', 'volume': 'ml'}.get(dimension, native_unit)
|
||||
key = (item.product_id, dimension)
|
||||
if key not in cards:
|
||||
choices = {'mg': ('mg', 'g', 'kg'), 'g': ('mg', 'g', 'kg'), 'kg': ('mg', 'g', 'kg'),
|
||||
'ml': ('ml', 'L'), 'L': ('ml', 'L')}
|
||||
cards[key] = {'product': item.product, 'unit': unit, 'packages': [], 'total': Decimal(0),
|
||||
'units': choices.get(unit, (unit,)),
|
||||
'count_unit': dimension in ('pieces', 'packs', 'portions')}
|
||||
cards[key]['packages'].append(item)
|
||||
cards[key]['total'] += (item.remaining_amount if item.remaining_amount is not None
|
||||
else Decimal(item.quantity)) * factor
|
||||
recent = InventoryConsumption.objects.filter(user=request.user, reverses__isnull=True).select_related('product').prefetch_related('lines__package').order_by('-created_at')[:8]
|
||||
return render(request, 'food/inventory_overview.html', {
|
||||
'items': items, 'query': query, 'sort': sort, 'selected_location': location,
|
||||
'items': items, 'cards': list(cards.values()), 'recent_consumption': recent,
|
||||
'query': query, 'sort': sort, 'selected_location': location,
|
||||
'selected_category': category, 'opened': opened, 'use_soon': request.GET.get('use_soon'),
|
||||
'locations': InventoryLocation.objects.filter(user=request.user),
|
||||
'categories': InventoryCategory.objects.filter(user=request.user),
|
||||
@@ -61,7 +81,9 @@ def add(request):
|
||||
product = get_object_or_404(FoodProduct, owner=request.user, pk=product_id) if product_id else None
|
||||
query = request.GET.get('q', '').strip()[:100]
|
||||
products = local_products(request.user, query)
|
||||
form = InventoryItemForm(request.POST or None, initial={'quantity': 1, 'location_name': request.session.get('inventory_location', '')}) if product else None
|
||||
form = InventoryItemForm(request.POST or None, initial={'quantity': 1, 'location_name': request.session.get('inventory_location', ''),
|
||||
'original_amount': product.package_amount if product else None,
|
||||
'inventory_unit': product.package_unit if product else ''}) if product else None
|
||||
existing = _owned_items(request.user).filter(product=product) if product else []
|
||||
if request.method == 'POST':
|
||||
if not product:
|
||||
@@ -75,8 +97,20 @@ def add(request):
|
||||
category, _ = InventoryCategory.objects.get_or_create(user=request.user, name__iexact=category_name, defaults={'name': category_name})
|
||||
item = form.save(commit=False)
|
||||
item.user, item.product, item.location, item.category = request.user, product, location, category
|
||||
if item.original_amount is not None:
|
||||
item.remaining_amount = item.original_amount
|
||||
if item.quantity > 1:
|
||||
count = item.quantity
|
||||
item.quantity = 1
|
||||
else:
|
||||
count = 1
|
||||
else:
|
||||
count = 1
|
||||
item.full_clean()
|
||||
item.save()
|
||||
if count > 1:
|
||||
item.quantity = count
|
||||
materialize_packages(item)
|
||||
request.session['inventory_location'] = location.name
|
||||
messages.success(request, f'{product.product_name} added. Scan the next item when ready.')
|
||||
return redirect('food:inventory-add')
|
||||
@@ -127,6 +161,15 @@ def manual(request):
|
||||
if request.method == 'POST' and form.is_valid():
|
||||
product = form.save(commit=False)
|
||||
product.owner = request.user
|
||||
match = re.fullmatch(r'\s*(\d+(?:[.,]\d+)?)\s*(kg|g|ml|l)\s*', product.package_quantity, re.I)
|
||||
if match:
|
||||
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') and amount == amount.quantize(Decimal('.001')):
|
||||
product.package_amount, product.package_unit = amount, unit
|
||||
product.save()
|
||||
return redirect(f"{reverse('food:inventory-add')}?product={product.pk}")
|
||||
return render(request, 'food/inventory_manual.html', {'form': form})
|
||||
@@ -136,6 +179,7 @@ def manual(request):
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def edit(request, pk):
|
||||
item = get_object_or_404(_owned_items(request.user), pk=pk)
|
||||
was_count_only = item.original_amount is None
|
||||
form = InventoryItemForm(request.POST or None, instance=item)
|
||||
if request.method == 'POST' and form.is_valid():
|
||||
with transaction.atomic():
|
||||
@@ -146,8 +190,12 @@ def edit(request, pk):
|
||||
category, _ = InventoryCategory.objects.get_or_create(user=request.user, name__iexact=category_name, defaults={'name': category_name})
|
||||
item = form.save(commit=False)
|
||||
item.location, item.category = location, category
|
||||
if item.original_amount is not None and item.remaining_amount is None:
|
||||
item.remaining_amount = item.original_amount
|
||||
item.full_clean()
|
||||
item.save()
|
||||
if was_count_only and item.original_amount is not None:
|
||||
materialize_packages(item)
|
||||
return redirect('food:inventory')
|
||||
return render(request, 'food/inventory_edit.html', {'item': item, 'form': form,
|
||||
'locations': InventoryLocation.objects.filter(user=request.user),
|
||||
@@ -157,20 +205,27 @@ def edit(request, pk):
|
||||
@login_required
|
||||
@require_POST
|
||||
def change_quantity(request, pk):
|
||||
action = request.POST.get('action')
|
||||
if action == 'used':
|
||||
item = get_object_or_404(_owned_items(request.user), pk=pk)
|
||||
try:
|
||||
consume(request.user, item.product, item.remaining_amount if item.original_amount is not None else 1,
|
||||
item.inventory_unit or 'packs', package_id=item.api_id)
|
||||
messages.success(request, f'{item.product.product_name} used.')
|
||||
except StockError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return redirect('food:inventory')
|
||||
if action != 'increase':
|
||||
return HttpResponseBadRequest('Invalid action.')
|
||||
with transaction.atomic():
|
||||
item = get_object_or_404(KitchenInventoryItem.objects.select_for_update(), pk=pk, user=request.user, archived_at__isnull=True)
|
||||
action = request.POST.get('action')
|
||||
if action == 'increase':
|
||||
item.quantity += 1
|
||||
elif action == 'used':
|
||||
if item.quantity == 1:
|
||||
item.archived_at = timezone.now()
|
||||
messages.success(request, f'{item.product.product_name} used up.')
|
||||
else:
|
||||
item.quantity -= 1
|
||||
if item.original_amount is not None:
|
||||
KitchenInventoryItem.objects.create(user=item.user, product=item.product, location=item.location,
|
||||
category=item.category, original_amount=item.original_amount, remaining_amount=item.original_amount,
|
||||
inventory_unit=item.inventory_unit, best_before=item.best_before)
|
||||
else:
|
||||
return HttpResponseBadRequest('Invalid action.')
|
||||
item.save()
|
||||
item.quantity += 1
|
||||
item.save(update_fields=('quantity', 'updated_at'))
|
||||
return redirect('food:inventory')
|
||||
|
||||
|
||||
@@ -179,7 +234,50 @@ def change_quantity(request, pk):
|
||||
def add_existing(request, pk):
|
||||
with transaction.atomic():
|
||||
item = get_object_or_404(KitchenInventoryItem.objects.select_for_update(), pk=pk, user=request.user, archived_at__isnull=True)
|
||||
item.quantity += 1
|
||||
item.save(update_fields=('quantity', 'updated_at'))
|
||||
if item.original_amount is not None:
|
||||
KitchenInventoryItem.objects.create(user=item.user, product=item.product, location=item.location,
|
||||
category=item.category, original_amount=item.original_amount, remaining_amount=item.original_amount,
|
||||
inventory_unit=item.inventory_unit, best_before=item.best_before)
|
||||
else:
|
||||
item.quantity += 1
|
||||
item.save(update_fields=('quantity', 'updated_at'))
|
||||
messages.success(request, f'{item.product.product_name} quantity increased.')
|
||||
return redirect('food:inventory-add')
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def preview_consumption(request, pk):
|
||||
product = get_object_or_404(FoodProduct, pk=pk, owner=request.user)
|
||||
try:
|
||||
plan = preview(request.user, product, request.POST.get('amount'),
|
||||
request.POST.get('unit'), request.POST.get('package_id') or None)
|
||||
except StockError as exc:
|
||||
return render(request, 'food/partials/inventory_preview.html', {'error': str(exc)})
|
||||
return render(request, 'food/partials/inventory_preview.html',
|
||||
{'plan': plan, 'product': product, 'package_id': request.POST.get('package_id', '')})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def use_amount(request, pk):
|
||||
product = get_object_or_404(FoodProduct, pk=pk, owner=request.user)
|
||||
try:
|
||||
operation = consume(request.user, product, request.POST.get('amount'), request.POST.get('unit'),
|
||||
package_id=request.POST.get('package_id') or None,
|
||||
allow_partial=request.POST.get('allow_partial') == 'yes')
|
||||
messages.success(request, f'Used {operation.amount} {operation.unit} of {product.product_name}.')
|
||||
except StockError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return redirect('food:inventory')
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def undo_consumption(request, identifier):
|
||||
try:
|
||||
undo(request.user, identifier)
|
||||
messages.success(request, 'Consumption undone.')
|
||||
except StockError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return redirect('food:inventory')
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# Generated by Django 6.1.1 on 2026-10-11 13:22
|
||||
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
def backfill_packages(apps, schema_editor):
|
||||
Item = apps.get_model('food', 'KitchenInventoryItem')
|
||||
for item in Item.objects.select_related('product').all().iterator():
|
||||
amount = item.product.package_amount
|
||||
unit = item.product.package_unit
|
||||
if not amount or not unit:
|
||||
continue # Unknown-size legacy entries remain count based.
|
||||
count = item.quantity
|
||||
remaining = item.remaining_amount if item.remaining_amount is not None else amount
|
||||
Item.objects.filter(pk=item.pk).update(quantity=1, original_amount=amount,
|
||||
remaining_amount=remaining, inventory_unit=unit)
|
||||
for _ in range(count - 1):
|
||||
copy = Item.objects.create(user_id=item.user_id, product_id=item.product_id, quantity=1,
|
||||
location_id=item.location_id, category_id=item.category_id, notes=item.notes,
|
||||
opened=False, original_amount=amount, remaining_amount=amount,
|
||||
inventory_unit=unit, best_before=item.best_before, archived_at=item.archived_at)
|
||||
Item.objects.filter(pk=copy.pk).update(added_at=item.added_at, updated_at=item.updated_at)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('food', '0005_package_contents'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='kitcheninventoryitem',
|
||||
name='inventory_unit',
|
||||
field=models.CharField(blank=True, max_length=8),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='kitcheninventoryitem',
|
||||
name='opened_at',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='kitcheninventoryitem',
|
||||
name='original_amount',
|
||||
field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0.001)]),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='kitcheninventoryitem',
|
||||
name='purchase_batch',
|
||||
field=models.CharField(blank=True, max_length=100),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='InventoryConsumption',
|
||||
fields=[
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
||||
('amount', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(0.001)])),
|
||||
('unit', models.CharField(max_length=8)),
|
||||
('source', models.CharField(choices=[('manual', 'Manual'), ('mcp', 'MCP'), ('recipe', 'Recipe')], max_length=16)),
|
||||
('source_reference', models.CharField(blank=True, max_length=255)),
|
||||
('description', models.CharField(blank=True, max_length=255)),
|
||||
('idempotency_key', models.CharField(blank=True, max_length=128)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('product', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='food.foodproduct')),
|
||||
('reverses', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='reversal', to='food.inventoryconsumption')),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='InventoryConsumptionLine',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('amount', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(0.001)])),
|
||||
('unit', models.CharField(max_length=8)),
|
||||
('before_amount', models.DecimalField(decimal_places=3, max_digits=10)),
|
||||
('after_amount', models.DecimalField(decimal_places=3, max_digits=10)),
|
||||
('package', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='consumption_lines', to='food.kitcheninventoryitem')),
|
||||
('transaction', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines', to='food.inventoryconsumption')),
|
||||
],
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='inventoryconsumption',
|
||||
constraint=models.UniqueConstraint(condition=models.Q(('idempotency_key', ''), _negated=True), fields=('user', 'idempotency_key'), name='food_unique_consumption_key'),
|
||||
),
|
||||
migrations.RunPython(backfill_packages, migrations.RunPython.noop),
|
||||
]
|
||||
@@ -0,0 +1,28 @@
|
||||
# Generated by Django 6.1.1 on 2026-10-11 13:27
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('food', '0006_inventory_packages_consumption'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='inventoryconsumption',
|
||||
name='request_signature',
|
||||
field=models.CharField(blank=True, max_length=64),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='inventoryconsumptionline',
|
||||
name='before_opened',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='inventoryconsumptionline',
|
||||
name='before_opened_at',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
]
|
||||
@@ -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)]
|
||||
+71
-5
@@ -2,9 +2,10 @@ 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
|
||||
|
||||
|
||||
NON_NEGATIVE = [MinValueValidator(0)]
|
||||
@@ -37,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)
|
||||
@@ -75,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)
|
||||
@@ -172,6 +182,10 @@ class KitchenInventoryItem(models.Model):
|
||||
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)
|
||||
original_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
|
||||
inventory_unit = models.CharField(max_length=8, blank=True)
|
||||
opened_at = models.DateTimeField(null=True, blank=True)
|
||||
purchase_batch = models.CharField(max_length=100, blank=True)
|
||||
best_before = models.DateField(null=True, blank=True)
|
||||
archived_at = models.DateTimeField(null=True, blank=True)
|
||||
added_at = models.DateTimeField(auto_now_add=True)
|
||||
@@ -179,10 +193,16 @@ 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.original_amount is None) != (self.remaining_amount is None):
|
||||
raise ValidationError('Original and remaining quantities must be supplied together.')
|
||||
was_count_only = self.pk and KitchenInventoryItem.objects.filter(pk=self.pk, original_amount__isnull=True).exists()
|
||||
if self.original_amount is not None and ((self.pk is not None and self.quantity != 1 and not was_count_only) or
|
||||
self.inventory_unit not in ('mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions') or
|
||||
self.remaining_amount > self.original_amount):
|
||||
raise ValidationError('A package needs one valid unit and remaining quantity within its original quantity.')
|
||||
if (self.original_amount is not None and self.remaining_amount is not None and
|
||||
0 < self.remaining_amount < self.original_amount and not self.opened):
|
||||
raise ValidationError({'opened': 'A partly used package must be opened.'})
|
||||
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:
|
||||
@@ -190,6 +210,52 @@ class KitchenInventoryItem(models.Model):
|
||||
if self.user_id and self.category_id and self.category.user_id != self.user_id:
|
||||
raise ValidationError({'category': 'Choose one of your own categories.'})
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if self.opened and self.opened_at is None:
|
||||
self.opened_at = timezone.now()
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
@property
|
||||
def percentage_remaining(self):
|
||||
if self.original_amount:
|
||||
return int(self.remaining_amount * 100 / self.original_amount)
|
||||
return 100
|
||||
|
||||
@property
|
||||
def package_status(self):
|
||||
if self.remaining_amount == 0:
|
||||
return 'depleted'
|
||||
return 'opened' if self.opened else 'unopened'
|
||||
|
||||
|
||||
class InventoryConsumption(models.Model):
|
||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||||
product = models.ForeignKey(FoodProduct, on_delete=models.PROTECT)
|
||||
amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE)
|
||||
unit = models.CharField(max_length=8)
|
||||
source = models.CharField(max_length=16, choices=[('manual', 'Manual'), ('mcp', 'MCP'), ('recipe', 'Recipe')])
|
||||
source_reference = models.CharField(max_length=255, blank=True)
|
||||
description = models.CharField(max_length=255, blank=True)
|
||||
idempotency_key = models.CharField(max_length=128, blank=True)
|
||||
request_signature = models.CharField(max_length=64, blank=True)
|
||||
reverses = models.OneToOneField('self', on_delete=models.PROTECT, null=True, blank=True, related_name='reversal')
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [models.UniqueConstraint(fields=('user', 'idempotency_key'), condition=~Q(idempotency_key=''), name='food_unique_consumption_key')]
|
||||
|
||||
|
||||
class InventoryConsumptionLine(models.Model):
|
||||
transaction = models.ForeignKey(InventoryConsumption, on_delete=models.CASCADE, related_name='lines')
|
||||
package = models.ForeignKey(KitchenInventoryItem, on_delete=models.PROTECT, related_name='consumption_lines')
|
||||
amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE)
|
||||
unit = models.CharField(max_length=8)
|
||||
before_amount = models.DecimalField(max_digits=10, decimal_places=3)
|
||||
after_amount = models.DecimalField(max_digits=10, decimal_places=3)
|
||||
before_opened = models.BooleanField(default=False)
|
||||
before_opened_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
|
||||
class PersonalAccessToken(models.Model):
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='personal_access_tokens')
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Atomic package allocation shared by the web inventory and MCP API."""
|
||||
|
||||
import hashlib
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
|
||||
from food.models import FoodProduct, InventoryConsumption, InventoryConsumptionLine, KitchenInventoryItem
|
||||
|
||||
|
||||
FACTORS = {'mg': ('mass', Decimal('.001')), 'g': ('mass', Decimal(1)),
|
||||
'kg': ('mass', Decimal(1000)), 'ml': ('volume', Decimal(1)),
|
||||
'L': ('volume', Decimal(1000)), 'pieces': ('pieces', Decimal(1)),
|
||||
'packs': ('packs', Decimal(1)), 'portions': ('portions', Decimal(1))}
|
||||
|
||||
|
||||
class StockError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def normalized(amount, unit):
|
||||
if unit not in FACTORS:
|
||||
raise StockError('Unsupported unit.')
|
||||
try:
|
||||
input_value = Decimal(str(amount))
|
||||
value = input_value * FACTORS[unit][1]
|
||||
except (InvalidOperation, TypeError):
|
||||
raise StockError('Enter a valid amount.') from None
|
||||
if (not value.is_finite() or value <= 0 or value > Decimal('9999999.999') or
|
||||
input_value != input_value.quantize(Decimal('.001')) or
|
||||
value != value.quantize(Decimal('.001'))):
|
||||
raise StockError('Enter a positive amount with at most three decimal places in the base unit.')
|
||||
if FACTORS[unit][0] in ('pieces', 'packs', 'portions') and value != value.to_integral_value():
|
||||
raise StockError('Count units must be whole numbers.')
|
||||
return value, FACTORS[unit][0]
|
||||
|
||||
|
||||
def _package_stock(item):
|
||||
if item.original_amount is None:
|
||||
return Decimal(item.quantity), 'packs', 'packs'
|
||||
unit = item.inventory_unit
|
||||
return item.remaining_amount * FACTORS[unit][1], FACTORS[unit][0], unit
|
||||
|
||||
|
||||
def stock(user, product, location_id=None, lock=False):
|
||||
if product.owner_id != user.pk:
|
||||
raise StockError('Product not found.')
|
||||
qs = KitchenInventoryItem.objects.filter(user=user, product=product, archived_at__isnull=True)
|
||||
if location_id is not None:
|
||||
qs = qs.filter(location_id=location_id)
|
||||
if lock:
|
||||
qs = qs.select_for_update()
|
||||
return list(qs.order_by('pk'))
|
||||
|
||||
|
||||
def materialize_packages(item):
|
||||
"""Turn a newly added count into separate packages when a size is known."""
|
||||
if item.original_amount is None and item.product.package_amount and item.product.package_unit:
|
||||
item.original_amount = item.product.package_amount
|
||||
item.remaining_amount = item.product.package_amount
|
||||
item.inventory_unit = item.product.package_unit
|
||||
if item.original_amount is None:
|
||||
return item
|
||||
count = item.quantity
|
||||
item.quantity = 1
|
||||
item.full_clean()
|
||||
item.save()
|
||||
for _ in range(count - 1):
|
||||
KitchenInventoryItem.objects.create(user=item.user, product=item.product, quantity=1,
|
||||
location=item.location, category=item.category, notes=item.notes, opened=False,
|
||||
original_amount=item.original_amount, remaining_amount=item.original_amount,
|
||||
inventory_unit=item.inventory_unit, best_before=item.best_before,
|
||||
purchase_batch=item.purchase_batch)
|
||||
return item
|
||||
|
||||
|
||||
def preview(user, product, amount, unit, package_id=None, location_id=None, lock=False):
|
||||
requested, dimension = normalized(amount, unit)
|
||||
items = stock(user, product, location_id, lock)
|
||||
if package_id is not None:
|
||||
items = [item for item in items if str(item.api_id) == str(package_id)]
|
||||
if not items:
|
||||
raise StockError('Package not found.')
|
||||
compatible = []
|
||||
for item in items:
|
||||
available, kind, native_unit = _package_stock(item)
|
||||
if kind == dimension and available > 0:
|
||||
compatible.append((item, available, native_unit))
|
||||
compatible.sort(key=lambda row: (not row[0].opened, row[0].best_before is None,
|
||||
row[0].best_before or timezone.datetime.max.date(),
|
||||
row[0].added_at, row[0].pk))
|
||||
total = sum((row[1] for row in compatible), Decimal(0))
|
||||
left = requested
|
||||
deductions = []
|
||||
for item, available, native_unit in compatible:
|
||||
if left <= 0:
|
||||
break
|
||||
take = min(left, available)
|
||||
native = take / FACTORS[native_unit][1]
|
||||
deductions.append({'package': item, 'amount': native, 'unit': native_unit,
|
||||
'before': available / FACTORS[native_unit][1],
|
||||
'after': (available - take) / FACTORS[native_unit][1]})
|
||||
left -= take
|
||||
factor = FACTORS[unit][1]
|
||||
return {'requested': requested / factor, 'unit': unit, 'total': total / factor,
|
||||
'shortage': max(left, Decimal(0)) / factor, 'deductions': deductions}
|
||||
|
||||
|
||||
def consume(user, product, amount, unit, *, package_id=None, source='manual',
|
||||
source_reference='', description='', idempotency_key='', allow_partial=False):
|
||||
if source not in ('manual', 'mcp', 'recipe'):
|
||||
raise StockError('Invalid source.')
|
||||
if idempotency_key and len(idempotency_key) > 128:
|
||||
raise StockError('Idempotency key is too long.')
|
||||
requested, _ = normalized(amount, unit)
|
||||
signature = hashlib.sha256(f'{product.pk}|{requested}|{unit}|{package_id or ""}|{source}|{source_reference}|{description}|{allow_partial}'.encode()).hexdigest()
|
||||
with transaction.atomic():
|
||||
# Serializes even on databases where select_for_update on inventory rows is limited.
|
||||
get_user_model().objects.select_for_update().get(pk=user.pk)
|
||||
if idempotency_key:
|
||||
previous = InventoryConsumption.objects.filter(user=user, idempotency_key=idempotency_key).first()
|
||||
if previous:
|
||||
if previous.request_signature != signature:
|
||||
raise StockError('Idempotency key was used for another request.')
|
||||
return previous
|
||||
plan = preview(user, product, amount, unit, package_id, lock=True)
|
||||
if plan['shortage'] and not allow_partial:
|
||||
raise StockError(f"Insufficient stock: shortage {plan['shortage']} {unit}.")
|
||||
if not plan['deductions']:
|
||||
raise StockError('No compatible stock available.')
|
||||
consumed = plan['requested'] - plan['shortage']
|
||||
operation = InventoryConsumption.objects.create(user=user, product=product, amount=consumed,
|
||||
unit=unit, source=source, source_reference=source_reference[:255],
|
||||
description=description[:255], idempotency_key=idempotency_key, request_signature=signature)
|
||||
for deduction in plan['deductions']:
|
||||
item = deduction['package']
|
||||
before_opened, before_opened_at = item.opened, item.opened_at
|
||||
if item.original_amount is None:
|
||||
item.quantity = int(deduction['after']) or 1
|
||||
else:
|
||||
item.remaining_amount = deduction['after']
|
||||
if deduction['after'] == 0:
|
||||
item.archived_at = timezone.now()
|
||||
elif not item.opened:
|
||||
item.opened = True
|
||||
item.opened_at = timezone.now()
|
||||
item.save(update_fields=('quantity', 'remaining_amount', 'opened', 'opened_at', 'archived_at', 'updated_at'))
|
||||
InventoryConsumptionLine.objects.create(transaction=operation, package=item,
|
||||
amount=deduction['amount'], unit=deduction['unit'], before_amount=deduction['before'],
|
||||
after_amount=deduction['after'], before_opened=before_opened,
|
||||
before_opened_at=before_opened_at)
|
||||
return operation
|
||||
|
||||
|
||||
def undo(user, operation_id):
|
||||
with transaction.atomic():
|
||||
get_user_model().objects.select_for_update().get(pk=user.pk)
|
||||
operation = InventoryConsumption.objects.filter(user=user, pk=operation_id).first()
|
||||
if not operation or operation.reverses_id or hasattr(operation, 'reversal'):
|
||||
raise StockError('Consumption cannot be undone.')
|
||||
lines = list(operation.lines.select_related('package').order_by('pk'))
|
||||
for line in lines:
|
||||
item = KitchenInventoryItem.objects.select_for_update().get(pk=line.package_id)
|
||||
current = Decimal(item.quantity) if item.original_amount is None and not item.archived_at else (
|
||||
Decimal(0) if item.original_amount is None else item.remaining_amount)
|
||||
if current != line.after_amount:
|
||||
raise StockError('Package changed since this consumption. Undo it in reverse order.')
|
||||
if item.archived_at is not None and line.after_amount != 0:
|
||||
raise StockError('Package was removed after this consumption.')
|
||||
reversal = InventoryConsumption.objects.create(user=user, product=operation.product,
|
||||
amount=operation.amount, unit=operation.unit, source=operation.source,
|
||||
description=f'Undo {operation.pk}', reverses=operation)
|
||||
for line in lines:
|
||||
item = line.package
|
||||
if item.original_amount is None:
|
||||
item.quantity = int(line.before_amount)
|
||||
else:
|
||||
item.remaining_amount = line.before_amount
|
||||
item.archived_at = None
|
||||
item.opened, item.opened_at = line.before_opened, line.before_opened_at
|
||||
item.save(update_fields=('quantity', 'remaining_amount', 'archived_at', 'opened', 'opened_at', 'updated_at'))
|
||||
InventoryConsumptionLine.objects.create(transaction=reversal, package=item,
|
||||
amount=line.amount, unit=line.unit, before_amount=line.after_amount,
|
||||
after_amount=line.before_amount)
|
||||
return reversal
|
||||
@@ -61,3 +61,6 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317}
|
||||
.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)}}
|
||||
|
||||
.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}}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Kitchen Inventory · Tasknest{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}">
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261011-packages">
|
||||
<div class="food-page inventory-page"><header class="food-heading"><div><h1>Kitchen Inventory</h1><p>What you have and where it lives.</p></div><a class="button" href="{% url 'food:inventory-add' %}">+ Add item</a></header>
|
||||
<form method="get" class="food-card inventory-filters"><label>Search<input type="search" name="q" value="{{ query }}"></label><label>Location<select name="location"><option value="">All locations</option>{% for location in locations %}<option value="{{ location.pk }}" {% if selected_location == location.pk|stringformat:'s' %}selected{% endif %}>{{ location.name }}</option>{% endfor %}</select></label><label>Category<select name="category"><option value="">All categories</option>{% for category in categories %}<option value="{{ category.pk }}" {% if selected_category == category.pk|stringformat:'s' %}selected{% endif %}>{{ category.name }}</option>{% endfor %}</select></label><label>Opened<select name="opened"><option value="">All</option><option value="yes" {% if opened == 'yes' %}selected{% endif %}>Opened</option><option value="no" {% if opened == 'no' %}selected{% endif %}>Unopened</option></select></label><label>Sort<select name="sort"><option value="location" {% if sort == 'location' %}selected{% endif %}>Location</option><option value="category" {% if sort == 'category' %}selected{% endif %}>Category</option><option value="name" {% if sort == 'name' %}selected{% endif %}>Product name</option><option value="recent" {% if sort == 'recent' %}selected{% endif %}>Recently added</option><option value="best_before" {% if sort == 'best_before' %}selected{% endif %}>Best before</option></select></label><label class="inventory-check"><input type="checkbox" name="use_soon" value="1" {% if use_soon == '1' %}checked{% endif %}> Use soon</label><button class="button" type="submit">Apply</button></form>
|
||||
{% for item in items %}{% if sort == 'location' %}{% ifchanged item.location_id %}<h2 class="inventory-group">{{ item.location.name }}</h2>{% endifchanged %}{% endif %}<article class="food-card inventory-row">{% if item.product.image_url %}<img src="{{ item.product.image_url }}" alt="" loading="lazy">{% endif %}<div class="inventory-row-main"><h3>{{ item.product.product_name }}</h3>{% if item.product.brand %}<p>{{ item.product.brand }}</p>{% endif %}<p>Qty: {{ item.quantity }} · {{ item.location.name }}{% if item.category %} · {{ item.category.name }}{% endif %}</p>{% if item.opened %}<span class="inventory-tag">Opened</span>{% endif %}{% if item.best_before %}<span class="inventory-tag {% if item.best_before < today %}inventory-expired{% elif item.best_before <= soon_date %}inventory-soon{% endif %}">{% if item.best_before < today %}Expired{% elif item.best_before <= soon_date %}Use soon{% else %}Best before{% endif %} {{ item.best_before }}</span>{% endif %}</div><div class="inventory-row-actions"><form method="post" action="{% url 'food:inventory-quantity' item.pk %}">{% csrf_token %}<button type="submit" name="action" value="increase" aria-label="Increase quantity of {{ item.product.product_name }}">+1</button><button type="submit" name="action" value="used">Used up</button></form><a href="{% url 'food:inventory-edit' item.pk %}">Edit</a></div></article>{% empty %}<section class="food-card"><p>No inventory items found.</p><a class="button" href="{% url 'food:inventory-add' %}">Add your first item</a></section>{% endfor %}</div>{% endblock %}
|
||||
{% for card in cards %}<article class="food-card inventory-product-card">
|
||||
<div class="inventory-product-heading">{% if card.product.image_url %}<img src="{{ card.product.image_url }}" alt="" loading="lazy">{% endif %}<div><h2>{{ card.product.product_name }}</h2>{% if card.product.brand %}<p>{{ card.product.brand }}</p>{% endif %}<p><strong>{{ card.total|floatformat:-3 }} {% if card.unit == "packs" and card.total == 1 %}pack{% else %}{{ card.unit }}{% endif %} remaining</strong> · {{ card.packages|length }} package{{ card.packages|length|pluralize }}</p></div></div>
|
||||
<details class="inventory-packages"><summary>View packages</summary><div class="inventory-package-list">{% for item in card.packages %}<div class="inventory-package"><div class="inventory-package-fill" role="img" aria-label="{{ item.percentage_remaining }}% remaining"><span style="height:{{ item.percentage_remaining }}%"></span></div><div><strong>Pack {{ forloop.counter }} · {{ item.package_status|title }}</strong><p>{% if item.original_amount %}{{ item.remaining_amount|floatformat:-3 }} / {{ item.original_amount|floatformat:-3 }} {{ item.inventory_unit }} · {{ item.percentage_remaining }}% remaining{% else %}{{ item.quantity }} pack{{ item.quantity|pluralize }} · size unknown{% endif %}</p><small>{{ item.location.name }}{% if item.category %} · {{ item.category.name }}{% endif %}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}</small><div><a href="{% url 'food:inventory-edit' item.pk %}">Edit package</a></div></div></div>{% endfor %}</div></details>
|
||||
<details class="inventory-use"><summary>Use amount</summary><form method="post" action="{% url 'food:inventory-preview' card.product.pk %}" hx-post="{% url 'food:inventory-preview' card.product.pk %}" hx-target="#inventory-preview-{{ card.product.pk }}-{{ card.unit }}" hx-swap="innerHTML" class="inventory-use-form">{% csrf_token %}<label>Amount<input type="number" name="amount" min="{% if card.count_unit %}1{% else %}0.001{% endif %}" step="{% if card.count_unit %}1{% else %}0.001{% endif %}" required inputmode="decimal"></label><label>Unit<select name="unit">{% for unit in card.units %}<option value="{{ unit }}" {% if unit == card.unit %}selected{% endif %}>{{ unit }}</option>{% endfor %}</select></label><label>Package (optional)<select name="package_id"><option value="">Automatic selection</option>{% for item in card.packages %}<option value="{{ item.api_id }}">Pack {{ forloop.counter }} · {% if item.remaining_amount is not None %}{{ item.remaining_amount|floatformat:-3 }} {{ item.inventory_unit }}{% else %}{{ item.quantity }} pack{{ item.quantity|pluralize }}{% endif %}</option>{% endfor %}</select></label><button class="button button--secondary" type="submit">Preview</button></form><div id="inventory-preview-{{ card.product.pk }}-{{ card.unit }}" aria-live="polite"></div></details>
|
||||
</article>{% empty %}<section class="food-card"><p>No inventory items found.</p><a class="button" href="{% url 'food:inventory-add' %}">Add your first item</a></section>{% endfor %}
|
||||
{% if recent_consumption %}<section class="food-card inventory-history"><h2>Recent use</h2><ul>{% for entry in recent_consumption %}<li>{{ entry.created_at|date:'j M, H:i' }} · {{ entry.product.product_name }} · {{ entry.amount|floatformat:-3 }} {{ entry.unit }}<details><summary>Package changes</summary><ul>{% for line in entry.lines.all %}<li>Pack {{ line.package.pk }}: {{ line.before_amount|floatformat:-3 }} → {{ line.after_amount|floatformat:-3 }} {{ line.unit }}</li>{% endfor %}</ul></details>{% if not entry.reversal %}<form method="post" action="{% url 'food:inventory-undo' entry.pk %}">{% csrf_token %}<button type="submit">Undo</button></form>{% else %} · Undone{% endif %}</li>{% endfor %}</ul></section>{% endif %}
|
||||
</div>{% endblock %}
|
||||
|
||||
@@ -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 @@
|
||||
{% if error %}<p role="alert">{{ error }}</p>{% elif plan %}<div class="inventory-preview"><h3>Consumption preview</h3><p>Available: {{ plan.total|floatformat:-3 }} {{ plan.unit }}</p><ul>{% for deduction in plan.deductions %}<li>{{ deduction.package.location.name }} · Pack {{ deduction.package.pk }}: −{{ deduction.amount|floatformat:-3 }} {{ deduction.unit }} ({{ deduction.after|floatformat:-3 }} left)</li>{% endfor %}</ul>{% if plan.shortage %}<p role="alert">Shortage: {{ plan.shortage|floatformat:-3 }} {{ plan.unit }}. Choose a partial use explicitly or cancel.</p>{% endif %}<form method="post" action="{% url 'food:inventory-use' product.pk %}">{% csrf_token %}<input type="hidden" name="amount" value="{{ plan.requested }}"><input type="hidden" name="unit" value="{{ plan.unit }}"><input type="hidden" name="package_id" value="{{ package_id }}">{% if plan.shortage %}<label><input type="checkbox" name="allow_partial" value="yes" required> Use only the available amount</label>{% endif %}<button class="button" type="submit" {% if not plan.deductions %}disabled{% endif %}>Confirm use</button><button type="button" onclick="this.closest('.inventory-preview').remove()">Cancel</button></form></div>{% endif %}
|
||||
@@ -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 %}
|
||||
+173
-4
@@ -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'})
|
||||
@@ -186,14 +269,100 @@ class FoodApiTests(TestCase):
|
||||
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),
|
||||
created = 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)
|
||||
self.assertEqual(created.status_code, 201)
|
||||
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a, product=product).count(), 2)
|
||||
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_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')
|
||||
location = InventoryLocation.objects.create(user=self.a, name='Fridge')
|
||||
for _ in range(2):
|
||||
KitchenInventoryItem.objects.create(user=self.a, product=product, location=location,
|
||||
original_amount=Decimal('250'), remaining_amount=Decimal('250'), inventory_unit='g')
|
||||
base = '/api/v1/kitchen/'
|
||||
stock = self.call('get', f'{base}stock/?product_id={product.api_id}').json()
|
||||
self.assertEqual(stock['products'][0]['totals'], {'g': '500.000'})
|
||||
payload = {'product_id': str(product.api_id), 'amount': '300', 'unit': 'g'}
|
||||
preview = self.call('post', f'{base}consumption/preview/', payload).json()
|
||||
self.assertEqual([row['amount'] for row in preview['deductions']], ['250.000', '50.000'])
|
||||
self.assertEqual(self.call('post', f'{base}consumption/', payload).status_code, 400)
|
||||
result = self.call('post', f'{base}consumption/', payload, HTTP_IDEMPOTENCY_KEY='stock-1')
|
||||
self.assertEqual(result.status_code, 200, result.content)
|
||||
again = self.call('post', f'{base}consumption/', payload, HTTP_IDEMPOTENCY_KEY='stock-1')
|
||||
self.assertEqual(result.json(), again.json())
|
||||
self.assertEqual(self.call('get', f'{base}stock/?product_id={product.api_id}').json()['products'][0]['totals'], {'g': '200.000'})
|
||||
self.assertEqual(self.call('post', f'{base}consumption/{result.json()["transaction_id"]}/undo/', {}).status_code, 200)
|
||||
self.assertEqual(self.call('get', f'{base}stock/?product_id={product.api_id}').json()['products'][0]['totals'], {'g': '500.000'})
|
||||
self.assertEqual(self.call('get', f'{base}stock/?product_id={self.product_b.api_id}').status_code, 404)
|
||||
_, read_secret = create_token(self.a, 'Inventory read', ['inventory:read'])
|
||||
self.assertEqual(self.call('post', f'{base}consumption/preview/', payload, token=read_secret).status_code, 200)
|
||||
self.assertEqual(self.call('post', f'{base}consumption/', payload, token=read_secret,
|
||||
HTTP_IDEMPOTENCY_KEY='read-cannot-write').status_code, 403)
|
||||
|
||||
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')
|
||||
|
||||
@@ -4,7 +4,7 @@ from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from .models import FoodProduct, KitchenInventoryItem
|
||||
from .models import FoodProduct, InventoryLocation, KitchenInventoryItem
|
||||
|
||||
|
||||
class KitchenInventoryTests(TestCase):
|
||||
@@ -43,3 +43,28 @@ class KitchenInventoryTests(TestCase):
|
||||
product = FoodProduct.objects.get(owner=self.user, product_name='Loose onions')
|
||||
self.assertRedirects(response, f"{reverse('food:inventory-add')}?product={product.pk}", fetch_redirect_response=False)
|
||||
self.assertContains(self.client.get(reverse('food:add'), {'q': 'Loose onions'}), 'Loose onions')
|
||||
|
||||
def test_manual_product_size_creates_independent_packages(self):
|
||||
self.client.post(reverse('food:inventory-manual'), {'product_name': 'Butter block',
|
||||
'brand': '', 'barcode': '', 'package_quantity': '250 g'})
|
||||
product = FoodProduct.objects.get(owner=self.user, product_name='Butter block')
|
||||
self.assertEqual((product.package_amount, product.package_unit), (250, 'g'))
|
||||
response = self.client.post(reverse('food:inventory-add'), {'product': product.pk,
|
||||
'quantity': 2, 'original_amount': '250', 'inventory_unit': 'g',
|
||||
'location_name': 'Fridge'})
|
||||
self.assertEqual(response.status_code, 302)
|
||||
self.assertEqual(list(KitchenInventoryItem.objects.filter(product=product)
|
||||
.values_list('quantity', 'original_amount', 'remaining_amount', 'inventory_unit')),
|
||||
[(1, 250, 250, 'g'), (1, 250, 250, 'g')])
|
||||
|
||||
def test_legacy_count_gets_split_when_size_is_supplied(self):
|
||||
location = InventoryLocation.objects.create(user=self.user, name='Pantry')
|
||||
item = KitchenInventoryItem.objects.create(user=self.user, product=self.product,
|
||||
location=location, quantity=3)
|
||||
response = self.client.post(reverse('food:inventory-edit', args=[item.pk]), {
|
||||
'quantity': 3, 'original_amount': '6', 'inventory_unit': 'pieces',
|
||||
'location_name': 'Pantry'})
|
||||
self.assertEqual(response.status_code, 302)
|
||||
self.assertEqual(list(KitchenInventoryItem.objects.filter(product=self.product)
|
||||
.values_list('quantity', 'original_amount', 'remaining_amount', 'inventory_unit')),
|
||||
[(1, 6, 6, 'pieces')] * 3)
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
from django.utils import timezone
|
||||
|
||||
from .models import FoodProduct, InventoryConsumption, InventoryLocation, KitchenInventoryItem
|
||||
from .services.inventory_consumption import StockError, consume, normalized, preview, undo
|
||||
|
||||
|
||||
class InventoryConsumptionTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username='stock-owner')
|
||||
self.other = get_user_model().objects.create_user(username='stock-other')
|
||||
self.product = FoodProduct.objects.create(owner=self.user, product_name='Butter', package_amount=250, package_unit='g')
|
||||
self.location = InventoryLocation.objects.create(user=self.user, name='Fridge')
|
||||
|
||||
def package(self, amount='250', remaining='250', opened=False, best_before=None):
|
||||
return KitchenInventoryItem.objects.create(user=self.user, product=self.product, location=self.location,
|
||||
original_amount=Decimal(amount), remaining_amount=Decimal(remaining), inventory_unit='g',
|
||||
opened=opened, best_before=best_before)
|
||||
|
||||
def test_partial_across_packages_and_undo(self):
|
||||
first, second = self.package(), self.package()
|
||||
one = consume(self.user, self.product, '150', 'g')
|
||||
first.refresh_from_db(); second.refresh_from_db()
|
||||
self.assertEqual((first.remaining_amount, second.remaining_amount), (Decimal('100'), Decimal('250')))
|
||||
self.assertTrue(first.opened)
|
||||
two = consume(self.user, self.product, '150', 'g')
|
||||
first.refresh_from_db(); second.refresh_from_db()
|
||||
self.assertEqual((first.remaining_amount, second.remaining_amount), (Decimal('0'), Decimal('200')))
|
||||
self.assertIsNotNone(first.archived_at)
|
||||
self.assertEqual(list(two.lines.values_list('amount', flat=True)), [Decimal('100'), Decimal('50')])
|
||||
with self.assertRaises(StockError):
|
||||
undo(self.user, one.pk)
|
||||
undo(self.user, two.pk)
|
||||
first.refresh_from_db(); second.refresh_from_db()
|
||||
self.assertEqual((first.remaining_amount, second.remaining_amount), (Decimal('100'), Decimal('250')))
|
||||
undo(self.user, one.pk)
|
||||
first.refresh_from_db()
|
||||
self.assertFalse(first.opened)
|
||||
self.assertEqual(first.remaining_amount, Decimal('250'))
|
||||
|
||||
def test_priority_shortage_and_target(self):
|
||||
late = self.package(best_before=timezone.localdate() + timezone.timedelta(days=10))
|
||||
early = self.package(best_before=timezone.localdate() + timezone.timedelta(days=1))
|
||||
opened = self.package(remaining='80', opened=True)
|
||||
plan = preview(self.user, self.product, '100', 'g')
|
||||
self.assertEqual([row['package'].pk for row in plan['deductions']], [opened.pk, early.pk])
|
||||
self.assertEqual(preview(self.user, self.product, '300', 'g', package_id=late.api_id)['shortage'], Decimal('50'))
|
||||
with self.assertRaises(StockError):
|
||||
consume(self.user, self.product, '300', 'g', package_id=late.api_id)
|
||||
late.refresh_from_db()
|
||||
self.assertEqual(late.remaining_amount, Decimal('250'))
|
||||
|
||||
def test_units_idempotency_isolation_and_validation(self):
|
||||
package = self.package()
|
||||
self.assertEqual(normalized('0.25', 'kg')[0], Decimal('250'))
|
||||
self.assertEqual(normalized('1', 'L')[0], Decimal('1000'))
|
||||
operation = consume(self.user, self.product, '.1', 'kg', idempotency_key='use-once', source='mcp')
|
||||
self.assertEqual(consume(self.user, self.product, '.1', 'kg', idempotency_key='use-once', source='mcp').pk, operation.pk)
|
||||
self.assertEqual(InventoryConsumption.objects.filter(user=self.user).count(), 1)
|
||||
with self.assertRaises(StockError):
|
||||
consume(self.user, self.product, '.2', 'kg', idempotency_key='use-once', source='mcp')
|
||||
with self.assertRaises(StockError):
|
||||
preview(self.other, self.product, 1, 'g')
|
||||
for amount, unit in [('-1', 'g'), ('0', 'g'), ('1.0001', 'g'), ('1', 'ml')]:
|
||||
if unit == 'ml':
|
||||
self.assertEqual(preview(self.user, self.product, amount, unit)['shortage'], Decimal(1))
|
||||
else:
|
||||
with self.assertRaises(StockError):
|
||||
preview(self.user, self.product, amount, unit)
|
||||
package.refresh_from_db()
|
||||
self.assertEqual(package.remaining_amount, Decimal('150'))
|
||||
|
||||
def test_count_based_legacy_stock(self):
|
||||
item = KitchenInventoryItem.objects.create(user=self.user, product=self.product, location=self.location, quantity=3)
|
||||
operation = consume(self.user, self.product, 2, 'packs')
|
||||
item.refresh_from_db()
|
||||
self.assertEqual(item.quantity, 1)
|
||||
undo(self.user, operation.pk)
|
||||
item.refresh_from_db()
|
||||
self.assertEqual(item.quantity, 3)
|
||||
|
||||
def test_volume_count_and_explicit_partial_use(self):
|
||||
milk = FoodProduct.objects.create(owner=self.user, product_name='Milk')
|
||||
carton = KitchenInventoryItem.objects.create(user=self.user, product=milk, location=self.location,
|
||||
original_amount=Decimal('1'), remaining_amount=Decimal('1'), inventory_unit='L')
|
||||
consume(self.user, milk, '250', 'ml')
|
||||
carton.refresh_from_db()
|
||||
self.assertEqual(carton.remaining_amount, Decimal('.750'))
|
||||
self.assertEqual(preview(self.user, milk, '1', 'L')['shortage'], Decimal('.250'))
|
||||
with self.assertRaises(StockError):
|
||||
consume(self.user, milk, '1', 'L')
|
||||
operation = consume(self.user, milk, '1', 'L', allow_partial=True)
|
||||
self.assertEqual(operation.amount, Decimal('.750'))
|
||||
carton.refresh_from_db()
|
||||
self.assertEqual(carton.remaining_amount, Decimal(0))
|
||||
eggs = FoodProduct.objects.create(owner=self.user, product_name='Eggs')
|
||||
box = KitchenInventoryItem.objects.create(user=self.user, product=eggs, location=self.location,
|
||||
original_amount=Decimal('6'), remaining_amount=Decimal('6'), inventory_unit='pieces')
|
||||
consume(self.user, eggs, 2, 'pieces')
|
||||
box.refresh_from_db()
|
||||
self.assertEqual(box.remaining_amount, Decimal(4))
|
||||
with self.assertRaises(StockError):
|
||||
consume(self.user, eggs, '.5', 'pieces')
|
||||
|
||||
|
||||
from django.db import connection
|
||||
from django.db.migrations.executor import MigrationExecutor
|
||||
from django.test import TransactionTestCase
|
||||
|
||||
|
||||
class InventoryMigrationTests(TransactionTestCase):
|
||||
migrate_from = ('food', '0005_package_contents')
|
||||
migrate_to = ('food', '0007_inventory_reversal_state')
|
||||
|
||||
def test_existing_counts_split_only_when_package_size_known(self):
|
||||
executor = MigrationExecutor(connection)
|
||||
executor.migrate([self.migrate_from])
|
||||
old = executor.loader.project_state([self.migrate_from]).apps
|
||||
User = old.get_model('auth', 'User')
|
||||
Product = old.get_model('food', 'FoodProduct')
|
||||
Location = old.get_model('food', 'InventoryLocation')
|
||||
Item = old.get_model('food', 'KitchenInventoryItem')
|
||||
user = User.objects.create(username='migration-stock-user')
|
||||
location = Location.objects.create(user_id=user.pk, name='Pantry')
|
||||
known = Product.objects.create(owner_id=user.pk, product_name='Butter',
|
||||
package_amount=Decimal('250'), package_unit='g')
|
||||
unknown = Product.objects.create(owner_id=user.pk, product_name='Loose eggs')
|
||||
Item.objects.create(user_id=user.pk, product_id=known.pk, location_id=location.pk,
|
||||
quantity=2, opened=True, remaining_amount=Decimal('100'))
|
||||
Item.objects.create(user_id=user.pk, product_id=unknown.pk, location_id=location.pk, quantity=6)
|
||||
executor = MigrationExecutor(connection)
|
||||
executor.migrate([self.migrate_to])
|
||||
new = executor.loader.project_state([self.migrate_to]).apps
|
||||
migrated = list(new.get_model('food', 'KitchenInventoryItem').objects.filter(
|
||||
user_id=user.pk, product_id=known.pk).order_by('pk'))
|
||||
self.assertEqual([(i.original_amount, i.remaining_amount, i.quantity, i.location_id)
|
||||
for i in migrated], [(Decimal('250'), Decimal('100'), 1, location.pk),
|
||||
(Decimal('250'), Decimal('250'), 1, location.pk)])
|
||||
legacy = new.get_model('food', 'KitchenInventoryItem').objects.get(user_id=user.pk, product_id=unknown.pk)
|
||||
self.assertEqual((legacy.quantity, legacy.original_amount), (6, None))
|
||||
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from django.db import OperationalError, close_old_connections
|
||||
|
||||
|
||||
class ConcurrentInventoryConsumptionTests(TransactionTestCase):
|
||||
def test_competing_requests_do_not_overconsume(self):
|
||||
user = get_user_model().objects.create_user(username='parallel-stock-user')
|
||||
product = FoodProduct.objects.create(owner=user, product_name='One carton')
|
||||
location = InventoryLocation.objects.create(user=user, name='Fridge')
|
||||
item = KitchenInventoryItem.objects.create(user=user, product=product, location=location,
|
||||
original_amount=Decimal('100'), remaining_amount=Decimal('100'), inventory_unit='ml')
|
||||
|
||||
def use():
|
||||
close_old_connections()
|
||||
try:
|
||||
return consume(user, product, 80, 'ml').pk
|
||||
except (StockError, OperationalError):
|
||||
return None
|
||||
finally:
|
||||
close_old_connections()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
results = list(pool.map(lambda _: use(), range(2)))
|
||||
item.refresh_from_db()
|
||||
self.assertEqual(sum(result is not None for result in results), 1)
|
||||
self.assertEqual(item.remaining_amount, Decimal('20'))
|
||||
self.assertEqual(InventoryConsumption.objects.filter(user=user).count(), 1)
|
||||
@@ -15,6 +15,9 @@ urlpatterns = [
|
||||
path('inventory/<int:pk>/edit/', inventory.edit, name='inventory-edit'),
|
||||
path('inventory/<int:pk>/quantity/', inventory.change_quantity, name='inventory-quantity'),
|
||||
path('inventory/<int:pk>/add-one/', inventory.add_existing, name='inventory-add-one'),
|
||||
path('inventory/product/<int:pk>/preview/', inventory.preview_consumption, name='inventory-preview'),
|
||||
path('inventory/product/<int:pk>/use/', inventory.use_amount, name='inventory-use'),
|
||||
path('inventory/consumption/<uuid:identifier>/undo/', inventory.undo_consumption, name='inventory-undo'),
|
||||
path('', views.diary, name='diary'),
|
||||
path('add/', views.add_food, name='add'),
|
||||
path('search/openfoodfacts/', views.external_search, name='external-search'),
|
||||
@@ -26,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.')
|
||||
@@ -384,6 +399,67 @@ def create_server() -> MCPServer:
|
||||
await api_request('DELETE', f'kitchen/items/{item_id}/')
|
||||
return {'success': True, 'removed_item_id': item_id}
|
||||
|
||||
@server.tool(structured_output=True, description='Read stock for an owned product ID or search query, optionally limited to a location ID. Returns package details and remaining totals. Does not change stock.')
|
||||
async def inventory_get_stock(product_id: str | None = None, query: str | None = None,
|
||||
location_id: int | None = None) -> dict[str, Any]:
|
||||
params = {'product_id': product_id, 'query': query, 'location_id': location_id}
|
||||
return await api_request('GET', 'kitchen/stock/', params={k: v for k, v in params.items() if v is not None})
|
||||
|
||||
@server.tool(structured_output=True, description='Preview exact package deductions for one owned product without changing stock. A shortage is reported rather than silently consumed.')
|
||||
async def inventory_preview_consumption(product_id: str, amount: Decimal, unit: str,
|
||||
package_id: str | None = None) -> dict[str, Any]:
|
||||
return await api_request('POST', 'kitchen/consumption/preview/', payload={
|
||||
'product_id': product_id, 'amount': str(amount), 'unit': unit, 'package_id': package_id})
|
||||
|
||||
@server.tool(structured_output=True, description='Consume an exact quantity from owned inventory packages atomically. Requires a unique idempotency key. If stock is short, preview first and use allow_partial only with explicit user choice.')
|
||||
async def inventory_consume(product_id: str, amount: Decimal, unit: str, idempotency_key: str,
|
||||
package_id: str | None = None, source_reference: str = '',
|
||||
description: str = '', allow_partial: bool = False) -> dict[str, Any]:
|
||||
return await api_request('POST', 'kitchen/consumption/', payload={
|
||||
'product_id': product_id, 'amount': str(amount), 'unit': unit,
|
||||
'package_id': package_id, 'source_reference': source_reference,
|
||||
'description': description, 'allow_partial': allow_partial},
|
||||
idempotency_key=idempotency_key)
|
||||
|
||||
@server.tool(structured_output=True, description='Undo a previous owned inventory consumption transaction when its affected packages have not changed since. Records an auditable reversal.')
|
||||
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), 16)
|
||||
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
|
||||
@@ -253,5 +307,19 @@ class McpHttpTests(LiveServerTestCase):
|
||||
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)
|
||||
self.assertEqual((await client.call_tool('inventory_list')).structured_content['count'], 2)
|
||||
stock = (await client.call_tool('inventory_get_stock', {'product_id': created['product_id']})).structured_content
|
||||
self.assertEqual(stock['products'][0]['totals']['ml'], '2000.000')
|
||||
preview = (await client.call_tool('inventory_preview_consumption', {
|
||||
'product_id': created['product_id'], 'amount': '1250', 'unit': 'ml'})).structured_content
|
||||
self.assertEqual([row['amount'] for row in preview['deductions']], ['1000.000', '250.000'])
|
||||
used = (await client.call_tool('inventory_consume', {
|
||||
'product_id': created['product_id'], 'amount': '1250', 'unit': 'ml',
|
||||
'idempotency_key': 'mcp-use-oat'})).structured_content
|
||||
self.assertEqual(used['amount'], '1250.000')
|
||||
self.assertEqual((await client.call_tool('inventory_get_stock', {
|
||||
'product_id': created['product_id']})).structured_content['products'][0]['totals']['ml'], '750.000')
|
||||
undone = (await client.call_tool('inventory_undo_consumption', {
|
||||
'transaction_id': used['transaction_id']})).structured_content
|
||||
self.assertEqual(undone['reverses'], used['transaction_id'])
|
||||
asyncio.run(self._client(self.secret, check))
|
||||
|
||||
@@ -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