92 lines
4.6 KiB
Python
92 lines
4.6 KiB
Python
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)
|