from datetime import timedelta from constance import config from django.db.models import F, QuerySet, Sum from django.db.models.functions import Coalesce from django.utils.timezone import now from engine.core.models import Order, OrderProduct def get_period_order_products( period: timedelta = timedelta(days=30), statuses: list[str] | None = None ) -> QuerySet[OrderProduct]: if statuses is None: statuses = ["FINISHED"] current = now() perioded = current - period orders = Order.objects.filter(status="FINISHED", buy_time__lte=current, buy_time__gte=perioded) return OrderProduct.objects.filter(status__in=statuses, order__in=orders) def get_revenue(clear: bool = True, period: timedelta = timedelta(days=30)) -> float: order_products = get_period_order_products(period) total: float = ( order_products.aggregate(total=Coalesce(Sum(F("buy_price") * F("quantity")), 0.0)).get("total") or 0.0 ) try: total = float(total) except (TypeError, ValueError): total = 0.0 if clear: try: tax_rate = float(config.TAX_RATE or 0) except (TypeError, ValueError): tax_rate = 0.0 net = total * (1 - tax_rate / 100.0) return round(net, 2) else: return round(float(total), 2) def get_returns(period: timedelta = timedelta(days=30)) -> float: order_products = get_period_order_products(period, ["RETURNED"]) total_returns: float = ( order_products.aggregate(total=Coalesce(Sum(F("buy_price") * F("quantity")), 0.0)).get("total") or 0.0 ) try: return round(float(total_returns), 2) except (TypeError, ValueError): return 0.0 def get_total_processed_orders(period: timedelta = timedelta(days=30)) -> int: return get_period_order_products(period, ["RETURNED", "FINISHED"]).count()