From 9eefc6bdfd1de2f79a05b0ad114fc81e45e09671 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=AD=C3=B0ir=20Valberg=20Gu=C3=B0mundsson?= Date: Mon, 16 May 2016 16:09:25 +0200 Subject: [PATCH] Adding subtotal, VAT and total to order. Also redirect to shop index if there are no products. --- shop/models.py | 18 ++++++++++++++++++ shop/templates/order_detail.html | 21 ++++++++++++++++++++- shop/views.py | 15 +++++++-------- 3 files changed, 45 insertions(+), 9 deletions(-) diff --git a/shop/models.py b/shop/models.py index 3d29b3f6..05b2785f 100644 --- a/shop/models.py +++ b/shop/models.py @@ -70,6 +70,24 @@ class Order(CreatedUpdatedModel): sum=Sum('orderproductrelation__quantity') )['sum'] + @property + def subtotal(self): + return self.products.aggregate( + sum=Sum( + models.F('orderproductrelation__product__price') * + models.F('orderproductrelation__quantity'), + output_field=models.IntegerField() + ) + )['sum'] + + @property + def vat(self): + return (self.subtotal/100)*25 + + @property + def total(self): + return self.subtotal + self.vat + class ProductCategory(CreatedUpdatedModel, UUIDModel): class Meta: diff --git a/shop/templates/order_detail.html b/shop/templates/order_detail.html index 6892be32..05f5ce37 100644 --- a/shop/templates/order_detail.html +++ b/shop/templates/order_detail.html @@ -48,7 +48,26 @@ {% endfor %} -{# TODO: Add total + VAT info #} + + + + Subtotal + + {{ order.subtotal }} + + + + + VAT (25%) + + {{ order.vat }} + + + + + Total + + {{ order.total }} diff --git a/shop/views.py b/shop/views.py index 4c68d6af..f35326f0 100644 --- a/shop/views.py +++ b/shop/views.py @@ -60,16 +60,13 @@ class OrderDetailView(LoginRequiredMixin, DetailView): context_object_name = 'order' def get(self, request, *args, **kwargs): - if self.get_object().user != request.user: + order = self.get_object() + + if order.user != request.user: raise Http404("Order not found") - if self.get_object().paid: - messages.error(request, 'This order is already paid for!') - return HttpResponseRedirect('shop:order_detail') - - if not self.get_object().products: - messages.error(request, 'This order contains no products!') - return HttpResponseRedirect('shop:order_detail') + if not order.products.count() > 0: + return HttpResponseRedirect(reverse_lazy('shop:index')) return super(OrderDetailView, self).get(request, *args, **kwargs) @@ -111,6 +108,8 @@ class OrderDetailView(LoginRequiredMixin, DetailView): product_remove = request.POST.get('remove_product') if product_remove: order.orderproductrelation_set.filter(pk=product_remove).delete() + if not order.products.count() > 0: + return HttpResponseRedirect(reverse_lazy('shop:index')) return super(OrderDetailView, self).get(request, *args, **kwargs)