diff --git a/backend/apps/storefront/__init__.py b/backend/apps/storefront/__init__.py
new file mode 100644
index 0000000..f5ae612
--- /dev/null
+++ b/backend/apps/storefront/__init__.py
@@ -0,0 +1,6 @@
+"""Storefront: server-rendered pages for customers.
+
+The catalog is rendered on the server (SEO and speed), while the interactive
+parts — cart, checkout, account — talk to the existing REST API from the
+browser. No build step and no JavaScript framework: plain Django templates.
+"""
diff --git a/backend/apps/storefront/apps.py b/backend/apps/storefront/apps.py
new file mode 100644
index 0000000..63cd56c
--- /dev/null
+++ b/backend/apps/storefront/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class StorefrontConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "apps.storefront"
+ verbose_name = "Витрина"
diff --git a/backend/apps/storefront/management/__init__.py b/backend/apps/storefront/management/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/backend/apps/storefront/management/commands/__init__.py b/backend/apps/storefront/management/commands/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/backend/apps/storefront/management/commands/seed_demo.py b/backend/apps/storefront/management/commands/seed_demo.py
new file mode 100644
index 0000000..8234de3
--- /dev/null
+++ b/backend/apps/storefront/management/commands/seed_demo.py
@@ -0,0 +1,224 @@
+"""Демонстрационные данные, чтобы витрину можно было посмотреть до подключения 1С."""
+
+from decimal import Decimal
+
+from django.core.management.base import BaseCommand
+from django.db import transaction
+
+from apps.catalog.models import Category, Product
+from apps.common.utils import make_slug
+from apps.content.models import Banner, SiteSettings, StaticPage
+
+CATEGORIES = [
+ ("demo-cat-outer", "Верхняя одежда", "verhnyaya-odezhda", 10),
+ ("demo-cat-knit", "Трикотаж", "trikotazh", 20),
+ ("demo-cat-accessories", "Аксессуары", "aksessuary", 30),
+]
+
+PRODUCTS = [
+ {
+ "external_id": "demo-p-1042",
+ "sku": "HM-1042",
+ "name": "Куртка Softshell",
+ "category": "demo-cat-outer",
+ "brand": "HOMM",
+ "price": "12990.00",
+ "old_price": "14990.00",
+ "stock": 12,
+ "is_hit": True,
+ "short": "Ветрозащитная куртка на флисовой подкладке.",
+ "description": "Мембрана 10 000 мм, проклеенные швы, съёмный капюшон. "
+ "Подходит для города и коротких вылазок.",
+ "attributes": {"Цвет": "Чёрный", "Состав": "Полиэстер 100%", "Размеры": "46–54",
+ "Сезон": "Демисезон"},
+ },
+ {
+ "external_id": "demo-p-2011",
+ "sku": "HM-2011",
+ "name": "Пальто шерстяное",
+ "category": "demo-cat-outer",
+ "brand": "HOMM",
+ "price": "24900.00",
+ "stock": 3,
+ "short": "Прямого кроя, на подкладке.",
+ "attributes": {"Цвет": "Тёмно-серый", "Состав": "Шерсть 70%, полиэстер 30%",
+ "Размеры": "44–52"},
+ },
+ {
+ "external_id": "demo-p-3005",
+ "sku": "HM-3005",
+ "name": "Свитер мериносовый",
+ "category": "demo-cat-knit",
+ "brand": "HOMM",
+ "price": "8900.00",
+ "old_price": "9900.00",
+ "stock": 20,
+ "is_new": True,
+ "attributes": {"Цвет": "Кэмел", "Состав": "Меринос 100%", "Размеры": "S–XL"},
+ },
+ {
+ "external_id": "demo-p-3102",
+ "sku": "HM-3102",
+ "name": "Рубашка оксфорд",
+ "category": "demo-cat-knit",
+ "brand": "HOMM",
+ "price": "6490.00",
+ "stock": 7,
+ "attributes": {"Цвет": "Белый", "Состав": "Хлопок 100%", "Размеры": "S–XXL"},
+ },
+ {
+ "external_id": "demo-p-3201",
+ "sku": "HM-3201",
+ "name": "Футболка базовая",
+ "category": "demo-cat-knit",
+ "brand": "HOMM",
+ "price": "2490.00",
+ "stock": 40,
+ "is_hit": True,
+ "is_new": True,
+ "attributes": {"Цвет": "Белый", "Состав": "Хлопок 95%, эластан 5%", "Размеры": "S–XXL"},
+ },
+ {
+ "external_id": "demo-p-3300",
+ "sku": "HM-3300",
+ "name": "Джинсы прямые",
+ "category": "demo-cat-knit",
+ "brand": "HOMM",
+ "price": "9900.00",
+ "stock": 0,
+ "attributes": {"Цвет": "Индиго", "Состав": "Хлопок 98%, эластан 2%",
+ "Размеры": "28–38"},
+ },
+ {
+ "external_id": "demo-p-4001",
+ "sku": "HM-4001",
+ "name": "Шарф кашемировый",
+ "category": "demo-cat-accessories",
+ "brand": "HOMM",
+ "price": "5900.00",
+ "stock": 15,
+ "is_new": True,
+ "attributes": {"Цвет": "Серый меланж", "Состав": "Кашемир 100%", "Размер": "180×30 см"},
+ },
+ {
+ "external_id": "demo-p-4002",
+ "sku": "HM-4002",
+ "name": "Ремень кожаный",
+ "category": "demo-cat-accessories",
+ "brand": "HOMM",
+ "price": "4900.00",
+ "stock": 9,
+ "is_hit": True,
+ "attributes": {"Цвет": "Чёрный", "Материал": "Натуральная кожа", "Ширина": "35 мм"},
+ },
+ {
+ "external_id": "demo-p-4003",
+ "sku": "HM-4003",
+ "name": "Перчатки кожаные",
+ "category": "demo-cat-accessories",
+ "brand": "HOMM",
+ "price": "6900.00",
+ "stock": 4,
+ "attributes": {"Цвет": "Коричневый", "Материал": "Кожа овчины", "Подкладка": "Шерсть"},
+ },
+]
+
+PAGES = [
+ ("dostavka-i-oplata", "Доставка и оплата",
+ "Курьером по Москве — 490 ₽, бесплатно при заказе от 15 000 ₽. "
+ "Самовывоз из пункта выдачи — бесплатно.\n\n"
+ "Оплата картой онлайн, через СБП или при получении."),
+ ("politika-konfidencialnosti", "Политика конфиденциальности",
+ "Мы обрабатываем персональные данные (имя, телефон, email, адрес доставки) "
+ "только для исполнения заказа и связи с покупателем.\n\n"
+ "Данные не передаются третьим лицам, кроме служб доставки и платёжного провайдера."),
+]
+
+
+class Command(BaseCommand):
+ help = "Создаёт демонстрационные товары, категории, баннер и страницы."
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ "--reset",
+ action="store_true",
+ help="Удалить ранее созданные демо-товары и категории.",
+ )
+
+ @transaction.atomic
+ def handle(self, *args, **options):
+ if options["reset"]:
+ removed = Product.objects.filter(external_id__startswith="demo-p-").delete()
+ Category.objects.filter(external_id__startswith="demo-cat-").delete()
+ self.stdout.write(self.style.WARNING(f"Удалено записей: {removed[0]}"))
+ return
+
+ site = SiteSettings.load()
+ site.site_name = site.site_name or "HOMM"
+ site.phone = site.phone or "+7 (495) 120-33-45"
+ site.email = site.email or "shop@homm.ru"
+ site.address = site.address or "Москва, ул. Тверская, 12"
+ site.working_hours = site.working_hours or "Пн–Вс, 10:00–21:00"
+ site.telegram_url = site.telegram_url or "https://t.me/homm"
+ site.free_delivery_threshold = site.free_delivery_threshold or Decimal("15000.00")
+ site.default_delivery_cost = site.default_delivery_cost or Decimal("490.00")
+ site.bonus_accrual_percent = site.bonus_accrual_percent or Decimal("5.00")
+ site.bonus_max_payment_percent = site.bonus_max_payment_percent or Decimal("30.00")
+ site.save()
+
+ categories = {}
+ for external_id, name, slug, order in CATEGORIES:
+ category, _ = Category.objects.update_or_create(
+ external_id=external_id,
+ defaults={
+ "name": name,
+ "slug": slug,
+ "sort_order": order,
+ "is_active": True,
+ },
+ )
+ categories[external_id] = category
+
+ for item in PRODUCTS:
+ Product.objects.update_or_create(
+ external_id=item["external_id"],
+ defaults={
+ "sku": item["sku"],
+ "name": item["name"],
+ "slug": make_slug(f"{item['name']} {item['sku']}"),
+ "category": categories[item["category"]],
+ "brand": item.get("brand", ""),
+ "short_description": item.get("short", ""),
+ "description": item.get("description", ""),
+ "price": Decimal(item["price"]),
+ "old_price": Decimal(item["old_price"]) if item.get("old_price") else None,
+ "stock": item["stock"],
+ "is_hit": item.get("is_hit", False),
+ "is_new": item.get("is_new", False),
+ "is_active": True,
+ "attributes": item.get("attributes", {}),
+ },
+ )
+
+ Banner.objects.update_or_create(
+ title="Новая коллекция",
+ position="home_top",
+ defaults={
+ "link_url": "/catalog/",
+ "sort_order": 1,
+ "is_active": True,
+ },
+ )
+
+ for slug, title, content in PAGES:
+ StaticPage.objects.update_or_create(
+ slug=slug,
+ defaults={"title": title, "content": content, "is_published": True},
+ )
+
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"Готово: категорий {len(CATEGORIES)}, товаров {len(PRODUCTS)}, "
+ f"страниц {len(PAGES)}, баннер 1."
+ )
+ )
diff --git a/backend/apps/storefront/static/storefront/css/storefront.css b/backend/apps/storefront/static/storefront/css/storefront.css
new file mode 100644
index 0000000..1168f20
--- /dev/null
+++ b/backend/apps/storefront/static/storefront/css/storefront.css
@@ -0,0 +1,334 @@
+/* HOMM storefront — minimal, airy, one accent colour. */
+
+:root {
+ --ink: #14161a;
+ --ink-soft: #3d4450;
+ --muted: #737c8a;
+ --line: #e6e8ec;
+ --paper: #ffffff;
+ --sand: #f7f5f1;
+ --accent: #b07d3f;
+ --accent-dark: #8d6230;
+ --danger: #b3261e;
+ --ok: #0b7a3b;
+ --radius: 12px;
+ --shadow: 0 10px 30px rgba(20, 22, 26, .08);
+ --max: 1240px;
+}
+
+* { box-sizing: border-box; }
+
+html { -webkit-text-size-adjust: 100%; }
+
+body {
+ margin: 0;
+ font: 16px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ color: var(--ink);
+ background: var(--paper);
+}
+
+img { max-width: 100%; display: block; }
+
+a { color: inherit; text-decoration: none; }
+a:hover { color: var(--accent-dark); }
+
+h1, h2, h3, h4 { line-height: 1.2; margin: 0 0 12px; letter-spacing: -.01em; }
+h1 { font-size: 34px; }
+h2 { font-size: 26px; }
+h3 { font-size: 19px; }
+
+p { margin: 0 0 12px; }
+
+.container { max-width: var(--max); margin: 0 auto; padding: 0 20px; }
+
+/* ---------- header ---------- */
+
+.site-header { border-bottom: 1px solid var(--line); background: var(--paper); }
+.header-top {
+ display: flex; align-items: center; gap: 24px;
+ padding: 18px 0;
+}
+.logo { font-size: 22px; font-weight: 700; letter-spacing: .16em; }
+.logo span { color: var(--accent); }
+.header-nav { display: flex; gap: 20px; margin-left: 8px; flex: 1 1 auto; min-width: 0; flex-wrap: wrap; }
+.header-nav a { font-size: 14px; color: var(--ink-soft); }
+.header-actions { display: flex; align-items: center; gap: 18px; }
+.header-actions a { font-size: 14px; display: inline-flex; align-items: center; gap: 6px; }
+.cart-badge {
+ min-width: 20px; height: 20px; border-radius: 10px; background: var(--accent);
+ color: #fff; font-size: 12px; font-weight: 600; display: inline-flex;
+ align-items: center; justify-content: center; padding: 0 6px;
+}
+.cart-badge[hidden] { display: none; }
+
+.header-search { padding: 0 0 16px; }
+.header-search form { display: flex; gap: 10px; }
+.header-search input {
+ flex: 1; padding: 12px 16px; border: 1px solid var(--line);
+ border-radius: 10px; font-size: 15px; background: var(--sand);
+}
+.header-search input:focus { outline: 2px solid #e6d3b7; border-color: var(--accent); }
+
+/* ---------- buttons / forms ---------- */
+
+.btn {
+ display: inline-flex; align-items: center; justify-content: center; gap: 8px;
+ padding: 12px 22px; border-radius: 10px; border: 1px solid transparent;
+ font-size: 15px; font-weight: 500; cursor: pointer; transition: .18s ease;
+ background: var(--ink); color: #fff;
+}
+.btn:hover { background: #000; color: #fff; }
+.btn-accent { background: var(--accent); }
+.btn-accent:hover { background: var(--accent-dark); }
+.btn-outline { background: transparent; color: var(--ink); border-color: var(--line); }
+.btn-outline:hover { border-color: var(--ink); color: var(--ink); }
+.btn-ghost { background: transparent; color: var(--muted); padding: 8px 12px; }
+.btn-ghost:hover { color: var(--danger); }
+.btn-block { width: 100%; }
+.btn[disabled] { opacity: .5; cursor: not-allowed; }
+.btn-sm { padding: 8px 14px; font-size: 14px; }
+
+.field { margin-bottom: 16px; }
+.field label { display: block; font-size: 14px; color: var(--muted); margin-bottom: 6px; }
+.field input, .field select, .field textarea {
+ width: 100%; padding: 12px 14px; border: 1px solid var(--line);
+ border-radius: 10px; font: inherit; background: #fff;
+}
+.field input:focus, .field select:focus, .field textarea:focus {
+ outline: 2px solid #e6d3b7; border-color: var(--accent);
+}
+.field textarea { min-height: 90px; resize: vertical; }
+.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
+.form-note { font-size: 13px; color: var(--muted); }
+.form-error { color: var(--danger); font-size: 14px; margin-top: 8px; }
+
+/* ---------- layout blocks ---------- */
+
+main { min-height: 60vh; padding: 32px 0 60px; }
+.page-head { margin-bottom: 24px; }
+.page-head p { color: var(--muted); max-width: 720px; }
+.breadcrumbs { font-size: 13px; color: var(--muted); margin-bottom: 18px; }
+.breadcrumbs a { color: var(--muted); }
+.breadcrumbs span { color: var(--ink-soft); }
+
+.section { margin-bottom: 56px; }
+.section-head { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; margin-bottom: 20px; }
+.section-head a { font-size: 14px; color: var(--accent-dark); }
+
+/* ---------- hero / banners ---------- */
+
+.hero {
+ position: relative; border-radius: var(--radius); overflow: hidden;
+ background: linear-gradient(120deg, #1b1e24, #3a3225);
+ color: #fff; padding: 64px 48px; margin-bottom: 48px;
+}
+.hero h1 { font-size: 40px; max-width: 640px; margin-bottom: 14px; }
+.hero p { color: rgba(255,255,255,.75); max-width: 520px; }
+.hero .btn { margin-top: 12px; }
+.hero-image { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; opacity: .45; }
+
+.banner-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; margin-bottom: 48px; }
+.banner {
+ position: relative; min-height: 180px; border-radius: var(--radius);
+ overflow: hidden; background: var(--sand); padding: 24px;
+ display: flex; flex-direction: column; justify-content: flex-end;
+}
+.banner img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
+.banner h3 { position: relative; }
+
+/* ---------- categories ---------- */
+
+.category-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 14px; }
+.category-tile {
+ position: relative; border-radius: var(--radius); background: var(--sand);
+ padding: 22px; min-height: 120px; display: flex; align-items: flex-end;
+ overflow: hidden; transition: transform .18s ease, box-shadow .18s ease;
+}
+.category-tile:hover { transform: translateY(-2px); box-shadow: var(--shadow); }
+.category-tile img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; opacity: .35; }
+.category-tile span { position: relative; font-weight: 600; }
+
+/* ---------- product cards ---------- */
+
+.product-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 22px; }
+
+.product-card {
+ position: relative; display: flex; flex-direction: column;
+ border: 1px solid var(--line); border-radius: var(--radius);
+ overflow: hidden; background: #fff;
+ transition: transform .18s ease, box-shadow .18s ease, border-color .18s ease;
+}
+.product-card:hover { transform: translateY(-3px); box-shadow: var(--shadow); border-color: #d8dade; }
+
+.product-media {
+ position: relative; aspect-ratio: 1 / 1; background: var(--sand);
+ display: flex; align-items: center; justify-content: center; overflow: hidden;
+}
+.product-media img { width: 100%; height: 100%; object-fit: cover; transition: transform .35s ease; }
+.product-card:hover .product-media img { transform: scale(1.04); }
+.product-media .placeholder {
+ font-size: 34px; font-weight: 700; letter-spacing: .1em; color: #c9c3b8;
+}
+.product-badges { position: absolute; top: 10px; left: 10px; display: flex; gap: 6px; z-index: 2; }
+.badge {
+ font-size: 11px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase;
+ padding: 4px 8px; border-radius: 6px; background: #fff; color: var(--ink);
+}
+.badge-hit { background: #fff1e4; color: #a95e12; }
+.badge-new { background: #e9f4ec; color: #1c6b3a; }
+.badge-stock { background: #eef2f7; color: var(--ink-soft); }
+.badge-out { background: #fbeeed; color: var(--danger); }
+
+.product-body { padding: 14px 16px 18px; display: flex; flex-direction: column; gap: 6px; flex: 1; }
+.product-brand { font-size: 12px; letter-spacing: .08em; text-transform: uppercase; color: var(--muted); }
+.product-name { font-size: 15px; line-height: 1.35; }
+.product-name a:hover { color: var(--accent-dark); }
+.product-price { margin-top: auto; display: flex; align-items: baseline; gap: 8px; padding-top: 8px; }
+.price-now { font-size: 18px; font-weight: 600; }
+.price-old { font-size: 14px; color: var(--muted); text-decoration: line-through; }
+
+.product-actions { padding: 0 16px 16px; }
+
+/* ---------- catalog layout ---------- */
+
+.catalog-layout { display: grid; grid-template-columns: 250px 1fr; gap: 32px; align-items: start; }
+
+.filters { border: 1px solid var(--line); border-radius: var(--radius); padding: 18px; position: sticky; top: 16px; }
+.filters h3 { font-size: 15px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin-bottom: 14px; }
+.filter-group { margin-bottom: 22px; }
+.filter-group h4 { font-size: 14px; margin-bottom: 8px; }
+.filter-list { display: flex; flex-direction: column; gap: 6px; max-height: 220px; overflow: auto; }
+.filter-list a { font-size: 14px; color: var(--ink-soft); padding: 3px 0; }
+.filter-list a.active { color: var(--accent-dark); font-weight: 600; }
+.filter-price { display: flex; gap: 8px; }
+.filter-price input { width: 100%; padding: 9px 10px; border: 1px solid var(--line); border-radius: 8px; font: inherit; }
+.filter-actions { display: flex; flex-direction: column; gap: 8px; }
+
+.catalog-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 20px; flex-wrap: wrap; }
+.catalog-toolbar .count { color: var(--muted); font-size: 14px; }
+.catalog-toolbar select { padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px; font: inherit; background: #fff; }
+.chips { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px; }
+.chip { font-size: 13px; background: var(--sand); border-radius: 20px; padding: 5px 12px; color: var(--ink-soft); }
+.chip a { margin-left: 6px; color: var(--muted); }
+
+.pagination { display: flex; gap: 6px; justify-content: center; margin-top: 32px; flex-wrap: wrap; }
+.pagination a, .pagination span {
+ min-width: 38px; height: 38px; display: inline-flex; align-items: center; justify-content: center;
+ border: 1px solid var(--line); border-radius: 8px; font-size: 14px; padding: 0 10px;
+}
+.pagination .current { background: var(--ink); color: #fff; border-color: var(--ink); }
+
+.empty-state { border: 1px dashed var(--line); border-radius: var(--radius); padding: 48px 24px; text-align: center; color: var(--muted); }
+
+/* ---------- product page ---------- */
+
+.product-layout { display: grid; grid-template-columns: 1.1fr 1fr; gap: 44px; align-items: start; }
+.gallery-main { border-radius: var(--radius); overflow: hidden; background: var(--sand); aspect-ratio: 1 / 1; display: flex; align-items: center; justify-content: center; }
+.gallery-main img { width: 100%; height: 100%; object-fit: cover; }
+.gallery-main .placeholder { font-size: 64px; color: #c9c3b8; letter-spacing: .1em; }
+.gallery-thumbs { display: flex; gap: 10px; margin-top: 12px; flex-wrap: wrap; }
+.gallery-thumbs button { border: 1px solid var(--line); border-radius: 8px; overflow: hidden; padding: 0; width: 72px; height: 72px; background: var(--sand); cursor: pointer; }
+.gallery-thumbs button.active { border-color: var(--accent); }
+.gallery-thumbs img { width: 100%; height: 100%; object-fit: cover; }
+
+.product-info h1 { font-size: 30px; margin-bottom: 10px; }
+.product-sku { font-size: 13px; color: var(--muted); margin-bottom: 16px; }
+.product-price-lg { display: flex; align-items: baseline; gap: 12px; margin: 18px 0; }
+.product-price-lg .price-now { font-size: 30px; }
+.stock { display: inline-flex; align-items: center; gap: 8px; font-size: 14px; margin-bottom: 18px; }
+.stock .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--ok); }
+.stock.out .dot { background: var(--danger); }
+.buy-row { display: flex; gap: 12px; align-items: stretch; margin: 20px 0 12px; }
+.qty { display: inline-flex; align-items: center; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; }
+.qty button { width: 42px; height: 46px; border: 0; background: #fff; font-size: 18px; cursor: pointer; color: var(--ink); }
+.qty input { width: 56px; height: 46px; border: 0; text-align: center; font: inherit; }
+.product-desc { color: var(--ink-soft); margin: 24px 0; }
+.specs { width: 100%; border-collapse: collapse; font-size: 15px; }
+.specs tr { border-bottom: 1px solid var(--line); }
+.specs td { padding: 10px 0; vertical-align: top; }
+.specs td:first-child { color: var(--muted); width: 45%; padding-right: 16px; }
+
+/* ---------- cart ---------- */
+
+.cart-layout { display: grid; grid-template-columns: 1.6fr 1fr; gap: 36px; align-items: start; }
+.cart-list { border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; }
+.cart-row { display: grid; grid-template-columns: 84px 1fr auto; gap: 16px; padding: 16px; border-bottom: 1px solid var(--line); align-items: center; }
+.cart-row:last-child { border-bottom: 0; }
+.cart-thumb { width: 84px; height: 84px; border-radius: 8px; background: var(--sand); overflow: hidden; display: flex; align-items: center; justify-content: center; font-weight: 700; color: #c9c3b8; }
+.cart-thumb img { width: 100%; height: 100%; object-fit: cover; }
+.cart-row h4 { font-size: 15px; margin-bottom: 4px; }
+.cart-row .muted { font-size: 13px; color: var(--muted); }
+.cart-row .row-actions { display: flex; align-items: center; gap: 12px; }
+.summary { border: 1px solid var(--line); border-radius: var(--radius); padding: 22px; position: sticky; top: 16px; }
+.summary h3 { margin-bottom: 16px; }
+.summary-row { display: flex; justify-content: space-between; padding: 8px 0; font-size: 15px; color: var(--ink-soft); }
+.summary-row.total { border-top: 1px solid var(--line); margin-top: 10px; padding-top: 14px; font-size: 19px; color: var(--ink); font-weight: 600; }
+
+/* ---------- account ---------- */
+
+.account-layout { display: grid; grid-template-columns: 220px 1fr; gap: 32px; align-items: start; }
+.account-nav { display: flex; flex-direction: column; gap: 4px; }
+.account-nav button {
+ text-align: left; padding: 11px 14px; border: 0; background: transparent;
+ border-radius: 8px; font: inherit; cursor: pointer; color: var(--ink-soft);
+}
+.account-nav button.active { background: var(--sand); color: var(--ink); font-weight: 600; }
+.account-panel { border: 1px solid var(--line); border-radius: var(--radius); padding: 24px; }
+.panel-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-bottom: 18px; }
+.panel-head h2 { margin: 0; font-size: 22px; }
+
+.order-card { border: 1px solid var(--line); border-radius: 10px; padding: 16px; margin-bottom: 12px; }
+.order-card .order-head { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 10px; }
+.order-card .order-number { font-weight: 600; }
+.order-items { font-size: 14px; color: var(--ink-soft); }
+.balance-card { border-radius: 10px; background: var(--sand); padding: 20px; margin-bottom: 20px; }
+.balance-card .value { font-size: 30px; font-weight: 600; }
+
+/* ---------- toast ---------- */
+
+.toast-stack { position: fixed; right: 20px; bottom: 20px; display: flex; flex-direction: column; gap: 10px; z-index: 100; }
+.toast {
+ background: var(--ink); color: #fff; padding: 12px 16px; border-radius: 10px;
+ font-size: 14px; box-shadow: var(--shadow); animation: toast-in .2s ease;
+ max-width: 340px;
+}
+.toast.error { background: var(--danger); }
+.toast.ok { background: var(--ok); }
+@keyframes toast-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
+
+/* ---------- footer ---------- */
+
+.site-footer { background: var(--sand); border-top: 1px solid var(--line); padding: 44px 0 28px; margin-top: 40px; }
+.footer-grid { display: grid; grid-template-columns: 1.4fr 1fr 1fr; gap: 32px; }
+.footer-grid h4 { font-size: 13px; text-transform: uppercase; letter-spacing: .1em; color: var(--muted); margin-bottom: 12px; }
+.footer-grid a, .footer-grid p { font-size: 14px; color: var(--ink-soft); display: block; margin: 0 0 8px; }
+.footer-bottom { border-top: 1px solid var(--line); margin-top: 28px; padding-top: 18px; font-size: 13px; color: var(--muted); display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
+
+/* ---------- responsive ---------- */
+
+@media (max-width: 1020px) {
+ .catalog-layout, .product-layout, .cart-layout, .account-layout { grid-template-columns: 1fr; }
+ .filters { position: static; }
+ .summary { position: static; }
+ .hero { padding: 44px 28px; }
+ .hero h1 { font-size: 30px; }
+}
+
+@media (max-width: 720px) {
+ h1 { font-size: 26px; }
+ .header-top { flex-wrap: wrap; gap: 12px; }
+ .header-nav {
+ order: 3; flex: 1 0 100%; width: 100%;
+ overflow-x: auto; flex-wrap: nowrap; padding-bottom: 6px;
+ -webkit-overflow-scrolling: touch;
+ }
+ .header-nav a { white-space: nowrap; }
+ .header-actions { margin-left: auto; }
+ .product-grid { grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 14px; }
+ .product-body { padding: 10px 12px 14px; }
+ .product-actions { padding: 0 12px 12px; }
+ .cart-row { grid-template-columns: 64px 1fr; }
+ .cart-thumb { width: 64px; height: 64px; }
+ .footer-grid { grid-template-columns: 1fr; }
+ .field-row { grid-template-columns: 1fr; }
+}
diff --git a/backend/apps/storefront/static/storefront/js/account-page.js b/backend/apps/storefront/static/storefront/js/account-page.js
new file mode 100644
index 0000000..fe15251
--- /dev/null
+++ b/backend/apps/storefront/static/storefront/js/account-page.js
@@ -0,0 +1,233 @@
+/* Account page: profile, orders, addresses and bonuses via the REST API. */
+(function () {
+ 'use strict';
+
+ var HOMM = window.HOMM;
+ if (!document.querySelector('[data-panel]')) { return; }
+
+ if (!HOMM.Auth.isLoggedIn()) {
+ window.location.href = '/login/?next=' + encodeURIComponent(window.location.pathname);
+ return;
+ }
+
+ var STATUS_LABELS = {
+ new: 'Новый',
+ processing: 'В обработке',
+ delivering: 'Доставляется',
+ completed: 'Выполнен',
+ cancelled: 'Отменён'
+ };
+ var PAYMENT_LABELS = {
+ pending: 'Ожидает оплаты',
+ partially_paid: 'Частично оплачен',
+ paid: 'Оплачен',
+ refunded: 'Возвращён'
+ };
+ var REASON_LABELS = {
+ accrual: 'Начисление',
+ spend: 'Списание',
+ refund: 'Возврат',
+ adjustment: 'Корректировка'
+ };
+
+ function showError(message) {
+ HOMM.toast(message, 'error');
+ }
+
+ function loadProfile() {
+ return HOMM.api('/auth/me/').then(function (user) {
+ var greeting = user.full_name
+ ? 'Вы вошли как ' + user.full_name + ' (' + user.phone + ')'
+ : 'Вы вошли как ' + user.phone;
+ document.querySelector('[data-account-hello]').textContent = greeting;
+ document.querySelector('#first_name').value = user.first_name || '';
+ document.querySelector('#last_name').value = user.last_name || '';
+ document.querySelector('#middle_name').value = user.middle_name || '';
+ document.querySelector('#profile_phone').value = user.phone || '';
+ document.querySelector('#profile_email').value = user.email || '';
+ }).catch(function (error) {
+ if (error.status === 401) {
+ HOMM.Auth.logout();
+ window.location.href = '/login/?next=/account/';
+ } else {
+ showError('Не удалось загрузить профиль: ' + error.message);
+ }
+ });
+ }
+
+ function loadOrders() {
+ var container = document.querySelector('[data-orders-list]');
+ return HOMM.api('/orders/').then(function (data) {
+ var orders = data.results || data || [];
+ if (!orders.length) {
+ container.innerHTML =
+ '
Заказов пока нет
' +
+ '
Оформите первый заказ — он появится здесь.
' +
+ '
В каталог ';
+ return;
+ }
+ container.innerHTML = orders.map(function (order) {
+ var items = (order.items || []).map(function (item) {
+ return '' + HOMM.escapeHtml(item.name) + ' × ' + Number(item.quantity) +
+ ' — ' + HOMM.money(item.total) + ' ₽
';
+ }).join('');
+ return '' +
+ '
' +
+ 'Заказ ' + HOMM.escapeHtml(order.number) + '' +
+ '' + HOMM.escapeHtml(STATUS_LABELS[order.status] || order.status) + '' +
+ '
' +
+ '
' + items + '
' +
+ '
' +
+ '' + HOMM.escapeHtml(PAYMENT_LABELS[order.payment_status] || '') +
+ ' · ' + new Date(order.created_at).toLocaleDateString('ru-RU') + '' +
+ '' + HOMM.money(order.total) + ' ₽' +
+ '
' +
+ '
';
+ }).join('');
+ }).catch(function (error) {
+ container.innerHTML = 'Ошибка загрузки заказов: ' +
+ HOMM.escapeHtml(error.message) + '
';
+ });
+ }
+
+ function loadAddresses() {
+ var container = document.querySelector('[data-addresses-list]');
+ return HOMM.api('/auth/addresses/').then(function (addresses) {
+ if (!addresses.length) {
+ container.innerHTML = 'Адресов пока нет.
';
+ return;
+ }
+ container.innerHTML = addresses.map(function (address) {
+ var parts = [address.city, address.street, address.house,
+ address.apartment ? 'кв. ' + address.apartment : ''].filter(Boolean);
+ return '' +
+ '
' +
+ '' + HOMM.escapeHtml(address.title || 'Адрес') +
+ (address.is_default ? ' основной' : '') + '' +
+ '' +
+ '
' +
+ '
' + HOMM.escapeHtml(parts.join(', ')) + '
' +
+ '
';
+ }).join('');
+ }).catch(function (error) {
+ container.innerHTML = 'Не удалось загрузить адреса: ' +
+ HOMM.escapeHtml(error.message) + '
';
+ });
+ }
+
+ function loadBonus() {
+ var amountNode = document.querySelector('[data-bonus-amount]');
+ var historyNode = document.querySelector('[data-bonus-history]');
+ return HOMM.api('/loyalty/bonus/').then(function (account) {
+ amountNode.textContent = HOMM.money(account.balance) + ' ₽';
+ var transactions = account.transactions || [];
+ if (!transactions.length) {
+ historyNode.innerHTML = 'Операций пока не было.
';
+ return;
+ }
+ historyNode.innerHTML = '' + transactions.map(function (item) {
+ var sign = Number(item.amount) > 0 ? '+' : '';
+ return '' + new Date(item.created_at).toLocaleDateString('ru-RU') +
+ ' ' +
+ HOMM.escapeHtml(REASON_LABELS[item.reason] || item.reason) +
+ (item.comment ? ' · ' + HOMM.escapeHtml(item.comment) : '') + ' | ' +
+ '' + sign + HOMM.money(item.amount) + ' ₽ |
';
+ }).join('') + '
';
+ }).catch(function (error) {
+ historyNode.innerHTML = 'Не удалось загрузить бонусы: ' +
+ HOMM.escapeHtml(error.message) + '
';
+ });
+ }
+
+ /* ---------- tabs ---------- */
+
+ var loaded = { orders: false, profile: false, addresses: false, bonus: false };
+ var loaders = {
+ orders: loadOrders,
+ addresses: loadAddresses,
+ bonus: loadBonus
+ };
+
+ function openPanel(name) {
+ document.querySelectorAll('[data-panel]').forEach(function (button) {
+ button.classList.toggle('active', button.dataset.panel === name);
+ });
+ document.querySelectorAll('[data-panel-body]').forEach(function (panel) {
+ panel.hidden = panel.dataset.panelBody !== name;
+ });
+ if (!loaded[name] && loaders[name]) {
+ loaded[name] = true;
+ loaders[name]();
+ }
+ }
+
+ document.querySelectorAll('[data-panel]').forEach(function (button) {
+ button.addEventListener('click', function () { openPanel(button.dataset.panel); });
+ });
+
+ /* ---------- actions ---------- */
+
+ var profileForm = document.querySelector('[data-profile-form]');
+ profileForm.addEventListener('submit', function (event) {
+ event.preventDefault();
+ HOMM.api('/auth/me/', {
+ method: 'PATCH',
+ body: {
+ first_name: profileForm.first_name.value.trim(),
+ last_name: profileForm.last_name.value.trim(),
+ middle_name: profileForm.middle_name.value.trim(),
+ email: profileForm.email.value.trim()
+ }
+ }).then(function () {
+ HOMM.toast('Профиль сохранён', 'ok');
+ loadProfile();
+ }).catch(function (error) {
+ showError('Не удалось сохранить: ' + error.message);
+ });
+ });
+
+ var addressForm = document.querySelector('[data-address-form]');
+ addressForm.addEventListener('submit', function (event) {
+ event.preventDefault();
+ HOMM.api('/auth/addresses/', {
+ method: 'POST',
+ body: {
+ city: addressForm.city.value.trim(),
+ street: addressForm.street.value.trim(),
+ house: addressForm.house.value.trim(),
+ apartment: addressForm.apartment.value.trim(),
+ title: addressForm.title.value.trim(),
+ is_default: addressForm.is_default.checked
+ }
+ }).then(function () {
+ HOMM.toast('Адрес добавлен', 'ok');
+ addressForm.reset();
+ loadAddresses();
+ }).catch(function (error) {
+ showError('Не удалось добавить адрес: ' + error.message);
+ });
+ });
+
+ document.addEventListener('click', function (event) {
+ var button = event.target.closest('[data-remove-address]');
+ if (!button) { return; }
+ if (!window.confirm('Удалить адрес?')) { return; }
+ HOMM.api('/auth/addresses/' + button.dataset.removeAddress + '/', { method: 'DELETE' })
+ .then(function () {
+ HOMM.toast('Адрес удалён', 'ok');
+ loadAddresses();
+ })
+ .catch(function (error) {
+ showError('Не удалось удалить адрес: ' + error.message);
+ });
+ });
+
+ document.querySelector('[data-logout]').addEventListener('click', function () {
+ HOMM.Auth.logout();
+ window.location.href = '/';
+ });
+
+ loadProfile();
+ openPanel('orders');
+})();
diff --git a/backend/apps/storefront/static/storefront/js/cart-page.js b/backend/apps/storefront/static/storefront/js/cart-page.js
new file mode 100644
index 0000000..bc1ebe2
--- /dev/null
+++ b/backend/apps/storefront/static/storefront/js/cart-page.js
@@ -0,0 +1,103 @@
+/* Cart page rendering. Depends on site.js (window.HOMM). */
+(function () {
+ 'use strict';
+
+ var HOMM = window.HOMM;
+ var list = document.querySelector('[data-cart-list]');
+ var empty = document.querySelector('[data-cart-empty]');
+ var subtotalNode = document.querySelector('[data-subtotal]');
+ var totalNode = document.querySelector('[data-total]');
+ var checkoutLink = document.querySelector('[data-checkout-link]');
+ var clearButton = document.querySelector('[data-clear-cart]');
+
+ if (!list) { return; }
+
+ function row(item) {
+ var image = item.image
+ ? '
'
+ : '' + HOMM.escapeHtml((item.name || '?').slice(0, 1)) + '';
+
+ return '' +
+ '' +
+ '
' + image + '' +
+ '
' +
+ '
' +
+ '
' + HOMM.money(item.price) + ' ₽ за шт.
' +
+ '
' +
+ '
' +
+ '
' +
+ '' +
+ '' +
+ '' +
+ '
' +
+ '
' + HOMM.money(Number(item.price) * Number(item.qty)) + ' ₽' +
+ '
' +
+ '
' +
+ '
';
+ }
+
+ function render() {
+ var items = HOMM.Cart.items();
+ if (!items.length) {
+ list.innerHTML = '';
+ list.hidden = true;
+ empty.hidden = false;
+ subtotalNode.textContent = '0 ₽';
+ totalNode.textContent = '0 ₽';
+ if (checkoutLink) { checkoutLink.setAttribute('aria-disabled', 'true'); }
+ return;
+ }
+
+ list.hidden = false;
+ empty.hidden = true;
+ if (checkoutLink) { checkoutLink.removeAttribute('aria-disabled'); }
+
+ list.innerHTML = items.map(row).join('');
+ var subtotal = HOMM.Cart.subtotal();
+ subtotalNode.textContent = HOMM.money(subtotal) + ' ₽';
+ totalNode.textContent = HOMM.money(subtotal) + ' ₽';
+ }
+
+ list.addEventListener('click', function (event) {
+ var rowNode = event.target.closest('.cart-row');
+ if (!rowNode) { return; }
+ var id = Number(rowNode.dataset.id);
+ var input = rowNode.querySelector('[data-qty]');
+ var current = Number(input.value) || 1;
+
+ if (event.target.closest('[data-inc]')) {
+ HOMM.Cart.setQty(id, current + 1);
+ } else if (event.target.closest('[data-dec]')) {
+ HOMM.Cart.setQty(id, current - 1);
+ } else if (event.target.closest('[data-remove]')) {
+ HOMM.Cart.remove(id);
+ HOMM.toast('Товар удалён', 'ok');
+ }
+ });
+
+ list.addEventListener('change', function (event) {
+ if (!event.target.matches('[data-qty]')) { return; }
+ var rowNode = event.target.closest('.cart-row');
+ HOMM.Cart.setQty(Number(rowNode.dataset.id), Number(event.target.value));
+ });
+
+ if (clearButton) {
+ clearButton.addEventListener('click', function () {
+ if (!HOMM.Cart.items().length) { return; }
+ HOMM.Cart.clear();
+ HOMM.toast('Корзина очищена', 'ok');
+ });
+ }
+
+ if (checkoutLink) {
+ checkoutLink.addEventListener('click', function (event) {
+ if (!HOMM.Cart.items().length) {
+ event.preventDefault();
+ HOMM.toast('Корзина пуста', 'error');
+ }
+ });
+ }
+
+ document.addEventListener('cart:change', render);
+ render();
+})();
diff --git a/backend/apps/storefront/static/storefront/js/checkout-page.js b/backend/apps/storefront/static/storefront/js/checkout-page.js
new file mode 100644
index 0000000..3b9eb74
--- /dev/null
+++ b/backend/apps/storefront/static/storefront/js/checkout-page.js
@@ -0,0 +1,250 @@
+/* Checkout: totals, promo code, bonuses and order submission. */
+(function () {
+ 'use strict';
+
+ var HOMM = window.HOMM;
+ var root = document.querySelector('[data-checkout]');
+ if (!root) { return; }
+
+ var freeThreshold = Number(root.dataset.freeThreshold) || 0;
+ var deliveryCost = Number(root.dataset.deliveryCost) || 0;
+ var bonusLimitPercent = Number(root.dataset.bonusLimit) || 0;
+
+ var itemsNode = document.querySelector('[data-checkout-items]');
+ var subtotalNode = document.querySelector('[data-subtotal]');
+ var discountNode = document.querySelector('[data-discount]');
+ var bonusNode = document.querySelector('[data-bonus]');
+ var deliveryNode = document.querySelector('[data-delivery]');
+ var totalNode = document.querySelector('[data-total]');
+ var errorNode = document.querySelector('[data-checkout-error]');
+ var successNode = document.querySelector('[data-order-success]');
+ var form = document.querySelector('[data-checkout-form]');
+ var bonusField = document.querySelector('[data-bonus-field]');
+ var bonusInput = document.querySelector('#bonus_amount');
+ var bonusBalanceNode = document.querySelector('[data-bonus-balance]');
+ var promoNote = document.querySelector('[data-promo-note]');
+ var deliveryMethod = document.querySelector('#delivery_method');
+ var addressField = document.querySelector('[data-address-field]');
+
+ var state = {
+ discount: 0,
+ promoCode: '',
+ bonusBalance: 0,
+ submitting: false
+ };
+
+ function cartItems() {
+ return HOMM.Cart.items();
+ }
+
+ function deliveryValue() {
+ var subtotal = HOMM.Cart.subtotal();
+ if (deliveryMethod && deliveryMethod.value === 'pickup') { return 0; }
+ if (freeThreshold > 0 && subtotal >= freeThreshold) { return 0; }
+ return deliveryCost;
+ }
+
+ function bonusValue(subtotal) {
+ if (!bonusInput || bonusField.hidden) { return 0; }
+ var wanted = Math.max(0, Number(bonusInput.value) || 0);
+ var cap = bonusLimitPercent > 0 ? (subtotal - state.discount) * bonusLimitPercent / 100 : wanted;
+ return Math.min(wanted, state.bonusBalance, Math.max(0, subtotal - state.discount), cap);
+ }
+
+ function totals() {
+ var subtotal = HOMM.Cart.subtotal();
+ var discount = Math.min(state.discount, subtotal);
+ var bonus = bonusValue(subtotal);
+ var delivery = deliveryValue();
+ var total = Math.max(0, subtotal - discount - bonus + delivery);
+ return {
+ subtotal: subtotal,
+ discount: discount,
+ bonus: Math.round(bonus * 100) / 100,
+ delivery: delivery,
+ total: total
+ };
+ }
+
+ function render() {
+ var items = cartItems();
+ if (!items.length) {
+ window.location.href = '/cart/';
+ return;
+ }
+
+ itemsNode.innerHTML = items.map(function (item) {
+ return '' + HOMM.escapeHtml(item.name) +
+ ' × ' + Number(item.qty) + '' +
+ HOMM.money(Number(item.price) * Number(item.qty)) + ' ₽
';
+ }).join('');
+
+ var sum = totals();
+ subtotalNode.textContent = HOMM.money(sum.subtotal) + ' ₽';
+ discountNode.textContent = '−' + HOMM.money(sum.discount) + ' ₽';
+ bonusNode.textContent = '−' + HOMM.money(sum.bonus) + ' ₽';
+ deliveryNode.textContent = sum.delivery > 0 ? HOMM.money(sum.delivery) + ' ₽' : 'бесплатно';
+ totalNode.textContent = HOMM.money(sum.total) + ' ₽';
+ }
+
+ function showError(message) {
+ errorNode.textContent = message;
+ errorNode.hidden = !message;
+ }
+
+ /* ---------- prefill for logged-in users ---------- */
+
+ function prefillProfile() {
+ if (!HOMM.Auth.isLoggedIn()) { return; }
+ HOMM.api('/auth/me/').then(function (user) {
+ var name = [user.last_name, user.first_name].filter(Boolean).join(' ');
+ if (name && !form.customer_name.value) { form.customer_name.value = name; }
+ if (user.phone && !form.phone.value) { form.phone.value = user.phone; }
+ if (user.email && !form.email.value) { form.email.value = user.email; }
+ }).catch(function () { /* anonymous checkout is fine */ });
+
+ HOMM.api('/auth/addresses/').then(function (addresses) {
+ var preferred = (addresses || []).find(function (item) { return item.is_default; }) ||
+ (addresses || [])[0];
+ if (preferred) {
+ var parts = [preferred.city, preferred.street, preferred.house,
+ preferred.apartment ? 'кв. ' + preferred.apartment : ''].filter(Boolean);
+ form.delivery_address.value = parts.join(', ');
+ }
+ }).catch(function () {});
+
+ HOMM.api('/loyalty/bonus/').then(function (account) {
+ state.bonusBalance = Number(account.balance) || 0;
+ if (state.bonusBalance > 0) {
+ bonusBalanceNode.textContent = HOMM.money(state.bonusBalance) + ' ₽';
+ bonusField.hidden = false;
+ bonusInput.max = Math.floor(state.bonusBalance);
+ render();
+ }
+ }).catch(function () {});
+ }
+
+ /* ---------- promo ---------- */
+
+ var promoButton = document.querySelector('[data-apply-promo]');
+ if (promoButton) {
+ promoButton.addEventListener('click', function () {
+ var input = document.querySelector('#promo_code');
+ var code = (input.value || '').trim();
+ if (!code) {
+ state.discount = 0;
+ state.promoCode = '';
+ promoNote.textContent = '';
+ render();
+ return;
+ }
+
+ promoButton.disabled = true;
+ HOMM.api('/loyalty/promo/validate/', {
+ method: 'POST',
+ body: { code: code, subtotal: HOMM.Cart.subtotal() }
+ }).then(function (result) {
+ state.discount = Number(result.discount) || 0;
+ state.promoCode = result.code || code;
+ promoNote.textContent = 'Промокод применён: скидка ' + HOMM.money(state.discount) + ' ₽';
+ render();
+ }).catch(function (error) {
+ state.discount = 0;
+ state.promoCode = '';
+ promoNote.textContent = 'Промокод не подошёл: ' + error.message;
+ render();
+ }).finally(function () {
+ promoButton.disabled = false;
+ });
+ });
+ }
+
+ if (deliveryMethod) {
+ deliveryMethod.addEventListener('change', function () {
+ if (addressField) { addressField.hidden = deliveryMethod.value === 'pickup'; }
+ render();
+ });
+ }
+ if (bonusInput) { bonusInput.addEventListener('input', render); }
+ document.addEventListener('cart:change', render);
+
+ /* ---------- submit ---------- */
+
+ var submitButton = document.querySelector('[data-submit-order]');
+ if (submitButton) {
+ submitButton.addEventListener('click', function () {
+ if (state.submitting) { return; }
+ showError('');
+
+ var items = cartItems();
+ if (!items.length) {
+ showError('Корзина пуста');
+ return;
+ }
+
+ var name = (form.customer_name.value || '').trim();
+ var phone = (form.phone.value || '').trim();
+ if (name.length < 2) {
+ showError('Укажите имя');
+ form.customer_name.focus();
+ return;
+ }
+ if (phone.replace(/\D/g, '').length < 10) {
+ showError('Укажите корректный телефон');
+ form.phone.focus();
+ return;
+ }
+ if (deliveryMethod.value === 'courier' && !(form.delivery_address.value || '').trim()) {
+ showError('Укажите адрес доставки');
+ form.delivery_address.focus();
+ return;
+ }
+
+ var sum = totals();
+ var payload = {
+ items: items.map(function (item) {
+ return { product_id: Number(item.id), quantity: Number(item.qty) };
+ }),
+ customer_name: name,
+ phone: phone,
+ email: (form.email.value || '').trim(),
+ delivery_method: deliveryMethod.value,
+ delivery_address: deliveryMethod.value === 'pickup' ? '' : (form.delivery_address.value || '').trim(),
+ delivery_cost: sum.delivery,
+ comment: (form.comment.value || '').trim(),
+ promo_code: state.promoCode,
+ bonus_amount: sum.bonus,
+ payment_method: form.payment_method.value
+ };
+
+ state.submitting = true;
+ submitButton.disabled = true;
+ submitButton.textContent = 'Отправляем…';
+
+ HOMM.api('/orders/', {
+ method: 'POST',
+ body: payload,
+ headers: { 'Idempotency-Key': (window.crypto && window.crypto.randomUUID)
+ ? window.crypto.randomUUID()
+ : String(Date.now()) + Math.random().toString(16).slice(2) }
+ }).then(function (order) {
+ HOMM.Cart.clear();
+ document.querySelector('[data-order-number]').textContent = order.number || '—';
+ successNode.hidden = false;
+ form.closest('.cart-layout').hidden = true;
+ window.scrollTo({ top: 0, behavior: 'smooth' });
+ }).catch(function (error) {
+ showError(error.status === 400
+ ? 'Проверьте данные: ' + error.message
+ : 'Не удалось создать заказ: ' + error.message);
+ }).finally(function () {
+ state.submitting = false;
+ submitButton.disabled = false;
+ submitButton.textContent = 'Подтвердить заказ';
+ });
+ });
+ }
+
+ prefillProfile();
+ render();
+})();
diff --git a/backend/apps/storefront/static/storefront/js/login-page.js b/backend/apps/storefront/static/storefront/js/login-page.js
new file mode 100644
index 0000000..79d62c5
--- /dev/null
+++ b/backend/apps/storefront/static/storefront/js/login-page.js
@@ -0,0 +1,108 @@
+/* Login page: OTP by phone and phone/password fallback. */
+(function () {
+ 'use strict';
+
+ var HOMM = window.HOMM;
+ var otpForm = document.querySelector('[data-otp-form]');
+ var passwordForm = document.querySelector('[data-password-form]');
+ if (!otpForm) { return; }
+
+ var codeBlock = document.querySelector('[data-code-block]');
+ var requestButton = document.querySelector('[data-request-code]');
+ var otpError = document.querySelector('[data-otp-error]');
+ var passwordError = document.querySelector('[data-password-error]');
+ var codeNote = document.querySelector('[data-code-note]');
+
+ function nextUrl() {
+ var params = new URLSearchParams(window.location.search);
+ var next = params.get('next') || '/account/';
+ return next.indexOf('/') === 0 ? next : '/account/';
+ }
+
+ function showError(node, message) {
+ node.textContent = message || '';
+ node.hidden = !message;
+ }
+
+ function finish(data) {
+ HOMM.Auth.setTokens(data.access, data.refresh);
+ window.location.href = nextUrl();
+ }
+
+ document.querySelectorAll('[data-tab]').forEach(function (button) {
+ button.addEventListener('click', function () {
+ document.querySelectorAll('[data-tab]').forEach(function (other) {
+ other.classList.toggle('active', other === button);
+ });
+ var isOtp = button.dataset.tab === 'otp';
+ otpForm.hidden = !isOtp;
+ passwordForm.hidden = isOtp;
+ });
+ });
+
+ requestButton.addEventListener('click', function () {
+ showError(otpError, '');
+ var phone = (otpForm.phone.value || '').trim();
+ if (phone.replace(/\D/g, '').length < 10) {
+ showError(otpError, 'Введите номер телефона полностью');
+ otpForm.phone.focus();
+ return;
+ }
+
+ requestButton.disabled = true;
+ HOMM.api('/auth/otp/request/', {
+ method: 'POST',
+ auth: false,
+ body: { phone: phone }
+ }).then(function (data) {
+ codeBlock.hidden = false;
+ var note = 'Код отправлен. Действует ' + Math.round((data.expires_in || 300) / 60) + ' мин.';
+ if (data.debug_code) {
+ note += ' Тестовый режим — код: ' + data.debug_code;
+ document.querySelector('#otp_code').value = data.debug_code;
+ }
+ codeNote.textContent = note;
+ document.querySelector('#otp_code').focus();
+ }).catch(function (error) {
+ showError(otpError, 'Не удалось отправить код: ' + error.message);
+ }).finally(function () {
+ requestButton.disabled = false;
+ });
+ });
+
+ otpForm.addEventListener('submit', function (event) {
+ event.preventDefault();
+ showError(otpError, '');
+ var phone = (otpForm.phone.value || '').trim();
+ var code = (otpForm.code.value || '').trim();
+ if (!code) {
+ showError(otpError, 'Введите код из SMS');
+ otpForm.code.focus();
+ return;
+ }
+
+ HOMM.api('/auth/otp/verify/', {
+ method: 'POST',
+ auth: false,
+ body: { phone: phone, code: code }
+ }).then(finish).catch(function (error) {
+ showError(otpError, 'Код не подошёл: ' + error.message);
+ });
+ });
+
+ passwordForm.addEventListener('submit', function (event) {
+ event.preventDefault();
+ showError(passwordError, '');
+
+ HOMM.api('/auth/token/', {
+ method: 'POST',
+ auth: false,
+ body: {
+ phone: (passwordForm.phone.value || '').trim(),
+ password: passwordForm.password.value
+ }
+ }).then(finish).catch(function () {
+ showError(passwordError, 'Неверный номер телефона или пароль');
+ });
+ });
+})();
diff --git a/backend/apps/storefront/static/storefront/js/site.js b/backend/apps/storefront/static/storefront/js/site.js
new file mode 100644
index 0000000..9d74fa8
--- /dev/null
+++ b/backend/apps/storefront/static/storefront/js/site.js
@@ -0,0 +1,258 @@
+/* HOMM storefront: cart storage, API client and small UI helpers.
+ No dependencies, no build step. */
+(function () {
+ 'use strict';
+
+ var CART_KEY = 'homm_cart';
+ var ACCESS_KEY = 'homm_access';
+ var REFRESH_KEY = 'homm_refresh';
+
+ /* ---------- helpers ---------- */
+
+ function readJson(key, fallback) {
+ try {
+ var raw = localStorage.getItem(key);
+ return raw ? JSON.parse(raw) : fallback;
+ } catch (error) {
+ return fallback;
+ }
+ }
+
+ function escapeHtml(value) {
+ return String(value === undefined || value === null ? '' : value)
+ .replace(/&/g, '&')
+ .replace(//g, '>')
+ .replace(/"/g, '"')
+ .replace(/'/g, ''');
+ }
+
+ function money(value) {
+ var number = Number(value) || 0;
+ return Math.round(number).toLocaleString('ru-RU').replace(/,/g, ' ');
+ }
+
+ function toast(message, type) {
+ var stack = document.querySelector('[data-toasts]');
+ if (!stack) { return; }
+ var node = document.createElement('div');
+ node.className = 'toast' + (type ? ' ' + type : '');
+ node.textContent = message;
+ stack.appendChild(node);
+ setTimeout(function () {
+ node.remove();
+ }, 3500);
+ }
+
+ /* ---------- cart ---------- */
+
+ function cartItems() {
+ return readJson(CART_KEY, []);
+ }
+
+ function cartWrite(items) {
+ localStorage.setItem(CART_KEY, JSON.stringify(items));
+ updateBadge();
+ document.dispatchEvent(new CustomEvent('cart:change', { detail: items }));
+ }
+
+ function updateBadge() {
+ var count = cartItems().reduce(function (sum, item) {
+ return sum + (Number(item.qty) || 0);
+ }, 0);
+ document.querySelectorAll('[data-cart-count]').forEach(function (node) {
+ node.textContent = count;
+ node.hidden = count === 0;
+ });
+ }
+
+ var Cart = {
+ items: cartItems,
+ count: function () {
+ return cartItems().reduce(function (sum, item) {
+ return sum + (Number(item.qty) || 0);
+ }, 0);
+ },
+ subtotal: function () {
+ return cartItems().reduce(function (sum, item) {
+ return sum + Number(item.price) * Number(item.qty || 0);
+ }, 0);
+ },
+ add: function (product, qty) {
+ var items = cartItems();
+ var id = Number(product.id);
+ var stock = Number(product.stock) || 999;
+ var existing = items.find(function (item) { return Number(item.id) === id; });
+ if (existing) {
+ existing.qty = Math.min(stock, Number(existing.qty || 0) + (qty || 1));
+ } else {
+ items.push({
+ id: id,
+ slug: product.slug || '',
+ name: product.name || '',
+ price: Number(product.price) || 0,
+ image: product.image || '',
+ stock: stock,
+ qty: Math.min(stock, qty || 1)
+ });
+ }
+ cartWrite(items);
+ return items;
+ },
+ setQty: function (id, qty) {
+ var items = cartItems().map(function (item) {
+ if (Number(item.id) === Number(id)) {
+ item.qty = Math.max(1, Math.min(Number(item.stock) || 999, Number(qty) || 1));
+ }
+ return item;
+ });
+ cartWrite(items);
+ return items;
+ },
+ remove: function (id) {
+ var items = cartItems().filter(function (item) {
+ return Number(item.id) !== Number(id);
+ });
+ cartWrite(items);
+ return items;
+ },
+ clear: function () {
+ cartWrite([]);
+ }
+ };
+
+ /* ---------- auth ---------- */
+
+ var Auth = {
+ token: function () {
+ return localStorage.getItem(ACCESS_KEY) || '';
+ },
+ isLoggedIn: function () {
+ return Boolean(Auth.token());
+ },
+ setTokens: function (access, refresh) {
+ if (access) { localStorage.setItem(ACCESS_KEY, access); }
+ if (refresh) { localStorage.setItem(REFRESH_KEY, refresh); }
+ },
+ logout: function () {
+ localStorage.removeItem(ACCESS_KEY);
+ localStorage.removeItem(REFRESH_KEY);
+ }
+ };
+
+ /* ---------- api client ---------- */
+
+ function refreshToken() {
+ var refresh = localStorage.getItem(REFRESH_KEY);
+ if (!refresh) { return Promise.resolve(false); }
+ return fetch('/api/v1/auth/token/refresh/', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ refresh: refresh })
+ }).then(function (response) {
+ if (!response.ok) {
+ Auth.logout();
+ return false;
+ }
+ return response.json().then(function (data) {
+ Auth.setTokens(data.access, data.refresh);
+ return true;
+ });
+ }).catch(function () {
+ return false;
+ });
+ }
+
+ function api(path, options) {
+ options = options || {};
+ var headers = { 'Content-Type': 'application/json' };
+ var token = Auth.token();
+ if (token && options.auth !== false) {
+ headers.Authorization = 'Bearer ' + token;
+ }
+ var request = {
+ method: options.method || 'GET',
+ headers: headers
+ };
+ if (options.body !== undefined) {
+ request.body = JSON.stringify(options.body);
+ }
+ if (options.headers) {
+ Object.keys(options.headers).forEach(function (key) {
+ headers[key] = options.headers[key];
+ });
+ }
+
+ return fetch('/api/v1' + path, request).then(function (response) {
+ if (response.status === 401 && options.auth !== false && localStorage.getItem(REFRESH_KEY)) {
+ return refreshToken().then(function (refreshed) {
+ if (refreshed) { return api(path, options); }
+ var error = new Error('Требуется вход');
+ error.status = 401;
+ throw error;
+ });
+ }
+ return response.json().catch(function () { return {}; }).then(function (data) {
+ if (!response.ok) {
+ var message = 'Ошибка запроса';
+ if (data && data.error) {
+ message = data.error.message || JSON.stringify(data.error.details || '');
+ } else if (data && data.detail) {
+ message = data.detail;
+ }
+ var error = new Error(message);
+ error.status = response.status;
+ error.data = data;
+ throw error;
+ }
+ return data;
+ });
+ });
+ }
+
+ /* ---------- global wiring ---------- */
+
+ document.addEventListener('click', function (event) {
+ var button = event.target.closest('[data-add-to-cart]');
+ if (!button) { return; }
+ event.preventDefault();
+
+ var qtyNode = button.dataset.qtySource
+ ? document.querySelector(button.dataset.qtySource)
+ : null;
+ var qty = qtyNode ? Math.max(1, parseInt(qtyNode.value, 10) || 1) : 1;
+
+ if (Number(button.dataset.stock) <= 0) {
+ toast('Товара нет в наличии', 'error');
+ return;
+ }
+
+ Cart.add({
+ id: button.dataset.id,
+ slug: button.dataset.slug,
+ name: button.dataset.name,
+ price: button.dataset.price,
+ image: button.dataset.image,
+ stock: button.dataset.stock
+ }, qty);
+ toast('Добавлено в корзину', 'ok');
+ });
+
+ document.addEventListener('DOMContentLoaded', function () {
+ updateBadge();
+
+ document.querySelectorAll('[data-account-link]').forEach(function (link) {
+ link.href = Auth.isLoggedIn() ? '/account/' : '/login/';
+ });
+ });
+
+ window.HOMM = {
+ Cart: Cart,
+ Auth: Auth,
+ api: api,
+ toast: toast,
+ money: money,
+ escapeHtml: escapeHtml,
+ updateBadge: updateBadge
+ };
+})();
diff --git a/backend/apps/storefront/templatetags/__init__.py b/backend/apps/storefront/templatetags/__init__.py
new file mode 100644
index 0000000..8c1d42c
--- /dev/null
+++ b/backend/apps/storefront/templatetags/__init__.py
@@ -0,0 +1 @@
+"""Template filters and tags for the storefront."""
diff --git a/backend/apps/storefront/templatetags/storefront.py b/backend/apps/storefront/templatetags/storefront.py
new file mode 100644
index 0000000..40cf99d
--- /dev/null
+++ b/backend/apps/storefront/templatetags/storefront.py
@@ -0,0 +1,44 @@
+from decimal import Decimal, InvalidOperation
+
+from django import template
+
+register = template.Library()
+
+
+@register.filter
+def money(value) -> str:
+ """Formats a price as a Russian rouble amount without kopecks.
+
+ ``Decimal("12990.00")`` -> ``"12 990"``.
+ """
+ try:
+ amount = Decimal(str(value))
+ except (InvalidOperation, TypeError, ValueError):
+ return "—"
+ rounded = int(amount.quantize(Decimal("1")))
+ return f"{rounded:,}".replace(",", " ")
+
+
+@register.filter
+def discount_percent(price, old_price) -> int:
+ """Returns the discount percentage, or 0 when there is none."""
+ try:
+ current = Decimal(str(price))
+ previous = Decimal(str(old_price))
+ except (InvalidOperation, TypeError, ValueError):
+ return 0
+ if previous <= 0 or previous <= current:
+ return 0
+ return int(round((previous - current) / previous * 100))
+
+
+@register.filter
+def attr_value(value) -> str:
+ """Renders a characteristic value: lists become comma-separated text."""
+ if isinstance(value, (list, tuple)):
+ return ", ".join(str(item) for item in value)
+ if isinstance(value, bool):
+ return "да" if value else "нет"
+ if isinstance(value, dict):
+ return "; ".join(f"{key}: {val}" for key, val in value.items())
+ return str(value)
diff --git a/backend/apps/storefront/tests.py b/backend/apps/storefront/tests.py
new file mode 100644
index 0000000..508aced
--- /dev/null
+++ b/backend/apps/storefront/tests.py
@@ -0,0 +1,138 @@
+from decimal import Decimal
+
+from django.test import TestCase
+
+from apps.catalog.models import Category, Product
+from apps.content.models import StaticPage
+
+from .templatetags.storefront import attr_value, discount_percent, money
+
+
+class StorefrontHelperTests(TestCase):
+ def test_money_formats_roubles_with_spaces(self):
+ self.assertEqual(money(Decimal("12990.00")), "12 990")
+ self.assertEqual(money("490"), "490")
+ self.assertEqual(money(None), "—")
+
+ def test_discount_percent(self):
+ self.assertEqual(discount_percent("12990", "14990"), 13)
+ self.assertEqual(discount_percent("12990", None), 0)
+ self.assertEqual(discount_percent("12990", "10000"), 0)
+
+ def test_attr_value_renders_lists(self):
+ self.assertEqual(attr_value(["S", "M"]), "S, M")
+ self.assertEqual(attr_value(True), "да")
+ self.assertEqual(attr_value("Чёрный"), "Чёрный")
+
+
+class StorefrontPagesTests(TestCase):
+ @classmethod
+ def setUpTestData(cls):
+ cls.outer = Category.objects.create(
+ external_id="t-outer", name="Верхняя одежда", slug="verhnyaya-odezhda"
+ )
+ cls.knit = Category.objects.create(
+ external_id="t-knit", name="Трикотаж", slug="trikotazh"
+ )
+ cls.coat = Product.objects.create(
+ external_id="t-coat",
+ sku="T-1",
+ name="Куртка тестовая",
+ slug="kurtka-testovaya",
+ category=cls.outer,
+ price=Decimal("12000.00"),
+ old_price=Decimal("15000.00"),
+ stock=5,
+ is_hit=True,
+ attributes={"Цвет": "Чёрный"},
+ )
+ cls.tshirt = Product.objects.create(
+ external_id="t-tshirt",
+ sku="T-2",
+ name="Футболка тестовая",
+ slug="futbolka-testovaya",
+ category=cls.knit,
+ brand="HOMM",
+ price=Decimal("2500.00"),
+ stock=0,
+ is_new=True,
+ )
+ cls.page = StaticPage.objects.create(
+ slug="dostavka", title="Доставка", content="Курьером", is_published=True
+ )
+
+ def test_home_shows_hits_and_new(self):
+ response = self.client.get("/")
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, "Куртка тестовая")
+ self.assertContains(response, "Футболка тестовая")
+
+ def test_catalog_lists_only_active_products(self):
+ hidden = Product.objects.create(
+ external_id="t-hidden",
+ sku="T-3",
+ name="Скрытый товар",
+ slug="skrytyy-tovar",
+ price=Decimal("100.00"),
+ is_active=False,
+ )
+ response = self.client.get("/catalog/")
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, "Куртка тестовая")
+ self.assertNotContains(response, hidden.name)
+
+ def test_catalog_filters_by_category(self):
+ response = self.client.get("/catalog/?category=trikotazh")
+ self.assertContains(response, "Футболка тестовая")
+ self.assertNotContains(response, "Куртка тестовая")
+
+ def test_catalog_filters_by_price_and_stock(self):
+ response = self.client.get("/catalog/?price_max=5000&in_stock=1")
+ self.assertNotContains(response, "Куртка тестовая")
+ self.assertNotContains(response, "Футболка тестовая")
+
+ response = self.client.get("/catalog/?price_min=10000")
+ self.assertContains(response, "Куртка тестовая")
+
+ def test_catalog_search(self):
+ response = self.client.get("/catalog/", {"search": "куртка"})
+ self.assertContains(response, "Куртка тестовая")
+ self.assertNotContains(response, "Футболка тестовая")
+
+ def test_catalog_shows_filter_chips(self):
+ response = self.client.get("/catalog/?brand=HOMM&in_stock=1")
+ self.assertContains(response, "Бренд: HOMM")
+ self.assertContains(response, "Только в наличии")
+
+ def test_catalog_ordering(self):
+ response = self.client.get("/catalog/?ordering=price")
+ content = response.content.decode()
+ self.assertLess(content.index("Футболка тестовая"), content.index("Куртка тестовая"))
+
+ def test_product_page(self):
+ response = self.client.get("/catalog/kurtka-testovaya/")
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, "Куртка тестовая")
+ self.assertContains(response, "Цвет")
+ self.assertContains(response, "Чёрный")
+
+ def test_product_page_404(self):
+ self.assertEqual(self.client.get("/catalog/no-such-product/").status_code, 404)
+
+ def test_cart_checkout_login_account_pages(self):
+ for url in ("/cart/", "/checkout/", "/login/", "/account/"):
+ with self.subTest(url=url):
+ self.assertEqual(self.client.get(url).status_code, 200)
+
+ def test_static_page(self):
+ response = self.client.get("/pages/dostavka/")
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, "Курьером")
+
+ def test_static_page_404(self):
+ self.assertEqual(self.client.get("/pages/no-such-page/").status_code, 404)
+
+ def test_api_still_works(self):
+ response = self.client.get("/api/v1/catalog/products/")
+ self.assertEqual(response.status_code, 200)
+ self.assertGreaterEqual(response.json()["count"], 2)
diff --git a/backend/apps/storefront/urls.py b/backend/apps/storefront/urls.py
new file mode 100644
index 0000000..050b4b3
--- /dev/null
+++ b/backend/apps/storefront/urls.py
@@ -0,0 +1,14 @@
+from django.urls import path
+
+from . import views
+
+urlpatterns = [
+ path("", views.home, name="home"),
+ path("catalog/", views.catalog, name="catalog"),
+ path("catalog//", views.product_detail, name="product"),
+ path("cart/", views.cart, name="cart"),
+ path("checkout/", views.checkout, name="checkout"),
+ path("login/", views.login_view, name="login"),
+ path("account/", views.account, name="account"),
+ path("pages//", views.static_page, name="page"),
+]
diff --git a/backend/apps/storefront/views.py b/backend/apps/storefront/views.py
new file mode 100644
index 0000000..5ea9db6
--- /dev/null
+++ b/backend/apps/storefront/views.py
@@ -0,0 +1,246 @@
+"""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})
diff --git a/backend/config/settings/base.py b/backend/config/settings/base.py
index cb58e37..635f8fb 100644
--- a/backend/config/settings/base.py
+++ b/backend/config/settings/base.py
@@ -59,6 +59,7 @@ INSTALLED_APPS = [
"apps.loyalty",
"apps.integration",
"apps.content",
+ "apps.storefront",
]
MIDDLEWARE = [
diff --git a/backend/config/urls.py b/backend/config/urls.py
index 9a14b5d..06f64e1 100644
--- a/backend/config/urls.py
+++ b/backend/config/urls.py
@@ -40,6 +40,8 @@ urlpatterns = [
SpectacularRedocView.as_view(url_name="schema"),
name="redoc",
),
+ # Customer-facing storefront. Keep it last: it owns the site root.
+ path("", include("apps.storefront.urls")),
]
if settings.DEBUG:
diff --git a/backend/templates/storefront/_product_card.html b/backend/templates/storefront/_product_card.html
new file mode 100644
index 0000000..f86bfda
--- /dev/null
+++ b/backend/templates/storefront/_product_card.html
@@ -0,0 +1,40 @@
+{% load storefront %}
+
+
+
+ {% if product.is_hit %}Хит{% endif %}
+ {% if product.is_new %}Новинка{% endif %}
+
+ {% if product.main_image %}
+
+ {% else %}
+ {{ product.name|slice:":1" }}
+ {% endif %}
+
+
+ {% if product.brand %}
{{ product.brand }}{% endif %}
+
+
+ {{ product.price|money }} ₽
+ {% if product.old_price %}
+ {{ product.old_price|money }} ₽
+ {% endif %}
+
+
+
+ {% if product.stock > 0 %}
+
+ {% else %}
+
+ {% endif %}
+
+
diff --git a/backend/templates/storefront/account.html b/backend/templates/storefront/account.html
new file mode 100644
index 0000000..8b27852
--- /dev/null
+++ b/backend/templates/storefront/account.html
@@ -0,0 +1,110 @@
+{% extends "storefront/base.html" %}
+{% load static %}
+
+{% block title %}Личный кабинет — {{ site.site_name }}{% endblock %}
+
+{% block content %}
+
+
+
Личный кабинет
+
Загрузка…
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Адреса доставки
+
+
+
Добавить адрес
+
+
+
+
+
Бонусы
+
+
Доступно бонусов
+
0 ₽
+
+
+
+
+
+{% endblock %}
+
+{% block scripts %}
+
+{% endblock %}
diff --git a/backend/templates/storefront/base.html b/backend/templates/storefront/base.html
new file mode 100644
index 0000000..61fc47d
--- /dev/null
+++ b/backend/templates/storefront/base.html
@@ -0,0 +1,86 @@
+{% load static storefront %}
+
+
+
+
+ {% block title %}{{ site.site_name }}{% endblock %}
+
+ {% block meta %}{% endblock %}
+
+
+
+
+
+
+
+
+ {% block content %}{% endblock %}
+
+
+
+
+
+
+
+{% block scripts %}{% endblock %}
+
+
diff --git a/backend/templates/storefront/cart.html b/backend/templates/storefront/cart.html
new file mode 100644
index 0000000..cf1338e
--- /dev/null
+++ b/backend/templates/storefront/cart.html
@@ -0,0 +1,34 @@
+{% extends "storefront/base.html" %}
+{% load static storefront %}
+
+{% block title %}Корзина — {{ site.site_name }}{% endblock %}
+
+{% block content %}
+
+
Корзина
+
+
+
+
+
+
+
Корзина пуста
+
Добавьте товары из каталога — они сохранятся в этом браузере.
+
Перейти в каталог
+
+
+
+
+
+{% endblock %}
+
+{% block scripts %}
+
+{% endblock %}
diff --git a/backend/templates/storefront/catalog.html b/backend/templates/storefront/catalog.html
new file mode 100644
index 0000000..3c1e463
--- /dev/null
+++ b/backend/templates/storefront/catalog.html
@@ -0,0 +1,136 @@
+{% extends "storefront/base.html" %}
+{% load storefront %}
+
+{% block title %}{% if selected_category %}{{ selected_category.name }}{% else %}Каталог{% endif %} — {{ site.site_name }}{% endblock %}
+
+{% block content %}
+
+
Главная /
+ {% if selected_category %}
+
Каталог /
{{ selected_category.name }}
+ {% else %}
+
Каталог
+ {% endif %}
+
+
+
+
{% if selected_category %}{{ selected_category.name }}{% elif filters.search %}Поиск: {{ filters.search }}{% else %}Каталог{% endif %}
+ {% if selected_category.description %}
{{ selected_category.description }}
{% endif %}
+
+
+
+
+
+
+
+ {% if total %}Найдено товаров: {{ total }}{% else %}Ничего не найдено{% endif %}
+
+
+
+ {% if chips %}
+
+ {% for chip in chips %}
+
+ {{ chip.label }}{% if chip.value %}: {{ chip.value }}{% endif %}
+ ×
+
+ {% endfor %}
+
+ {% endif %}
+
+ {% if products %}
+
+ {% for product in products %}
+ {% include "storefront/_product_card.html" %}
+ {% endfor %}
+
+
+ {% if page.paginator.num_pages > 1 %}
+
+ {% endif %}
+ {% else %}
+
+
Товары не найдены
+
Попробуйте изменить фильтры или сбросить их.
+
Сбросить фильтры
+
+ {% endif %}
+
+
+{% endblock %}
diff --git a/backend/templates/storefront/checkout.html b/backend/templates/storefront/checkout.html
new file mode 100644
index 0000000..70aa181
--- /dev/null
+++ b/backend/templates/storefront/checkout.html
@@ -0,0 +1,115 @@
+{% extends "storefront/base.html" %}
+{% load static storefront %}
+
+{% block title %}Оформление заказа — {{ site.site_name }}{% endblock %}
+
+{% block content %}
+
+
Оформление заказа
+
+
+
+
+
+
+
+
+
+
+{% endblock %}
+
+{% block scripts %}
+
+{% endblock %}
diff --git a/backend/templates/storefront/home.html b/backend/templates/storefront/home.html
new file mode 100644
index 0000000..009acc7
--- /dev/null
+++ b/backend/templates/storefront/home.html
@@ -0,0 +1,79 @@
+{% extends "storefront/base.html" %}
+{% load storefront %}
+
+{% block title %}{{ site.site_name }} — одежда и аксессуары{% endblock %}
+
+{% block content %}
+ {% if banners %}
+
+ {% with banner=banners.0 %}
+ {% if banner.image_url %}

{% endif %}
+
{{ banner.title }}
+
{{ site.site_name }}: одежда, обувь и аксессуары. Ассортимент и наличие синхронизированы с 1С.
+ {% if banner.link_url %}
+
Смотреть
+ {% else %}
+
Смотреть каталог
+ {% endif %}
+ {% endwith %}
+
+ {% else %}
+
+
{{ site.site_name }} — вещи, которые носят годами
+
Одежда, обувь и аксессуары. Цены и наличие обновляются из 1С в реальном времени.
+
Смотреть каталог
+
+ {% endif %}
+
+ {% if categories %}
+
+ {% endif %}
+
+ {% if hits %}
+
+
+
+ {% for product in hits %}
+ {% include "storefront/_product_card.html" %}
+ {% endfor %}
+
+
+ {% endif %}
+
+ {% if new %}
+
+
+
+ {% for product in new %}
+ {% include "storefront/_product_card.html" %}
+ {% endfor %}
+
+
+ {% endif %}
+
+ {% if not hits and not new %}
+
+
Каталог пока пуст
+
Товары появятся после первой синхронизации с 1С.
+
+ {% endif %}
+{% endblock %}
diff --git a/backend/templates/storefront/login.html b/backend/templates/storefront/login.html
new file mode 100644
index 0000000..a033a81
--- /dev/null
+++ b/backend/templates/storefront/login.html
@@ -0,0 +1,60 @@
+{% extends "storefront/base.html" %}
+{% load static %}
+
+{% block title %}Вход — {{ site.site_name }}{% endblock %}
+
+{% block content %}
+
+
+
Вход в личный кабинет
+
Войдите по номеру телефона — код придёт в SMS. Пароль нужен, только если вы его задавали.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Нет аккаунта? Он создастся автоматически при первом входе по коду.
+
+
+
+{% endblock %}
+
+{% block scripts %}
+
+{% endblock %}
diff --git a/backend/templates/storefront/page.html b/backend/templates/storefront/page.html
new file mode 100644
index 0000000..ee39911
--- /dev/null
+++ b/backend/templates/storefront/page.html
@@ -0,0 +1,12 @@
+{% extends "storefront/base.html" %}
+
+{% block title %}{{ page.seo_title|default:page.title }} — {{ site.site_name }}{% endblock %}
+{% block description %}{{ page.seo_description|default:page.title }}{% endblock %}
+
+{% block content %}
+
+ {{ page.title }}
+ {{ page.content|linebreaks }}
+{% endblock %}
diff --git a/backend/templates/storefront/product.html b/backend/templates/storefront/product.html
new file mode 100644
index 0000000..bbec0a9
--- /dev/null
+++ b/backend/templates/storefront/product.html
@@ -0,0 +1,151 @@
+{% extends "storefront/base.html" %}
+{% load storefront %}
+
+{% block title %}{{ product.name }} — {{ site.site_name }}{% endblock %}
+{% block description %}{{ product.short_description|default:product.name|truncatechars:160 }}{% endblock %}
+
+{% block content %}
+
+
+
+
+
+ {% if images %}
+

+ {% else %}
+
{{ product.name|slice:":1" }}
+ {% endif %}
+
+ {% if images|length > 1 %}
+
+ {% for image in images %}
+
+ {% endfor %}
+
+ {% endif %}
+
+
+
+ {% if product.brand %}
{{ product.brand }}{% endif %}
+
{{ product.name }}
+
Артикул: {{ product.sku }}
+
+
+ {{ product.price|money }} ₽
+ {% if product.old_price %}
+ {{ product.old_price|money }} ₽
+ −{{ product.price|discount_percent:product.old_price }}%
+ {% endif %}
+
+
+ {% if product.stock > 0 %}
+
В наличии: {{ product.stock }} шт.
+ {% elif product.stock_status == 'preorder' %}
+
Под заказ
+ {% else %}
+
Нет в наличии
+ {% endif %}
+
+ {% if product.short_description %}
+
{{ product.short_description }}
+ {% endif %}
+
+ {% if product.stock > 0 %}
+
+
+
+
+
+
+
+
+
Перейти в корзину
+ {% else %}
+
+ {% endif %}
+
+ {% if product.description %}
+
{{ product.description|linebreaks }}
+ {% endif %}
+
+
+
+ {% if attributes %}
+
+ Характеристики
+
+ {% for name, value in attributes.items %}
+ | {{ name }} | {{ value|attr_value }} |
+ {% endfor %}
+
+
+ {% endif %}
+
+ {% if related %}
+
+
+
Похожие товары
+ {% if product.category %}
+
Вся категория
+ {% endif %}
+
+
+ {% for item in related %}
+ {% include "storefront/_product_card.html" with product=item %}
+ {% endfor %}
+
+
+ {% endif %}
+{% endblock %}
+
+{% block scripts %}
+
+{% endblock %}
diff --git a/docs/architecture.md b/docs/architecture.md
index e302530..b03306f 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -54,7 +54,7 @@ HOMM — интернет-магазин, где **1С является маст
```mermaid
flowchart LR
subgraph Client
- B[Браузер / Nuxt 3]
+ B[Браузер / витрина HOMM]
end
subgraph Edge
@@ -108,14 +108,37 @@ flowchart LR
| `apps.loyalty` | Бонусный счёт, операции, промокоды, сертификаты |
| `apps.integration` | Обмен с 1С: сеансы, журналы, outbox, клиент 1С, задачи Celery |
| `apps.content` | Статические страницы, баннеры, настройки сайта |
+| `apps.storefront` | Витрина для покупателей: страницы на Django-шаблонах, корзина и кабинет на JS |
-### 3.2 Frontend (план)
+### 3.2 Frontend
+
+**Витрина реализована на Django-шаблонах** (`apps.storefront`): страницы рендерятся на сервере,
+интерактив — на ванильном JS без сборки и без фреймворков. Такой вариант выбран потому, что
+работает без npm/CDN и сразу отдаёт SEO-корректный HTML.
+
+| Адрес | Страница | Как работает |
+|-------|----------|--------------|
+| `/` | Главная | Баннеры, категории, «Хиты», «Новинки» — из БД |
+| `/catalog/` | Каталог | Фильтры категория/бренд/цена/наличие, поиск, сортировка, пагинация (по 12) |
+| `/catalog//` | Карточка товара | Галерея, характеристики, наличие, количество, похожие товары |
+| `/cart/` | Корзина | localStorage, пересчёт сумм на клиенте |
+| `/checkout/` | Оформление | Контакты, доставка, промокод, бонусы → `POST /api/v1/orders/` с `Idempotency-Key` |
+| `/login/` | Вход | OTP по телефону (в dev показывает отладочный код) или телефон+пароль |
+| `/account/` | Кабинет | Профиль, заказы, адреса, бонусы — через API с JWT |
+| `/pages//` | Статические страницы | Контент из админки |
+
+Особенности:
+
+- **Корзина** — только в браузере (`localStorage`), на сервер уходит при оформлении. Это
+ упрощает анонимную покупку и снимает необходимость серверной корзины на MVP.
+- **Авторизация** — JWT в `localStorage`; клиент сам обновляет access-токен по refresh при `401`.
+- **CSS/JS** лежат в `apps/storefront/static/storefront/` — никакой сборки, файлы отдаёт Django.
+- **Демо-данные** для просмотра витрины до подключения 1С:
+ `python manage.py seed_demo` (и `seed_demo --reset`, чтобы убрать их).
+
+Nuxt 3 (Vue + SSR) остаётся вариантом для фазы 2 — если понадобится более богатый интерактив.
+API уже готов к отдельному SPA: контракты в `/api/schema/`, авторизация по JWT.
-- **Nuxt 3** (Vue 3 + SSR) — витрина, каталог, карточка, корзина, checkout, ЛК.
-- **Pinia** — состояние корзины, избранного, пользователя.
-- **Axios** — клиент к `/api/v1/`.
-- Корзина хранится на клиенте (localStorage/Pinia) и передаётся в `POST /api/v1/orders/`; это упрощает анонимный checkout и снимает необходимость в серверной корзине на MVP.
-- SEO: SSR, meta-теги, sitemap, robots, JSON-LD (фаза 2).
---