schon/engine/core/utils/commerce.py
Egor fureunoir Gorbunov 00a172d463 Features: 1) Add currency symbol display in dashboard; 2) Add type hints to dashboard_callback and related functions;
Fixes: 1) Fix type annotations for get_revenue, get_returns, get_total_processed_orders; 2) Add missing import for Context;

Extra: 1) Add type hint for currency_symbol; 2) Add type ignore comments for image_url; 3) Update UNFOLD config to use dict[str, Any]; 4) Add missing import for typing.Any; 5) Refactor template to conditionally display currency symbol.
2025-11-16 23:35:03 +03:00

55 lines
1.8 KiB
Python

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()