latest changes
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import get_object_or_404
|
||||
|
||||
from food.api import _idempotent, _json, _uuid, api_view, error
|
||||
from recipes.models import Recipe
|
||||
from .models import GroceryItem
|
||||
from .services import GroceryError, add, apply_recipe, edit, product_for, recipe_preview, search
|
||||
|
||||
|
||||
def _data(item):
|
||||
return {'id': str(item.pk), 'name': item.name, 'quantity': str(item.quantity), 'unit': item.unit,
|
||||
'category': item.category, 'product_id': str(item.product.api_id) if item.product_id else None,
|
||||
'notes': item.notes, 'status': item.status,
|
||||
'purchased_at': item.purchased_at.isoformat() if item.purchased_at else None,
|
||||
'sources': [{'recipe_id': str(source.recipe.api_id), 'recipe_title': source.recipe.title,
|
||||
'ingredient_id': source.ingredient_id} for source in item.sources.all()]}
|
||||
|
||||
|
||||
def _page(request, qs):
|
||||
try:
|
||||
limit = min(max(int(request.GET.get('limit', 30)), 1), 100)
|
||||
offset = max(int(request.GET.get('offset', 0)), 0)
|
||||
except ValueError:
|
||||
raise GroceryError('Invalid pagination.') from None
|
||||
return JsonResponse({'count': qs.count(), 'results': [_data(item) for item in qs[offset:offset+limit]]})
|
||||
|
||||
|
||||
@api_view({'GET': 'inventory:read', 'POST': 'inventory:write'}, ('GET', 'POST'))
|
||||
def collection(request):
|
||||
if request.method == 'GET':
|
||||
product = product_for(request.api_user, request.GET.get('product_id'))
|
||||
return _page(request, search(request.api_user, query=request.GET.get('query', ''),
|
||||
category=request.GET.get('category', ''), product=product, status=request.GET.get('status', 'needed')))
|
||||
data = _json(request)
|
||||
if set(data) - {'name', 'quantity', 'unit', 'category', 'product_id', 'notes'}:
|
||||
raise GroceryError('Unsupported grocery field.')
|
||||
def action():
|
||||
item = add(request.api_user, name=data.get('name', ''), quantity=data.get('quantity'),
|
||||
unit=data.get('unit', 'pieces'), category=data.get('category', ''),
|
||||
product=product_for(request.api_user, data.get('product_id')), notes=data.get('notes', ''))
|
||||
return JsonResponse(_data(item), status=201)
|
||||
return _idempotent(request, data, action)
|
||||
|
||||
|
||||
@api_view({'PATCH': 'inventory:write', 'DELETE': 'inventory:write'}, ('PATCH', 'DELETE'))
|
||||
def item(request, identifier):
|
||||
item = GroceryItem.objects.filter(user=request.api_user, pk=identifier).first()
|
||||
if item is None:
|
||||
return error('not_found', 'Grocery item not found.', 404)
|
||||
if request.method == 'DELETE':
|
||||
item.delete()
|
||||
return JsonResponse({'id': str(identifier), 'deleted': True})
|
||||
return JsonResponse(_data(edit(request.api_user, identifier, _json(request))))
|
||||
|
||||
|
||||
def _recipe(user, identifier):
|
||||
return Recipe.objects.filter(owner=user, api_id=identifier).first()
|
||||
|
||||
|
||||
def _plan_data(plan):
|
||||
return {'recipe_id': str(plan['recipe'].api_id), 'servings': str(plan['servings']),
|
||||
'requires_review': plan['requires_review'],
|
||||
'lines': [{'ingredient_id': line['ingredient'].pk, 'name': line['name'],
|
||||
'quantity': str(line['quantity']), 'unit': line['unit'],
|
||||
'stock_used': str(line['stock_used']), 'listed': str(line['list_used']),
|
||||
'missing': str(line['missing']), 'uncertain': line['uncertain'],
|
||||
'reason': line['reason']} for line in plan['lines']]}
|
||||
|
||||
|
||||
@api_view({'GET': 'inventory:read', 'POST': 'inventory:write'}, ('GET', 'POST'))
|
||||
def recipe_import(request, identifier):
|
||||
recipe = _recipe(request.api_user, identifier)
|
||||
if recipe is None:
|
||||
return error('not_found', 'Recipe not found.', 404)
|
||||
data = request.GET if request.method == 'GET' else _json(request)
|
||||
if request.method == 'GET':
|
||||
optional = data.get('include_optional', 'false').lower() == 'true'
|
||||
substitutions = {key[4:]: value for key, value in data.items() if key.startswith('sub_') and value}
|
||||
else:
|
||||
optional = data.get('include_optional', False)
|
||||
substitutions = data.get('substitutions', {})
|
||||
options = {'servings': data.get('servings'), 'include_optional': optional,
|
||||
'substitutions': substitutions}
|
||||
if request.method == 'GET':
|
||||
return JsonResponse(_plan_data(recipe_preview(request.api_user, recipe, **options)))
|
||||
if not isinstance(options['include_optional'], bool) or not isinstance(options['substitutions'], dict):
|
||||
raise GroceryError('Invalid recipe options.')
|
||||
def action():
|
||||
return JsonResponse(_plan_data(apply_recipe(request.api_user, recipe,
|
||||
confirmed_uncertain=data.get('confirm_uncertain') is True, **options)))
|
||||
return _idempotent(request, data, action)
|
||||
@@ -0,0 +1,67 @@
|
||||
# Generated by Django 6.1.2 on 2026-10-21 18:45
|
||||
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('food', '0011_log_quantity'),
|
||||
('recipes', '0006_cooklater'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='GroceryItem',
|
||||
fields=[
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
||||
('name', models.CharField(max_length=180)),
|
||||
('quantity', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))])),
|
||||
('unit', models.CharField(choices=[('pieces', 'pieces'), ('g', 'g'), ('kg', 'kg'), ('ml', 'ml'), ('L', 'L'), ('packs', 'packs'), ('portions', 'portions'), ('tsp', 'tsp'), ('tbsp', 'tbsp')], max_length=10)),
|
||||
('category', models.CharField(blank=True, max_length=80)),
|
||||
('notes', models.TextField(blank=True)),
|
||||
('status', models.CharField(choices=[('needed', 'Needed'), ('purchased', 'Purchased')], default='needed', max_length=12)),
|
||||
('purchased_at', models.DateTimeField(blank=True, null=True)),
|
||||
('idempotency_key', models.CharField(blank=True, max_length=100)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='food.foodproduct')),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='grocery_items', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ('status', 'category', 'name', 'created_at'),
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='GrocerySource',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('requested_quantity', models.DecimalField(decimal_places=3, max_digits=10)),
|
||||
('requested_unit', models.CharField(max_length=10)),
|
||||
('selection_key', models.CharField(max_length=120)),
|
||||
('ingredient', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='recipes.recipeingredient')),
|
||||
('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sources', to='groceries.groceryitem')),
|
||||
('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.recipe')),
|
||||
],
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='groceryitem',
|
||||
constraint=models.CheckConstraint(condition=models.Q(('quantity__gt', 0)), name='groceries_positive_quantity'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='groceryitem',
|
||||
constraint=models.UniqueConstraint(condition=models.Q(('idempotency_key', ''), _negated=True), fields=('user', 'idempotency_key'), name='groceries_unique_idempotency_key'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='grocerysource',
|
||||
constraint=models.UniqueConstraint(fields=('item', 'recipe', 'ingredient', 'selection_key'), name='groceries_unique_source'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,35 @@
|
||||
# Generated by Django 6.1.2 on 2026-10-21 18:46
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('food', '0011_log_quantity'),
|
||||
('groceries', '0001_initial'),
|
||||
('recipes', '0006_cooklater'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='GroceryRecipeDemand',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('selection_key', models.CharField(blank=True, max_length=120)),
|
||||
('name', models.CharField(max_length=180)),
|
||||
('quantity', models.DecimalField(decimal_places=3, max_digits=10)),
|
||||
('unit', models.CharField(max_length=10)),
|
||||
('ingredient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.recipeingredient')),
|
||||
('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='food.foodproduct')),
|
||||
('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.recipe')),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'constraints': [models.UniqueConstraint(fields=('user', 'recipe', 'ingredient', 'selection_key'), name='groceries_unique_recipe_demand')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,25 @@
|
||||
# Generated by Django 6.1.2 on 2026-10-21 18:49
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('food', '0011_log_quantity'),
|
||||
('groceries', '0002_groceryrecipedemand'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='groceryitem',
|
||||
name='inventory_transfer',
|
||||
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='grocery_origin', to='food.kitcheninventoryitem'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='groceryitem',
|
||||
name='inventory_transferred_at',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,79 @@
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import MinValueValidator
|
||||
from django.db import models
|
||||
from django.db.models import Q
|
||||
|
||||
|
||||
class GroceryItem(models.Model):
|
||||
class Status(models.TextChoices):
|
||||
NEEDED = 'needed', 'Needed'
|
||||
PURCHASED = 'purchased', 'Purchased'
|
||||
|
||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='grocery_items')
|
||||
name = models.CharField(max_length=180)
|
||||
quantity = models.DecimalField(max_digits=10, decimal_places=3,
|
||||
validators=[MinValueValidator(Decimal('0.001'))])
|
||||
unit = models.CharField(max_length=10, choices=[('pieces', 'pieces'), ('g', 'g'), ('kg', 'kg'),
|
||||
('ml', 'ml'), ('L', 'L'), ('packs', 'packs'),
|
||||
('portions', 'portions'), ('tsp', 'tsp'), ('tbsp', 'tbsp')])
|
||||
category = models.CharField(max_length=80, blank=True)
|
||||
product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL, null=True, blank=True)
|
||||
notes = models.TextField(blank=True)
|
||||
status = models.CharField(max_length=12, choices=Status.choices, default=Status.NEEDED)
|
||||
purchased_at = models.DateTimeField(null=True, blank=True)
|
||||
inventory_transfer = models.OneToOneField('food.KitchenInventoryItem', on_delete=models.SET_NULL,
|
||||
null=True, blank=True, related_name='grocery_origin')
|
||||
inventory_transferred_at = models.DateTimeField(null=True, blank=True)
|
||||
idempotency_key = models.CharField(max_length=100, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ('status', 'category', 'name', 'created_at')
|
||||
constraints = [
|
||||
models.CheckConstraint(condition=Q(quantity__gt=0), name='groceries_positive_quantity'),
|
||||
models.UniqueConstraint(fields=('user', 'idempotency_key'), condition=~Q(idempotency_key=''),
|
||||
name='groceries_unique_idempotency_key'),
|
||||
]
|
||||
|
||||
def clean(self):
|
||||
if self.product_id and self.user_id and self.product.owner_id != self.user_id:
|
||||
raise ValidationError({'product': 'Choose one of your own food products.'})
|
||||
|
||||
|
||||
class GrocerySource(models.Model):
|
||||
item = models.ForeignKey(GroceryItem, on_delete=models.CASCADE, related_name='sources')
|
||||
recipe = models.ForeignKey('recipes.Recipe', on_delete=models.CASCADE)
|
||||
ingredient = models.ForeignKey('recipes.RecipeIngredient', on_delete=models.SET_NULL, null=True, blank=True)
|
||||
requested_quantity = models.DecimalField(max_digits=10, decimal_places=3)
|
||||
requested_unit = models.CharField(max_length=10)
|
||||
selection_key = models.CharField(max_length=120)
|
||||
|
||||
class Meta:
|
||||
constraints = [models.UniqueConstraint(fields=('item', 'recipe', 'ingredient', 'selection_key'),
|
||||
name='groceries_unique_source')]
|
||||
|
||||
def clean(self):
|
||||
if self.item_id and self.recipe_id and self.item.user_id != self.recipe.owner_id:
|
||||
raise ValidationError('Recipe and grocery item must have the same owner.')
|
||||
|
||||
|
||||
class GroceryRecipeDemand(models.Model):
|
||||
"""Remember recipe demand even when inventory currently covers it."""
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||||
recipe = models.ForeignKey('recipes.Recipe', on_delete=models.CASCADE)
|
||||
ingredient = models.ForeignKey('recipes.RecipeIngredient', on_delete=models.CASCADE)
|
||||
selection_key = models.CharField(max_length=120, blank=True)
|
||||
name = models.CharField(max_length=180)
|
||||
product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL, null=True, blank=True)
|
||||
quantity = models.DecimalField(max_digits=10, decimal_places=3)
|
||||
unit = models.CharField(max_length=10)
|
||||
|
||||
class Meta:
|
||||
constraints = [models.UniqueConstraint(fields=('user', 'recipe', 'ingredient', 'selection_key'),
|
||||
name='groceries_unique_recipe_demand')]
|
||||
@@ -0,0 +1,268 @@
|
||||
"""Owner-scoped grocery mutations and conservative recipe import."""
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
from django.utils import timezone
|
||||
|
||||
from food.models import FoodProduct, InventoryLocation, KitchenInventoryItem
|
||||
from recipes.models import Recipe
|
||||
from recipes.services.analysis import AnalysisError, analyze, physical_amount
|
||||
from .models import GroceryItem, GroceryRecipeDemand, GrocerySource
|
||||
|
||||
UNIT_FACTORS = {'g': ('mass', Decimal(1)), 'kg': ('mass', Decimal(1000)),
|
||||
'ml': ('volume', Decimal(1)), 'L': ('volume', Decimal(1000)),
|
||||
'pieces': ('pieces', Decimal(1)), 'packs': ('packs', Decimal(1)),
|
||||
'portions': ('portions', Decimal(1))}
|
||||
|
||||
|
||||
class GroceryError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def amount(value):
|
||||
try:
|
||||
number = Decimal(str(value))
|
||||
if not number.is_finite() or number <= 0 or number > Decimal('9999999.999') or number != number.quantize(Decimal('.001')):
|
||||
raise GroceryError('Enter a positive quantity with at most three decimal places.')
|
||||
return number
|
||||
except (InvalidOperation, TypeError, ValueError):
|
||||
raise GroceryError('Enter a valid positive quantity.') from None
|
||||
|
||||
|
||||
def product_for(user, identifier):
|
||||
if not identifier:
|
||||
return None
|
||||
return FoodProduct.objects.filter(owner=user, api_id=identifier).first() or _raise('Product not found.')
|
||||
|
||||
|
||||
def _raise(message):
|
||||
raise GroceryError(message)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def add(user, *, name, quantity, unit, category='', product=None, notes='', idempotency_key=''):
|
||||
name = str(name).strip()
|
||||
if not name or len(name) > 180:
|
||||
raise GroceryError('Enter a name of at most 180 characters.')
|
||||
if unit not in dict(GroceryItem._meta.get_field('unit').choices):
|
||||
raise GroceryError('Choose a supported unit.')
|
||||
if product and product.owner_id != user.pk:
|
||||
raise GroceryError('Product not found.')
|
||||
if len(category) > 80 or len(idempotency_key) > 100:
|
||||
raise GroceryError('Category or idempotency key is too long.')
|
||||
quantity = amount(quantity)
|
||||
if idempotency_key:
|
||||
existing = GroceryItem.objects.filter(user=user, idempotency_key=idempotency_key).first()
|
||||
if existing:
|
||||
if (existing.name, existing.quantity, existing.unit, existing.category, existing.product_id, existing.notes) != (name, quantity, unit, category, product.pk if product else None, notes):
|
||||
raise GroceryError('Idempotency key was used with different item details.')
|
||||
return existing
|
||||
if not idempotency_key and unit in UNIT_FACTORS:
|
||||
kind, factor = UNIT_FACTORS[unit]
|
||||
candidates = GroceryItem.objects.select_for_update().filter(user=user,
|
||||
status=GroceryItem.Status.NEEDED, category=category)
|
||||
for existing in candidates:
|
||||
if ((product and existing.product_id != product.pk) or
|
||||
(not product and (existing.product_id or existing.name.casefold() != name.casefold())) or
|
||||
existing.unit not in UNIT_FACTORS or UNIT_FACTORS[existing.unit][0] != kind):
|
||||
continue
|
||||
converted = quantity * factor / UNIT_FACTORS[existing.unit][1]
|
||||
if converted != converted.quantize(Decimal('.001')):
|
||||
continue
|
||||
existing.quantity += converted
|
||||
if notes and notes not in existing.notes:
|
||||
existing.notes = '\n'.join(filter(None, (existing.notes, notes)))
|
||||
existing.full_clean()
|
||||
existing.save()
|
||||
return existing
|
||||
item = GroceryItem(user=user, name=name, quantity=quantity, unit=unit,
|
||||
category=category, product=product, notes=notes,
|
||||
idempotency_key=idempotency_key)
|
||||
item.full_clean()
|
||||
item.save()
|
||||
return item
|
||||
|
||||
|
||||
def edit(user, identifier, changes):
|
||||
with transaction.atomic():
|
||||
item = GroceryItem.objects.select_for_update().filter(user=user, pk=identifier).first()
|
||||
if item is None:
|
||||
raise GroceryError('Grocery item not found.')
|
||||
allowed = {'name', 'quantity', 'unit', 'category', 'notes', 'status', 'product_id'}
|
||||
if set(changes) - allowed:
|
||||
raise GroceryError('Unsupported grocery field.')
|
||||
for key, value in changes.items():
|
||||
if key == 'quantity':
|
||||
value = amount(value)
|
||||
elif key == 'product_id':
|
||||
item.product = product_for(user, value)
|
||||
continue
|
||||
elif key == 'status':
|
||||
if value not in GroceryItem.Status.values:
|
||||
raise GroceryError('Invalid purchase status.')
|
||||
item.purchased_at = timezone.now() if value == GroceryItem.Status.PURCHASED else None
|
||||
elif key == 'name':
|
||||
value = str(value).strip()
|
||||
setattr(item, key, value)
|
||||
item.full_clean()
|
||||
item.save()
|
||||
return item
|
||||
|
||||
|
||||
def search(user, *, query='', category='', product=None, status='needed'):
|
||||
items = GroceryItem.objects.filter(user=user).select_related('product').prefetch_related('sources__recipe')
|
||||
if query:
|
||||
items = items.filter(Q(name__icontains=query) | Q(notes__icontains=query))
|
||||
if category:
|
||||
items = items.filter(category=category)
|
||||
if product:
|
||||
items = items.filter(product=product)
|
||||
if status != 'all':
|
||||
if status not in GroceryItem.Status.values:
|
||||
raise GroceryError('Invalid purchase status.')
|
||||
items = items.filter(status=status)
|
||||
return items
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def add_purchased_to_inventory(user, identifier, *, product, location):
|
||||
"""Explicitly convert one purchased grocery row into owned kitchen stock."""
|
||||
item = GroceryItem.objects.select_for_update().filter(user=user, pk=identifier,
|
||||
status=GroceryItem.Status.PURCHASED).first()
|
||||
if item is None:
|
||||
raise GroceryError('Purchased grocery item not found.')
|
||||
if item.inventory_transferred_at:
|
||||
raise GroceryError('This grocery item was already added to inventory.')
|
||||
if product.owner_id != user.pk:
|
||||
raise GroceryError('Product not found.')
|
||||
location_name = ' '.join(location.split())
|
||||
if not location_name or len(location_name) > 100:
|
||||
raise GroceryError('Enter a kitchen location.')
|
||||
place, _ = InventoryLocation.objects.get_or_create(user=user, name__iexact=location_name,
|
||||
defaults={'name': location_name})
|
||||
if item.unit in ('pieces', 'packs'):
|
||||
if item.quantity != item.quantity.to_integral_value():
|
||||
raise GroceryError('Count units must be whole numbers.')
|
||||
if item.quantity > 1000:
|
||||
raise GroceryError('Transfer at most 1,000 count units at a time.')
|
||||
stock = KitchenInventoryItem(user=user, product=product, location=place,
|
||||
quantity=1 if item.unit == 'pieces' else int(item.quantity))
|
||||
if item.unit == 'pieces':
|
||||
stock.original_amount = Decimal(1)
|
||||
stock.remaining_amount = Decimal(1)
|
||||
stock.inventory_unit = 'pieces'
|
||||
elif item.unit in ('g', 'kg', 'ml', 'L'):
|
||||
factor = Decimal(1000) if item.unit in ('kg', 'L') else Decimal(1)
|
||||
stock = KitchenInventoryItem(user=user, product=product, location=place, quantity=1,
|
||||
original_amount=item.quantity * factor, remaining_amount=item.quantity * factor,
|
||||
inventory_unit='g' if item.unit in ('g', 'kg') else 'ml')
|
||||
else:
|
||||
raise GroceryError('Set a weight, volume, or whole count before adding to inventory.')
|
||||
stock.full_clean()
|
||||
stock.save()
|
||||
if item.unit == 'packs':
|
||||
from food.services.inventory_consumption import materialize_packages
|
||||
materialize_packages(stock)
|
||||
if item.unit == 'pieces':
|
||||
for _ in range(int(item.quantity) - 1):
|
||||
KitchenInventoryItem.objects.create(user=user, product=product, location=place,
|
||||
quantity=1, original_amount=Decimal(1), remaining_amount=Decimal(1),
|
||||
inventory_unit='pieces')
|
||||
# Keep the purchased grocery row for history; prevent duplicate transfer with a durable link.
|
||||
item.inventory_transfer = stock
|
||||
item.inventory_transferred_at = timezone.now()
|
||||
item.save(update_fields=['inventory_transfer', 'inventory_transferred_at', 'updated_at'])
|
||||
return stock
|
||||
|
||||
|
||||
def _compatible(item, name, product, unit):
|
||||
if product:
|
||||
if item.product_id != product.pk:
|
||||
return False
|
||||
elif item.product_id or item.name.casefold() != name.casefold():
|
||||
return False
|
||||
return item.unit == unit
|
||||
|
||||
|
||||
def recipe_preview(user, recipe, servings=None, *, include_optional=False, substitutions=None):
|
||||
if recipe.owner_id != user.pk:
|
||||
raise GroceryError('Recipe not found.')
|
||||
try:
|
||||
result = analyze(recipe, user, servings, include_optional=include_optional,
|
||||
substitutions=substitutions or {})
|
||||
except AnalysisError as exc:
|
||||
raise GroceryError(str(exc)) from exc
|
||||
proposed = []
|
||||
existing = list(search(user))
|
||||
demands = list(GroceryRecipeDemand.objects.filter(user=user))
|
||||
for line in result['lines']:
|
||||
if line['status'] == 'optional':
|
||||
continue
|
||||
product = line['product']
|
||||
raw_quantity, raw_unit = line['quantity'], line['unit']
|
||||
chosen = next((s for s in line['substitutions'] if str(s.pk) == line['selected_substitution']), None) or line['ingredient']
|
||||
normalized, unit = physical_amount(raw_quantity, raw_unit, chosen.amount_per_unit,
|
||||
chosen.amount_per_unit_unit)
|
||||
if normalized is None:
|
||||
normalized, unit = raw_quantity, raw_unit
|
||||
group = next((g for g in result['groups'] if product and g['product'].pk == product.pk and g['unit'] == unit), None)
|
||||
stock = group['plan']['total'] if group and group['plan'] else None
|
||||
# Allocate known stock and existing list coverage across lines once, including repeat ingredients.
|
||||
related = [item for item in existing if _compatible(item, line['name'], product, unit)]
|
||||
matching_demands = [d for d in demands if d.unit == unit and
|
||||
((product and d.product_id == product.pk) or
|
||||
(not product and not d.product_id and d.name.casefold() == line['name'].casefold()))]
|
||||
prior = sum((d.quantity for d in matching_demands), Decimal(0))
|
||||
same_recipe = sum((d.quantity for d in matching_demands if d.recipe_id == recipe.pk and
|
||||
d.ingredient_id == line['ingredient'].pk), Decimal(0))
|
||||
additional = max(Decimal(0), normalized - same_recipe)
|
||||
previous = [p for p in proposed if p['product_id'] == (product.pk if product else None) and
|
||||
p['unit'] == unit]
|
||||
used_stock = sum((p['stock_used'] for p in previous), Decimal(0))
|
||||
stock_used = min(additional, max(Decimal(0), stock - prior - used_stock)) if stock is not None else Decimal(0)
|
||||
listed = sum((item.quantity for item in related), Decimal(0))
|
||||
prior_unmet = max(Decimal(0), prior - (stock or Decimal(0)))
|
||||
used_list = sum((p['list_used'] for p in previous if p['name'].casefold() == line['name'].casefold()), Decimal(0))
|
||||
list_used = min(additional - stock_used, max(Decimal(0), listed - prior_unmet - used_list))
|
||||
missing = max(Decimal(0), additional - stock_used - list_used)
|
||||
uncertain = stock is None or not product
|
||||
proposed.append({'ingredient': line['ingredient'], 'name': line['name'], 'quantity': normalized,
|
||||
'unit': unit, 'product': product, 'product_id': product.pk if product else None,
|
||||
'selected_substitution': line['selected_substitution'],
|
||||
'stock_used': stock_used, 'list_used': list_used, 'missing': missing,
|
||||
'uncertain': uncertain, 'reason': line['reason'] or ('Stock quantity or product match is unknown.' if uncertain else ''),
|
||||
'source': line['source']})
|
||||
return {'recipe': recipe, 'servings': result['servings'], 'lines': proposed,
|
||||
'substitutions': result['selected_substitutions'], 'include_optional': include_optional,
|
||||
'requires_review': any(line['uncertain'] for line in proposed)}
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def apply_recipe(user, recipe, servings=None, *, include_optional=False, substitutions=None,
|
||||
confirmed_uncertain=False):
|
||||
# Lock the user's rows before recalculating coverage to avoid concurrent duplicate additions.
|
||||
list(GroceryItem.objects.select_for_update().filter(user=user))
|
||||
plan = recipe_preview(user, recipe, servings, include_optional=include_optional,
|
||||
substitutions=substitutions)
|
||||
if plan['requires_review'] and not confirmed_uncertain:
|
||||
raise GroceryError('Review uncertain ingredients before adding them.')
|
||||
for line in plan['lines']:
|
||||
if line['missing'] > 0:
|
||||
item = next((item for item in search(user) if _compatible(item, line['name'], line['product'], line['unit'])
|
||||
and item.category == recipe.category), None)
|
||||
if item:
|
||||
item.quantity += line['missing']
|
||||
item.full_clean()
|
||||
item.save()
|
||||
else:
|
||||
item = add(user, name=line['name'], quantity=line['missing'], unit=line['unit'],
|
||||
category=recipe.category, product=line['product'])
|
||||
GrocerySource.objects.update_or_create(item=item, recipe=recipe, ingredient=line['ingredient'],
|
||||
selection_key=str(plan['substitutions'].get(str(line['ingredient'].pk), '')),
|
||||
defaults={'requested_quantity': line['quantity'], 'requested_unit': line['unit']})
|
||||
GroceryRecipeDemand.objects.update_or_create(user=user, recipe=recipe,
|
||||
ingredient=line['ingredient'], selection_key=str(plan['substitutions'].get(str(line['ingredient'].pk), '')),
|
||||
defaults={'name': line['name'], 'product': line['product'], 'quantity': line['quantity'],
|
||||
'unit': line['unit']})
|
||||
return plan
|
||||
@@ -0,0 +1 @@
|
||||
.grocery-page{max-width:1050px;margin:0 auto;padding:clamp(1rem,3vw,2.5rem);color:var(--text,#21372c)}.grocery-page h1{font-size:clamp(2rem,4vw,3rem);margin:.2rem 0}.grocery-kicker{text-transform:uppercase;letter-spacing:.12em;font-weight:700}.grocery-panel{background:var(--surface,#fff);border:1px solid #d3ddd5;border-radius:1rem;padding:clamp(1rem,2vw,1.5rem);margin:1.25rem 0;box-shadow:0 6px 24px #172a2010}.grocery-panel h2{margin:0 0 1rem}.grocery-add,.grocery-filter,.grocery-edit{display:flex;flex-wrap:wrap;align-items:end;gap:.75rem}.grocery-add label,.grocery-filter label,.grocery-edit label{display:grid;gap:.3rem;min-width:120px;flex:1}.grocery-add label:first-child{flex:2;min-width:200px}.grocery-page input,.grocery-page select,.grocery-page textarea{box-sizing:border-box;width:100%;padding:.65rem;border:1px solid #a7b7a9;border-radius:.5rem;background:var(--surface,#fff);color:inherit;font:inherit}.grocery-page button{padding:.65rem 1rem;border:0;border-radius:.5rem;background:#315d4d;color:white;font:inherit;cursor:pointer}.grocery-page button:focus-visible,.grocery-page a:focus-visible,.grocery-page input:focus-visible,.grocery-page select:focus-visible,.grocery-page summary:focus-visible{outline:3px solid #bd7319;outline-offset:2px}.grocery-panel-head{display:flex;justify-content:space-between;align-items:center;gap:1rem}.grocery-page .grocery-text-button{background:transparent;color:#315d4d;text-decoration:underline;padding:.4rem}.grocery-group h3{border-bottom:1px solid #d3ddd5;padding-bottom:.4rem}.grocery-group ul,.grocery-preview-list{list-style:none;padding:0}.grocery-item{display:flex;align-items:start;gap:.8rem;border-bottom:1px solid #e2e8e2;padding:.8rem 0}.grocery-item-body{flex:1;min-width:0}.grocery-item-body strong,.grocery-item-body span,.grocery-item-body small{display:block}.grocery-item-body small{color:#52655b}.grocery-item-body details{margin-top:.4rem}.grocery-check{min-width:2.7rem}.grocery-uncertain{display:block;color:#8a4400;font-weight:600}.grocery-confirm{display:flex;gap:.5rem;align-items:center;margin:1rem 0}.grocery-confirm input{width:auto}.grocery-preview-list li{padding:.8rem 0;border-bottom:1px solid #d3ddd5}@media(max-width:600px){.grocery-page{padding:1rem}.grocery-add,.grocery-filter,.grocery-edit{display:grid;grid-template-columns:1fr 1fr}.grocery-add label:first-child,.grocery-add button,.grocery-edit label:first-child,.grocery-edit button{grid-column:1/-1}.grocery-item{gap:.4rem}.grocery-page .grocery-text-button{font-size:.9rem}}
|
||||
@@ -0,0 +1,8 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Groceries · Tasknest{% endblock %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'groceries/groceries.css' %}?v=2">
|
||||
<div class="grocery-page"><header><p class="grocery-kicker">Food</p><h1>Grocery list</h1><p>Plan what to buy. Marking an item purchased does not add it to Kitchen Inventory.</p></header>
|
||||
<section class="grocery-panel" aria-labelledby="quick-add"><h2 id="quick-add">Quick add</h2><form class="grocery-add" method="post" action="{% url 'groceries:add' %}">{% csrf_token %}<label>Name<input name="name" maxlength="180" required autocomplete="off"></label><label>Quantity<input name="quantity" type="number" min="0.001" step="0.001" value="1" required></label><label>Unit<select name="unit"><option value="pieces">pieces</option><option value="g">g</option><option value="kg">kg</option><option value="ml">ml</option><option value="L">L</option><option value="packs">packs</option><option value="portions">portions</option><option value="tsp">tsp</option><option value="tbsp">tbsp</option></select></label><label>Category<input name="category" maxlength="80"></label><button type="submit">Add item</button></form></section>
|
||||
<section class="grocery-panel" aria-labelledby="grocery-items"><div class="grocery-panel-head"><h2 id="grocery-items">Items</h2><form method="post" action="{% url 'groceries:clear-purchased' %}">{% csrf_token %}<button type="submit" class="grocery-text-button">Clear purchased</button></form></div><form method="get" class="grocery-filter" hx-get="{% url 'groceries:index' %}" hx-target="#grocery-list" hx-push-url="true"><label>Search<input type="search" name="q" value="{{ query }}"></label><label>Status<select name="status"><option value="needed"{% if selected_status == 'needed' %} selected{% endif %}>Needed</option><option value="purchased"{% if selected_status == 'purchased' %} selected{% endif %}>Purchased</option><option value="all"{% if selected_status == 'all' %} selected{% endif %}>All</option></select></label><button type="submit">Filter</button></form><div id="grocery-list" aria-live="polite">{% include 'groceries/partials/list.html' %}</div></section></div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,3 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Add to Kitchen Inventory · Tasknest{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'groceries/groceries.css' %}?v=2"><div class="grocery-page"><a href="{% url 'groceries:index' %}">← Grocery list</a><h1>Add purchased item to inventory</h1><section class="grocery-panel"><p><strong>{{ item.name }}</strong> · {{ item.quantity|floatformat:-3 }} {{ item.unit }}</p>{% if item.inventory_transferred_at %}<p>This item was already added to Kitchen Inventory.</p>{% else %}<p>Confirm the product and location. This creates stock only when you submit this form.</p><form method="post" class="grocery-add">{% csrf_token %}<label>Food product<select name="product_id" required><option value="">Choose a product</option>{% for product in products %}<option value="{{ product.api_id }}"{% if product.pk == item.product_id %} selected{% endif %}>{{ product.product_name }}{% if product.brand %} · {{ product.brand }}{% endif %}</option>{% endfor %}</select></label><label>Kitchen location<input name="location" value="Pantry" maxlength="100" required></label><button type="submit">Confirm and add stock</button></form>{% endif %}</section></div>{% endblock %}
|
||||
@@ -0,0 +1,2 @@
|
||||
{% regroup items by category as categories %}
|
||||
{% for group in categories %}<section class="grocery-group"><h3>{{ group.grouper|default:'Other' }}</h3><ul>{% for item in group.list %}<li class="grocery-item"><form method="post" action="{% url 'groceries:update' item.pk %}" class="grocery-item-main">{% csrf_token %}<input type="hidden" name="status" value="{% if item.status == 'needed' %}purchased{% else %}needed{% endif %}"><button type="submit" class="grocery-check" aria-label="Mark {{ item.name }} {% if item.status == 'needed' %}purchased{% else %}needed{% endif %}" aria-pressed="{% if item.status == 'purchased' %}true{% else %}false{% endif %}">{% if item.status == 'purchased' %}✓{% else %}○{% endif %}</button></form><div class="grocery-item-body"><strong>{{ item.name }}</strong><span>{{ item.quantity|floatformat:-3 }} {{ item.unit }}</span>{% if item.notes %}<small>{{ item.notes }}</small>{% endif %}{% for source in item.sources.all %}<small>From {{ source.recipe.title }}</small>{% endfor %}{% if item.status == "purchased" %}<a href="{% url 'groceries:inventory-transfer' item.pk %}">{% if item.inventory_transferred_at %}Added to inventory{% else %}Add to inventory{% endif %}</a>{% endif %}<details><summary>Edit</summary><form method="post" action="{% url 'groceries:update' item.pk %}" class="grocery-edit">{% csrf_token %}<label>Name<input name="name" value="{{ item.name }}" required></label><label>Quantity<input name="quantity" type="number" min="0.001" step="0.001" value="{{ item.quantity }}" required></label><label>Unit<select name="unit"><option value="{{ item.unit }}" selected>{{ item.unit }}</option><option value="pieces">pieces</option><option value="g">g</option><option value="kg">kg</option><option value="ml">ml</option><option value="L">L</option><option value="packs">packs</option><option value="portions">portions</option><option value="tsp">tsp</option><option value="tbsp">tbsp</option></select></label><label>Category<input name="category" value="{{ item.category }}"></label><label>Notes<textarea name="notes">{{ item.notes }}</textarea></label><button type="submit">Save</button></form></details></div><form method="post" action="{% url 'groceries:delete' item.pk %}">{% csrf_token %}<button type="submit" class="grocery-text-button" aria-label="Delete {{ item.name }}">Delete</button></form></li>{% endfor %}</ul></section>{% empty %}<p class="grocery-empty">No grocery items here yet.</p>{% endfor %}
|
||||
@@ -0,0 +1,3 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Review groceries · {{ recipe.title }}{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'groceries/groceries.css' %}?v=2"><div class="grocery-page"><a href="{% url 'recipes:detail' recipe.api_id %}">← Back to recipe</a><h1>Review groceries for {{ recipe.title }}</h1><p>Only known, compatible stock is subtracted. Items already on your grocery list are counted.</p>{% if error %}<p role="alert">{{ error }}</p>{% endif %}{% if plan %}<form method="get" class="grocery-panel grocery-filter"><label>Servings<input type="number" name="servings" min="0.01" max="99999.99" step="0.01" value="{{ plan.servings }}"></label><label><input type="checkbox" name="optional" value="1"{% if plan.include_optional %} checked{% endif %}> Include optional ingredients</label>{% for line in plan.lines %}{% if line.ingredient.substitutions.exists %}<label>{{ line.name }} alternative<select name="sub_{{ line.ingredient.pk }}"><option value="">Original</option>{% for substitute in line.ingredient.substitutions.all %}<option value="{{ substitute.pk }}"{% if line.selected_substitution == substitute.pk|stringformat:"s" %} selected{% endif %}>{{ substitute.name }}</option>{% endfor %}</select></label>{% endif %}{% endfor %}<button>Update preview</button></form><section class="grocery-panel"><h2>Missing ingredients</h2><ul class="grocery-preview-list">{% for line in plan.lines %}<li><strong>{{ line.name }}</strong> · {{ line.quantity|floatformat:-3 }} {{ line.unit }} needed · {{ line.stock_used|floatformat:-3 }} in stock · {{ line.list_used|floatformat:-3 }} listed · <b>{{ line.missing|floatformat:-3 }} to add</b>{% if line.uncertain %}<span class="grocery-uncertain">Review: {{ line.reason }}</span>{% endif %}{% if line.source %}<small>From {{ line.source }}</small>{% endif %}</li>{% empty %}<li>No ingredients to add.</li>{% endfor %}</ul><form method="post" action="{% url 'groceries:recipe-add' recipe.api_id %}">{% csrf_token %}<input type="hidden" name="servings" value="{{ plan.servings }}">{% if plan.include_optional %}<input type="hidden" name="optional" value="1">{% endif %}{% for key,value in plan.substitutions.items %}<input type="hidden" name="sub_{{ key }}" value="{{ value }}">{% endfor %}{% if plan.requires_review %}<label class="grocery-confirm"><input type="checkbox" name="confirm_uncertain" value="1" required> I reviewed the uncertain stock or ingredient matches.</label>{% endif %}<button type="submit">Add missing ingredients</button></form></section>{% endif %}</div>{% endblock %}
|
||||
@@ -0,0 +1,100 @@
|
||||
from decimal import Decimal
|
||||
import json
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
from django.test import override_settings
|
||||
from django.conf import settings
|
||||
|
||||
from food.models import FoodProduct
|
||||
from food.api import create_token
|
||||
from recipes.models import Recipe, RecipeIngredient
|
||||
from .models import GroceryItem
|
||||
from .services import GroceryError, add, add_purchased_to_inventory, apply_recipe, edit, recipe_preview, search
|
||||
|
||||
|
||||
class GroceryTests(TestCase):
|
||||
def setUp(self):
|
||||
User = get_user_model()
|
||||
self.user = User.objects.create_user(username='grocery-user', password='test')
|
||||
self.other = User.objects.create_user(username='grocery-other', password='test')
|
||||
|
||||
def test_manual_items_are_scoped_and_purchase_does_not_create_stock(self):
|
||||
item = add(self.user, name='Milk', quantity='2', unit='L')
|
||||
self.assertEqual(search(self.user).count(), 1)
|
||||
self.assertEqual(search(self.other).count(), 0)
|
||||
with self.assertRaises(GroceryError):
|
||||
edit(self.other, item.pk, {'status': 'purchased'})
|
||||
edit(self.user, item.pk, {'status': 'purchased'})
|
||||
self.assertEqual(search(self.user).count(), 0)
|
||||
self.assertEqual(search(self.user, status='purchased').count(), 1)
|
||||
self.assertEqual(self.user.kitchen_inventory.count(), 0)
|
||||
|
||||
def test_compatible_manual_units_merge_and_keep_notes(self):
|
||||
item = add(self.user, name='Flour', quantity='1', unit='kg', notes='Wholegrain')
|
||||
merged = add(self.user, name='flour', quantity='500', unit='g', notes='For bread')
|
||||
self.assertEqual(item.pk, merged.pk)
|
||||
self.assertEqual(merged.quantity, Decimal('1.5'))
|
||||
self.assertIn('Wholegrain', merged.notes)
|
||||
self.assertIn('For bread', merged.notes)
|
||||
add(self.user, name='Flour', quantity='1', unit='pieces')
|
||||
self.assertEqual(GroceryItem.objects.filter(user=self.user).count(), 2)
|
||||
|
||||
def test_recipe_import_is_idempotent_and_does_not_reuse_stock(self):
|
||||
product = FoodProduct.objects.create(owner=self.user, product_name='Flour')
|
||||
first = Recipe.objects.create(owner=self.user, title='Bread', default_servings=2)
|
||||
second = Recipe.objects.create(owner=self.user, title='Pancakes', default_servings=2)
|
||||
RecipeIngredient.objects.create(recipe=first, name='Flour', quantity=200, unit='g', inventory_product=product)
|
||||
RecipeIngredient.objects.create(recipe=second, name='Flour', quantity=100, unit='g', inventory_product=product)
|
||||
self.assertEqual(recipe_preview(self.user, first)['lines'][0]['missing'], Decimal('200'))
|
||||
apply_recipe(self.user, first)
|
||||
apply_recipe(self.user, first)
|
||||
self.assertEqual(GroceryItem.objects.get(user=self.user).quantity, Decimal('200'))
|
||||
apply_recipe(self.user, second)
|
||||
self.assertEqual(GroceryItem.objects.get(user=self.user).quantity, Decimal('300'))
|
||||
|
||||
def test_unknown_match_requires_review(self):
|
||||
recipe = Recipe.objects.create(owner=self.user, title='Snack')
|
||||
RecipeIngredient.objects.create(recipe=recipe, name='Rare ingredient', quantity=1, unit='pieces')
|
||||
self.assertTrue(recipe_preview(self.user, recipe)['requires_review'])
|
||||
with self.assertRaises(GroceryError):
|
||||
apply_recipe(self.user, recipe)
|
||||
apply_recipe(self.user, recipe, confirmed_uncertain=True)
|
||||
self.assertEqual(GroceryItem.objects.filter(user=self.user).count(), 1)
|
||||
|
||||
@override_settings(MIDDLEWARE=[item for item in settings.MIDDLEWARE if not item.startswith('whitenoise.')],
|
||||
SECURE_SSL_REDIRECT=False)
|
||||
def test_page_and_recipe_preview_render(self):
|
||||
self.client.force_login(self.user)
|
||||
self.assertContains(self.client.get('/groceries/'), 'Quick add')
|
||||
recipe = Recipe.objects.create(owner=self.user, title='Soup')
|
||||
RecipeIngredient.objects.create(recipe=recipe, name='Water', quantity=200, unit='ml')
|
||||
self.assertContains(self.client.get(f'/groceries/recipe/{recipe.api_id}/preview/'), 'Review groceries')
|
||||
|
||||
def test_inventory_transfer_requires_purchase_and_is_single_use(self):
|
||||
item = add(self.user, name='Rice', quantity='500', unit='g')
|
||||
product = FoodProduct.objects.create(owner=self.user, product_name='Rice')
|
||||
with self.assertRaises(GroceryError):
|
||||
add_purchased_to_inventory(self.user, item.pk, product=product, location='Pantry')
|
||||
edit(self.user, item.pk, {'status': 'purchased'})
|
||||
stock = add_purchased_to_inventory(self.user, item.pk, product=product, location='Pantry')
|
||||
self.assertEqual(stock.remaining_amount, Decimal('500'))
|
||||
with self.assertRaises(GroceryError):
|
||||
add_purchased_to_inventory(self.user, item.pk, product=product, location='Pantry')
|
||||
|
||||
@override_settings(MIDDLEWARE=[item for item in settings.MIDDLEWARE if not item.startswith('whitenoise.')],
|
||||
SECURE_SSL_REDIRECT=False)
|
||||
def test_api_crud_is_owner_scoped(self):
|
||||
_, token = create_token(self.user, 'groceries', ['inventory:read', 'inventory:write'])
|
||||
_, other_token = create_token(self.other, 'groceries', ['inventory:read', 'inventory:write'])
|
||||
headers = {'HTTP_AUTHORIZATION': f'Bearer {token}'}
|
||||
response = self.client.post('/api/v1/groceries/', data=json.dumps({'name': 'Apples',
|
||||
'quantity': '2', 'unit': 'pieces'}), content_type='application/json', **headers)
|
||||
self.assertEqual(response.status_code, 201)
|
||||
identifier = response.json()['id']
|
||||
self.assertEqual(self.client.get('/api/v1/groceries/', **headers).json()['count'], 1)
|
||||
self.assertEqual(self.client.patch(f'/api/v1/groceries/{identifier}/',
|
||||
data=json.dumps({'status': 'purchased'}), content_type='application/json', **headers).status_code, 200)
|
||||
other_headers = {'HTTP_AUTHORIZATION': f'Bearer {other_token}'}
|
||||
self.assertEqual(self.client.delete(f'/api/v1/groceries/{identifier}/', **other_headers).status_code, 404)
|
||||
self.assertEqual(self.client.get('/api/v1/groceries/', **other_headers).json()['count'], 0)
|
||||
@@ -0,0 +1,14 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
app_name = 'groceries'
|
||||
urlpatterns = [
|
||||
path('', views.index, name='index'),
|
||||
path('add/', views.create, name='add'),
|
||||
path('clear-purchased/', views.clear_purchased, name='clear-purchased'),
|
||||
path('<uuid:identifier>/update/', views.update, name='update'),
|
||||
path('<uuid:identifier>/delete/', views.delete, name='delete'),
|
||||
path('<uuid:identifier>/inventory/', views.inventory_transfer, name='inventory-transfer'),
|
||||
path('recipe/<uuid:identifier>/preview/', views.preview_recipe, name='recipe-preview'),
|
||||
path('recipe/<uuid:identifier>/add/', views.add_recipe, name='recipe-add'),
|
||||
]
|
||||
@@ -0,0 +1,119 @@
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.http import HttpResponseBadRequest
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.views.decorators.http import require_POST
|
||||
|
||||
from recipes.models import Recipe
|
||||
from .models import GroceryItem
|
||||
from food.models import FoodProduct
|
||||
from .services import (GroceryError, add, add_purchased_to_inventory, apply_recipe,
|
||||
edit, recipe_preview, search)
|
||||
|
||||
|
||||
def _page(request, status=200):
|
||||
selected = request.GET.get('status', 'needed')
|
||||
try:
|
||||
items = list(search(request.user, query=request.GET.get('q', ''), status=selected).order_by('category', 'status', 'name'))
|
||||
except GroceryError:
|
||||
selected, items = 'needed', list(search(request.user))
|
||||
context = {'items': items, 'selected_status': selected, 'query': request.GET.get('q', '')}
|
||||
template = 'groceries/partials/list.html' if request.headers.get('HX-Request') == 'true' else 'groceries/index.html'
|
||||
return render(request, template, context, status=status)
|
||||
|
||||
|
||||
@login_required
|
||||
def index(request):
|
||||
return _page(request)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def create(request):
|
||||
try:
|
||||
add(request.user, name=request.POST.get('name', ''), quantity=request.POST.get('quantity', ''),
|
||||
unit=request.POST.get('unit', 'pieces'), category=request.POST.get('category', '').strip(),
|
||||
notes=request.POST.get('notes', '').strip())
|
||||
messages.success(request, 'Added to grocery list.')
|
||||
except GroceryError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return redirect('groceries:index')
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def update(request, identifier):
|
||||
try:
|
||||
changes = {field: request.POST[field] for field in ('name', 'quantity', 'unit', 'category', 'notes', 'status')
|
||||
if field in request.POST}
|
||||
edit(request.user, identifier, changes)
|
||||
except GroceryError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return redirect('groceries:index')
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def delete(request, identifier):
|
||||
item = get_object_or_404(GroceryItem, user=request.user, pk=identifier)
|
||||
item.delete()
|
||||
messages.success(request, 'Grocery item removed.')
|
||||
return redirect('groceries:index')
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def clear_purchased(request):
|
||||
count, _ = GroceryItem.objects.filter(user=request.user, status=GroceryItem.Status.PURCHASED).delete()
|
||||
messages.success(request, f'Cleared {count} purchased items.')
|
||||
return redirect('groceries:index')
|
||||
|
||||
|
||||
@login_required
|
||||
def inventory_transfer(request, identifier):
|
||||
item = get_object_or_404(GroceryItem, user=request.user, pk=identifier,
|
||||
status=GroceryItem.Status.PURCHASED)
|
||||
if request.method == 'POST':
|
||||
product = FoodProduct.objects.filter(owner=request.user, api_id=request.POST.get('product_id')).first()
|
||||
try:
|
||||
if product is None:
|
||||
raise GroceryError('Choose one of your own food products.')
|
||||
add_purchased_to_inventory(request.user, identifier, product=product,
|
||||
location=request.POST.get('location', ''))
|
||||
messages.success(request, 'Purchased item added to Kitchen Inventory.')
|
||||
return redirect('groceries:index')
|
||||
except GroceryError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return render(request, 'groceries/inventory_transfer.html', {
|
||||
'item': item, 'products': FoodProduct.objects.filter(owner=request.user).order_by('product_name')})
|
||||
|
||||
|
||||
def _recipe_options(data):
|
||||
return {'include_optional': data.get('optional') == '1',
|
||||
'substitutions': {key[4:]: value for key, value in data.items() if key.startswith('sub_') and value}}
|
||||
|
||||
|
||||
@login_required
|
||||
def preview_recipe(request, identifier):
|
||||
recipe = get_object_or_404(Recipe, owner=request.user, api_id=identifier)
|
||||
try:
|
||||
plan = recipe_preview(request.user, recipe, request.GET.get('servings'), **_recipe_options(request.GET))
|
||||
error = ''
|
||||
except GroceryError as exc:
|
||||
plan, error = None, str(exc)
|
||||
return render(request, 'groceries/recipe_preview.html', {'recipe': recipe, 'plan': plan, 'error': error})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def add_recipe(request, identifier):
|
||||
recipe = get_object_or_404(Recipe, owner=request.user, api_id=identifier)
|
||||
try:
|
||||
apply_recipe(request.user, recipe, request.POST.get('servings'),
|
||||
confirmed_uncertain=request.POST.get('confirm_uncertain') == '1',
|
||||
**_recipe_options(request.POST))
|
||||
messages.success(request, 'Missing ingredients added to your grocery list.')
|
||||
return redirect('groceries:index')
|
||||
except GroceryError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return redirect('groceries:recipe-preview', identifier=identifier)
|
||||
Reference in New Issue
Block a user