Fixes: 1) None. Extra: 1) Refactored language flag definitions into a centralized dictionary in base settings; 2) Added commerce utility functions for revenue, returns, and order processing; 3) Improved code structure and documentation in views and utils.
52 lines
1.8 KiB
Python
52 lines
1.8 KiB
Python
from datetime import timedelta
|
|
|
|
from django.db.models import F, Sum
|
|
from django.db.models.functions import Coalesce
|
|
from django.utils.timezone import now
|
|
from constance import config
|
|
from engine.core.models import Order, OrderProduct
|
|
|
|
|
|
def get_period_order_products(period: timedelta = timedelta(days=30), statuses: list[str] | None = None):
|
|
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)):
|
|
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)):
|
|
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)):
|
|
return get_period_order_products(period, ["RETURNED", "FINISHED"]).count()
|