From 0e0374b5772197ce56a1d532db2efa914ef5e56a Mon Sep 17 00:00:00 2001 From: Thomas Steen Rasmussen Date: Thu, 22 Jul 2021 00:07:30 +0200 Subject: [PATCH] calculate profit in the database, skip the margin calculation for now --- .../templates/ticket_stats_detail.html | 18 ++++++++------ src/shop/models.py | 24 +++++++------------ 2 files changed, 19 insertions(+), 23 deletions(-) diff --git a/src/backoffice/templates/ticket_stats_detail.html b/src/backoffice/templates/ticket_stats_detail.html index 9637a194..7cc54208 100644 --- a/src/backoffice/templates/ticket_stats_detail.html +++ b/src/backoffice/templates/ticket_stats_detail.html @@ -14,24 +14,28 @@ Product - Orders - Units Sold Revenue Cost Profit - Margin + Orders + Units Sold + Total Revenue + Total Cost + Total Profit {% for p in product_list %} {{ p.name }} + {{ p.price|floatformat:"2" }} DKK + {{ p.cost|floatformat:"2" }} DKK + {{ p.profit|floatformat:"2" }} DKK {{ p.order_set.count }} {{ p.total_units_sold }} - {{ p.price|floatformat:"2" }} DKK - {{ p.cost|floatformat:"2" }} DKK - {{ p.profit|floatformat:"2" }} DKK - {{ p.margin|floatformat:"2" }}% + {{ p.total_revenue|floatformat:"2" }} DKK + {{ p.total_cost|floatformat:"2" }} DKK + {{ p.total_profit|floatformat:"2" }} DKK {% endfor %} diff --git a/src/shop/models.py b/src/shop/models.py index efbd3665..bb70cec7 100644 --- a/src/shop/models.py +++ b/src/shop/models.py @@ -7,7 +7,7 @@ from django.contrib import messages from django.contrib.postgres.fields import DateTimeRangeField from django.core.exceptions import ValidationError from django.db import models -from django.db.models.aggregates import Sum +from django.db.models import F, Sum from django.urls import reverse_lazy from django.utils import timezone from django.utils.dateparse import parse_datetime @@ -396,7 +396,13 @@ class ProductCategory(CreatedUpdatedModel, UUIDModel): class ProductStatsManager(models.Manager): def with_ticket_stats(self): - return self.annotate(total_units_sold=Sum("orderproductrelation__quantity")) + return ( + self.annotate(total_units_sold=Sum("orderproductrelation__quantity")) + .annotate(profit=F("price") - F("cost")) + .annotate(total_revenue=F("price") * F("total_units_sold")) + .annotate(total_cost=F("cost") * F("total_units_sold")) + .annotate(total_profit=F("profit") * F("total_units_sold")) + ) class Product(CreatedUpdatedModel, UUIDModel): @@ -512,20 +518,6 @@ class Product(CreatedUpdatedModel, UUIDModel): # If there is no stock defined the product is generally available. return True - @property - def profit(self): - try: - return self.price - self.cost - except ValueError: - return 0 - - @property - def margin(self): - try: - return (self.profit / self.price) * 100 - except ValueError: - return 0 - class OrderProductRelation(CreatedUpdatedModel): order = models.ForeignKey("shop.Order", on_delete=models.PROTECT)