Pages are rendered server-side (SEO, no build step), the interactive parts talk to the existing REST API from the browser: - home: banners, categories, hits and new arrivals - catalog: filters (category, brand, price, stock), search, sorting, pagination, filter chips with one-click removal - product card: gallery, price with discount, stock, characteristics, related products - cart: localStorage, quantity controls, live totals - checkout: contacts, delivery, promo code, bonuses, order submission with Idempotency-Key, success screen - login: OTP by phone (debug code shown in dev) and phone/password - account: profile, orders, addresses, bonuses through the API with JWT - static pages from the admin Supporting pieces: - apps/storefront app with views, urls, templates and static CSS/JS - money/discount/attribute template filters - seed_demo management command with demo catalog, banners and pages - Cyrillic search fallback for SQLite: local DB does not fold case for non-ASCII, production PostgreSQL does Tests: 16 storefront cases (pages, filters, search, ordering, 404s, filters formatting); the suite is 61 passing.
247 lines
7.7 KiB
Python
247 lines
7.7 KiB
Python
"""Storefront views: server-rendered pages for customers."""
|
|
|
|
from urllib.parse import urlencode
|
|
|
|
from django.core.paginator import Paginator
|
|
from django.db import connection
|
|
from django.db.models import Max, Min, Q
|
|
from django.http import Http404
|
|
from django.shortcuts import get_object_or_404, render
|
|
from django.utils import timezone
|
|
|
|
from apps.catalog.models import Category, Product
|
|
from apps.content.models import Banner, SiteSettings, StaticPage
|
|
|
|
PAGE_SIZE = 12
|
|
|
|
ORDERING_CHOICES = [
|
|
("-created_at", "Сначала новые"),
|
|
("price", "Сначала дешёвые"),
|
|
("-price", "Сначала дорогие"),
|
|
("-is_hit", "Популярные"),
|
|
("name", "По названию"),
|
|
]
|
|
ORDERING_FIELDS = {value for value, _ in ORDERING_CHOICES}
|
|
|
|
|
|
def _common(request) -> dict:
|
|
"""Context shared by every storefront page."""
|
|
return {
|
|
"site": SiteSettings.load(),
|
|
"menu_categories": Category.objects.filter(is_active=True).order_by(
|
|
"sort_order", "name"
|
|
),
|
|
"footer_pages": StaticPage.objects.filter(is_published=True).order_by("title"),
|
|
}
|
|
|
|
|
|
def _active_banners(position: str):
|
|
now = timezone.now()
|
|
return (
|
|
Banner.objects.filter(is_active=True, position=position)
|
|
.filter(Q(starts_at__isnull=True) | Q(starts_at__lte=now))
|
|
.filter(Q(ends_at__isnull=True) | Q(ends_at__gte=now))
|
|
.order_by("sort_order", "id")
|
|
)
|
|
|
|
|
|
def _product_cards(queryset, limit=None):
|
|
queryset = queryset.prefetch_related("images")
|
|
return queryset[:limit] if limit else queryset
|
|
|
|
|
|
def _apply_search(products, search: str):
|
|
"""Case-insensitive search over name, SKU, brand and description.
|
|
|
|
PostgreSQL (production) folds Cyrillic case in ILIKE; SQLite does not, which
|
|
makes Russian search case-sensitive in the local database. For SQLite we
|
|
filter in Python so the dev storefront behaves like production.
|
|
"""
|
|
if connection.vendor == "sqlite":
|
|
needle = search.lower()
|
|
matched = [
|
|
row[0]
|
|
for row in products.values_list(
|
|
"id", "name", "sku", "brand", "description"
|
|
)
|
|
if needle in " ".join(row[1:]).lower()
|
|
]
|
|
return products.filter(pk__in=matched)
|
|
|
|
return products.filter(
|
|
Q(name__icontains=search)
|
|
| Q(sku__icontains=search)
|
|
| Q(brand__icontains=search)
|
|
| Q(description__icontains=search)
|
|
)
|
|
|
|
|
|
def home(request):
|
|
products = Product.objects.filter(is_active=True)
|
|
context = {
|
|
**_common(request),
|
|
"banners": _active_banners("home_top"),
|
|
"hits": _product_cards(products.filter(is_hit=True), 8),
|
|
"new": _product_cards(products.filter(is_new=True), 4),
|
|
"categories": Category.objects.filter(is_active=True).order_by(
|
|
"sort_order", "name"
|
|
)[:6],
|
|
}
|
|
return render(request, "storefront/home.html", context)
|
|
|
|
|
|
def catalog(request):
|
|
products = Product.objects.filter(is_active=True).select_related("category")
|
|
|
|
category_slug = request.GET.get("category", "").strip()
|
|
brand = request.GET.get("brand", "").strip()
|
|
search = request.GET.get("search", "").strip()
|
|
price_min = request.GET.get("price_min", "").strip()
|
|
price_max = request.GET.get("price_max", "").strip()
|
|
in_stock = request.GET.get("in_stock", "").strip()
|
|
ordering = request.GET.get("ordering", "").strip()
|
|
if ordering not in ORDERING_FIELDS:
|
|
ordering = "-created_at"
|
|
|
|
selected_category = None
|
|
if category_slug:
|
|
selected_category = Category.objects.filter(
|
|
slug=category_slug, is_active=True
|
|
).first()
|
|
if selected_category is not None:
|
|
products = products.filter(category=selected_category)
|
|
|
|
if brand:
|
|
products = products.filter(brand=brand)
|
|
if search:
|
|
products = _apply_search(products, search)
|
|
if price_min.isdigit():
|
|
products = products.filter(price__gte=int(price_min))
|
|
if price_max.isdigit():
|
|
products = products.filter(price__lte=int(price_max))
|
|
if in_stock == "1":
|
|
products = products.filter(stock__gt=0)
|
|
|
|
products = products.order_by(ordering, "-id")
|
|
|
|
paginator = Paginator(products, PAGE_SIZE)
|
|
page = paginator.get_page(request.GET.get("page"))
|
|
|
|
filters = {
|
|
key: value
|
|
for key, value in {
|
|
"category": category_slug,
|
|
"brand": brand,
|
|
"search": search,
|
|
"price_min": price_min,
|
|
"price_max": price_max,
|
|
"in_stock": in_stock,
|
|
"ordering": ordering,
|
|
}.items()
|
|
if value
|
|
}
|
|
|
|
bounds = Product.objects.filter(is_active=True).aggregate(
|
|
low=Min("price"), high=Max("price")
|
|
)
|
|
|
|
chips = []
|
|
chip_labels = {
|
|
"category": "Категория",
|
|
"brand": "Бренд",
|
|
"search": "Поиск",
|
|
"price_min": "Цена от",
|
|
"price_max": "Цена до",
|
|
"in_stock": "Только в наличии",
|
|
}
|
|
for key, value in filters.items():
|
|
if not value or key == "ordering":
|
|
continue
|
|
if key == "category" and selected_category is not None:
|
|
shown = selected_category.name
|
|
elif key == "in_stock":
|
|
shown = ""
|
|
else:
|
|
shown = value
|
|
rest = {name: val for name, val in filters.items() if name != key}
|
|
chips.append(
|
|
{
|
|
"label": chip_labels.get(key, key),
|
|
"value": shown,
|
|
"qs": urlencode(rest),
|
|
}
|
|
)
|
|
|
|
context = {
|
|
**_common(request),
|
|
"page": page,
|
|
"products": page.object_list,
|
|
"selected_category": selected_category,
|
|
"categories": Category.objects.filter(is_active=True).order_by(
|
|
"sort_order", "name"
|
|
),
|
|
"brands": list(
|
|
Product.objects.filter(is_active=True)
|
|
.exclude(brand="")
|
|
.values_list("brand", flat=True)
|
|
.distinct()
|
|
.order_by("brand")
|
|
),
|
|
"ordering_choices": ORDERING_CHOICES,
|
|
"filters": filters,
|
|
"selected_ordering": ordering,
|
|
"price_bounds": bounds,
|
|
"chips": chips,
|
|
"querystring": urlencode(filters),
|
|
"has_filters": bool(chips),
|
|
"total": paginator.count,
|
|
}
|
|
return render(request, "storefront/catalog.html", context)
|
|
|
|
|
|
def product_detail(request, slug):
|
|
product = get_object_or_404(
|
|
Product.objects.prefetch_related("images"), slug=slug, is_active=True
|
|
)
|
|
related = (
|
|
Product.objects.filter(is_active=True, category=product.category)
|
|
.exclude(pk=product.pk)
|
|
.prefetch_related("images")[:4]
|
|
if product.category
|
|
else Product.objects.none()
|
|
)
|
|
|
|
attributes = product.attributes if isinstance(product.attributes, dict) else {}
|
|
context = {
|
|
**_common(request),
|
|
"product": product,
|
|
"images": list(product.images.all()),
|
|
"attributes": attributes,
|
|
"related": related,
|
|
"in_stock": product.stock > 0,
|
|
}
|
|
return render(request, "storefront/product.html", context)
|
|
|
|
|
|
def cart(request):
|
|
return render(request, "storefront/cart.html", {**_common(request)})
|
|
|
|
|
|
def checkout(request):
|
|
return render(request, "storefront/checkout.html", {**_common(request)})
|
|
|
|
|
|
def login_view(request):
|
|
return render(request, "storefront/login.html", {**_common(request)})
|
|
|
|
|
|
def account(request):
|
|
return render(request, "storefront/account.html", {**_common(request)})
|
|
|
|
|
|
def static_page(request, slug):
|
|
page = StaticPage.objects.filter(slug=slug, is_published=True).first()
|
|
if page is None:
|
|
raise Http404("Страница не найдена")
|
|
return render(request, "storefront/page.html", {**_common(request), "page": page})
|