Add the customer storefront on Django templates
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.
This commit is contained in:
1 parent
b18e3ea703
commit
37d5d7b366
29 files changed
+2822
-7
No files matched your search
@@ -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.
|
||||
"""
|
||||
@@ -0,0 +1,7 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class StorefrontConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "apps.storefront"
|
||||
verbose_name = "Витрина"
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -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."
|
||||
)
|
||||
)
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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 =
|
||||
'<div class="empty-state"><h3>Заказов пока нет</h3>' +
|
||||
'<p>Оформите первый заказ — он появится здесь.</p>' +
|
||||
'<a class="btn btn-accent" href="/catalog/">В каталог</a></div>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = orders.map(function (order) {
|
||||
var items = (order.items || []).map(function (item) {
|
||||
return '<div>' + HOMM.escapeHtml(item.name) + ' × ' + Number(item.quantity) +
|
||||
' — ' + HOMM.money(item.total) + ' ₽</div>';
|
||||
}).join('');
|
||||
return '<div class="order-card">' +
|
||||
'<div class="order-head">' +
|
||||
'<span class="order-number">Заказ ' + HOMM.escapeHtml(order.number) + '</span>' +
|
||||
'<span class="badge">' + HOMM.escapeHtml(STATUS_LABELS[order.status] || order.status) + '</span>' +
|
||||
'</div>' +
|
||||
'<div class="order-items">' + items + '</div>' +
|
||||
'<div class="summary-row" style="margin-top:10px">' +
|
||||
'<span class="form-note">' + HOMM.escapeHtml(PAYMENT_LABELS[order.payment_status] || '') +
|
||||
' · ' + new Date(order.created_at).toLocaleDateString('ru-RU') + '</span>' +
|
||||
'<strong>' + HOMM.money(order.total) + ' ₽</strong>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}).join('');
|
||||
}).catch(function (error) {
|
||||
container.innerHTML = '<p class="form-error">Ошибка загрузки заказов: ' +
|
||||
HOMM.escapeHtml(error.message) + '</p>';
|
||||
});
|
||||
}
|
||||
|
||||
function loadAddresses() {
|
||||
var container = document.querySelector('[data-addresses-list]');
|
||||
return HOMM.api('/auth/addresses/').then(function (addresses) {
|
||||
if (!addresses.length) {
|
||||
container.innerHTML = '<p class="form-note">Адресов пока нет.</p>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = addresses.map(function (address) {
|
||||
var parts = [address.city, address.street, address.house,
|
||||
address.apartment ? 'кв. ' + address.apartment : ''].filter(Boolean);
|
||||
return '<div class="order-card">' +
|
||||
'<div class="order-head">' +
|
||||
'<span class="order-number">' + HOMM.escapeHtml(address.title || 'Адрес') +
|
||||
(address.is_default ? ' <span class="badge badge-new">основной</span>' : '') + '</span>' +
|
||||
'<button class="btn btn-ghost btn-sm" type="button" data-remove-address="' +
|
||||
Number(address.id) + '">Удалить</button>' +
|
||||
'</div>' +
|
||||
'<div class="order-items">' + HOMM.escapeHtml(parts.join(', ')) + '</div>' +
|
||||
'</div>';
|
||||
}).join('');
|
||||
}).catch(function (error) {
|
||||
container.innerHTML = '<p class="form-error">Не удалось загрузить адреса: ' +
|
||||
HOMM.escapeHtml(error.message) + '</p>';
|
||||
});
|
||||
}
|
||||
|
||||
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 = '<p class="form-note">Операций пока не было.</p>';
|
||||
return;
|
||||
}
|
||||
historyNode.innerHTML = '<table class="specs">' + transactions.map(function (item) {
|
||||
var sign = Number(item.amount) > 0 ? '+' : '';
|
||||
return '<tr><td>' + new Date(item.created_at).toLocaleDateString('ru-RU') +
|
||||
'<br><span class="form-note">' +
|
||||
HOMM.escapeHtml(REASON_LABELS[item.reason] || item.reason) +
|
||||
(item.comment ? ' · ' + HOMM.escapeHtml(item.comment) : '') + '</span></td>' +
|
||||
'<td style="text-align:right">' + sign + HOMM.money(item.amount) + ' ₽</td></tr>';
|
||||
}).join('') + '</table>';
|
||||
}).catch(function (error) {
|
||||
historyNode.innerHTML = '<p class="form-error">Не удалось загрузить бонусы: ' +
|
||||
HOMM.escapeHtml(error.message) + '</p>';
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- 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');
|
||||
})();
|
||||
@@ -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
|
||||
? '<img src="' + HOMM.escapeHtml(item.image) + '" alt="">'
|
||||
: '<span>' + HOMM.escapeHtml((item.name || '?').slice(0, 1)) + '</span>';
|
||||
|
||||
return '' +
|
||||
'<div class="cart-row" data-id="' + HOMM.escapeHtml(item.id) + '">' +
|
||||
'<a class="cart-thumb" href="/catalog/' + encodeURIComponent(item.slug) + '/">' + image + '</a>' +
|
||||
'<div>' +
|
||||
'<h4><a href="/catalog/' + encodeURIComponent(item.slug) + '/">' + HOMM.escapeHtml(item.name) + '</a></h4>' +
|
||||
'<div class="muted">' + HOMM.money(item.price) + ' ₽ за шт.</div>' +
|
||||
'</div>' +
|
||||
'<div class="row-actions">' +
|
||||
'<div class="qty">' +
|
||||
'<button type="button" data-dec aria-label="Меньше">−</button>' +
|
||||
'<input type="number" value="' + Number(item.qty) + '" min="1" max="' + Number(item.stock || 999) + '" data-qty aria-label="Количество">' +
|
||||
'<button type="button" data-inc aria-label="Больше">+</button>' +
|
||||
'</div>' +
|
||||
'<strong data-line>' + HOMM.money(Number(item.price) * Number(item.qty)) + ' ₽</strong>' +
|
||||
'<button type="button" class="btn btn-ghost" data-remove aria-label="Удалить">Удалить</button>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}
|
||||
|
||||
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();
|
||||
})();
|
||||
@@ -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 '<div class="summary-row"><span>' + HOMM.escapeHtml(item.name) +
|
||||
' × ' + Number(item.qty) + '</span><span>' +
|
||||
HOMM.money(Number(item.price) * Number(item.qty)) + ' ₽</span></div>';
|
||||
}).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();
|
||||
})();
|
||||
@@ -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, 'Неверный номер телефона или пароль');
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -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, '"')
|
||||
.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
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1 @@
|
||||
"""Template filters and tags for the storefront."""
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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/<slug:slug>/", 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/<slug:slug>/", views.static_page, name="page"),
|
||||
]
|
||||
@@ -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})
|
||||
@@ -59,6 +59,7 @@ INSTALLED_APPS = [
|
||||
"apps.loyalty",
|
||||
"apps.integration",
|
||||
"apps.content",
|
||||
"apps.storefront",
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
{% load storefront %}
|
||||
<article class="product-card">
|
||||
<a href="{% url 'product' product.slug %}" class="product-media" aria-label="{{ product.name }}">
|
||||
<div class="product-badges">
|
||||
{% if product.is_hit %}<span class="badge badge-hit">Хит</span>{% endif %}
|
||||
{% if product.is_new %}<span class="badge badge-new">Новинка</span>{% endif %}
|
||||
</div>
|
||||
{% if product.main_image %}
|
||||
<img src="{{ product.main_image }}" alt="{{ product.name }}" loading="lazy">
|
||||
{% else %}
|
||||
<span class="placeholder">{{ product.name|slice:":1" }}</span>
|
||||
{% endif %}
|
||||
</a>
|
||||
<div class="product-body">
|
||||
{% if product.brand %}<span class="product-brand">{{ product.brand }}</span>{% endif %}
|
||||
<h3 class="product-name"><a href="{% url 'product' product.slug %}">{{ product.name }}</a></h3>
|
||||
<div class="product-price">
|
||||
<span class="price-now">{{ product.price|money }} ₽</span>
|
||||
{% if product.old_price %}
|
||||
<span class="price-old">{{ product.old_price|money }} ₽</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="product-actions">
|
||||
{% if product.stock > 0 %}
|
||||
<button class="btn btn-outline btn-block btn-sm"
|
||||
data-add-to-cart
|
||||
data-id="{{ product.id }}"
|
||||
data-slug="{{ product.slug }}"
|
||||
data-name="{{ product.name }}"
|
||||
data-price="{{ product.price }}"
|
||||
data-image="{{ product.main_image|default:'' }}"
|
||||
data-stock="{{ product.stock }}">
|
||||
В корзину
|
||||
</button>
|
||||
{% else %}
|
||||
<button class="btn btn-outline btn-block btn-sm" disabled>Нет в наличии</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
</article>
|
||||
@@ -0,0 +1,110 @@
|
||||
{% extends "storefront/base.html" %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}Личный кабинет — {{ site.site_name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-head" style="display:flex;justify-content:space-between;align-items:center;gap:16px;flex-wrap:wrap">
|
||||
<div>
|
||||
<h1>Личный кабинет</h1>
|
||||
<p data-account-hello>Загрузка…</p>
|
||||
</div>
|
||||
<button class="btn btn-outline" type="button" data-logout>Выйти</button>
|
||||
</div>
|
||||
|
||||
<div class="account-layout">
|
||||
<nav class="account-nav">
|
||||
<button type="button" class="active" data-panel="orders">Мои заказы</button>
|
||||
<button type="button" data-panel="profile">Профиль</button>
|
||||
<button type="button" data-panel="addresses">Адреса доставки</button>
|
||||
<button type="button" data-panel="bonus">Бонусы</button>
|
||||
</nav>
|
||||
|
||||
<section>
|
||||
<div class="account-panel" data-panel-body="orders">
|
||||
<div class="panel-head"><h2>Мои заказы</h2></div>
|
||||
<div data-orders-list><p class="form-note">Загрузка…</p></div>
|
||||
</div>
|
||||
|
||||
<div class="account-panel" data-panel-body="profile" hidden>
|
||||
<div class="panel-head"><h2>Профиль</h2></div>
|
||||
<form data-profile-form>
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="first_name">Имя</label>
|
||||
<input id="first_name" name="first_name" autocomplete="given-name">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="last_name">Фамилия</label>
|
||||
<input id="last_name" name="last_name" autocomplete="family-name">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="middle_name">Отчество</label>
|
||||
<input id="middle_name" name="middle_name">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="profile_phone">Телефон</label>
|
||||
<input id="profile_phone" disabled>
|
||||
<div class="form-note">Телефон изменить нельзя — это логин для входа.</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="profile_email">Email</label>
|
||||
<input id="profile_email" name="email" type="email" autocomplete="email">
|
||||
</div>
|
||||
<button class="btn btn-accent" type="submit">Сохранить</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="account-panel" data-panel-body="addresses" hidden>
|
||||
<div class="panel-head"><h2>Адреса доставки</h2></div>
|
||||
<div data-addresses-list><p class="form-note">Загрузка…</p></div>
|
||||
|
||||
<h3 style="margin-top:24px;font-size:17px">Добавить адрес</h3>
|
||||
<form data-address-form>
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="city">Город *</label>
|
||||
<input id="city" name="city" required>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="street">Улица *</label>
|
||||
<input id="street" name="street" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="house">Дом</label>
|
||||
<input id="house" name="house">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="apartment">Квартира</label>
|
||||
<input id="apartment" name="apartment">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="title">Название (например, «Дом»)</label>
|
||||
<input id="title" name="title">
|
||||
</div>
|
||||
<label class="form-note" style="display:block;margin-bottom:14px">
|
||||
<input type="checkbox" name="is_default"> Сделать основным
|
||||
</label>
|
||||
<button class="btn btn-accent" type="submit">Добавить адрес</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="account-panel" data-panel-body="bonus" hidden>
|
||||
<div class="panel-head"><h2>Бонусы</h2></div>
|
||||
<div class="balance-card">
|
||||
<div class="form-note">Доступно бонусов</div>
|
||||
<div class="value" data-bonus-amount>0 ₽</div>
|
||||
</div>
|
||||
<div data-bonus-history><p class="form-note">Загрузка…</p></div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{% static 'storefront/js/account-page.js' %}" defer></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,86 @@
|
||||
{% load static storefront %}<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{% block title %}{{ site.site_name }}{% endblock %}</title>
|
||||
<meta name="description" content="{% block description %}{{ site.site_name }} — одежда и аксессуары{% endblock %}">
|
||||
{% block meta %}{% endblock %}
|
||||
<link rel="stylesheet" href="{% static 'storefront/css/storefront.css' %}">
|
||||
<meta name="csrf-token" content="{{ csrf_token }}">
|
||||
</head>
|
||||
<body>
|
||||
<header class="site-header">
|
||||
<div class="container">
|
||||
<div class="header-top">
|
||||
<a class="logo" href="{% url 'home' %}">HOMM<span>.</span></a>
|
||||
<nav class="header-nav">
|
||||
<a href="{% url 'catalog' %}">Каталог</a>
|
||||
{% for category in menu_categories|slice:":5" %}
|
||||
<a href="{% url 'catalog' %}?category={{ category.slug }}">{{ category.name }}</a>
|
||||
{% endfor %}
|
||||
</nav>
|
||||
<div class="header-actions">
|
||||
<a href="{% url 'account' %}" data-account-link>Кабинет</a>
|
||||
<a href="{% url 'cart' %}">Корзина
|
||||
<span class="cart-badge" data-cart-count hidden>0</span>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-search">
|
||||
<form action="{% url 'catalog' %}" method="get" role="search">
|
||||
<input type="search" name="search" placeholder="Поиск по каталогу: название, артикул, бренд"
|
||||
value="{{ filters.search|default:'' }}" aria-label="Поиск по каталогу">
|
||||
<button class="btn" type="submit">Найти</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<div class="container">
|
||||
{% block content %}{% endblock %}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="site-footer">
|
||||
<div class="container">
|
||||
<div class="footer-grid">
|
||||
<div>
|
||||
<h4>{{ site.site_name }}</h4>
|
||||
{% if site.address %}<p>{{ site.address }}</p>{% endif %}
|
||||
{% if site.phone %}<p><a href="tel:{{ site.phone }}">{{ site.phone }}</a></p>{% endif %}
|
||||
{% if site.email %}<p><a href="mailto:{{ site.email }}">{{ site.email }}</a></p>{% endif %}
|
||||
{% if site.working_hours %}<p>{{ site.working_hours }}</p>{% endif %}
|
||||
</div>
|
||||
<div>
|
||||
<h4>Покупателям</h4>
|
||||
<a href="{% url 'catalog' %}">Каталог</a>
|
||||
<a href="{% url 'cart' %}">Корзина</a>
|
||||
<a href="{% url 'account' %}">Личный кабинет</a>
|
||||
{% for page in footer_pages %}
|
||||
<a href="{% url 'page' page.slug %}">{{ page.title }}</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div>
|
||||
<h4>Связь</h4>
|
||||
{% if site.telegram_url %}<a href="{{ site.telegram_url }}" rel="noopener">Telegram</a>{% endif %}
|
||||
{% if site.vk_url %}<a href="{{ site.vk_url }}" rel="noopener">ВКонтакте</a>{% endif %}
|
||||
{% if site.whatsapp_url %}<a href="{{ site.whatsapp_url }}" rel="noopener">WhatsApp</a>{% endif %}
|
||||
{% if site.free_delivery_threshold %}
|
||||
<p>Бесплатная доставка от {{ site.free_delivery_threshold|money }} ₽</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer-bottom">
|
||||
<span>© {% now "Y" %} {{ site.site_name }}</span>
|
||||
<span>Цены и наличие обновляются из 1С</span>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<div class="toast-stack" data-toasts></div>
|
||||
<script src="{% static 'storefront/js/site.js' %}" defer></script>
|
||||
{% block scripts %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,34 @@
|
||||
{% extends "storefront/base.html" %}
|
||||
{% load static storefront %}
|
||||
|
||||
{% block title %}Корзина — {{ site.site_name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-head">
|
||||
<h1>Корзина</h1>
|
||||
</div>
|
||||
|
||||
<div class="cart-layout" data-cart-root>
|
||||
<div>
|
||||
<div class="cart-list" data-cart-list></div>
|
||||
<div class="empty-state" data-cart-empty hidden>
|
||||
<h2>Корзина пуста</h2>
|
||||
<p>Добавьте товары из каталога — они сохранятся в этом браузере.</p>
|
||||
<a class="btn btn-accent" href="{% url 'catalog' %}">Перейти в каталог</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<aside class="summary">
|
||||
<h3>Итого</h3>
|
||||
<div class="summary-row"><span>Товары</span><span data-subtotal>0 ₽</span></div>
|
||||
<div class="summary-row"><span>Доставка</span><span data-delivery>рассчитаем при оформлении</span></div>
|
||||
<div class="summary-row total"><span>К оплате</span><span data-total>0 ₽</span></div>
|
||||
<a class="btn btn-accent btn-block" href="{% url 'checkout' %}" data-checkout-link>Оформить заказ</a>
|
||||
<button class="btn btn-ghost btn-block" type="button" data-clear-cart>Очистить корзину</button>
|
||||
</aside>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{% static 'storefront/js/cart-page.js' %}" defer></script>
|
||||
{% endblock %}
|
||||
@@ -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 %}
|
||||
<div class="breadcrumbs">
|
||||
<a href="{% url 'home' %}">Главная</a> /
|
||||
{% if selected_category %}
|
||||
<a href="{% url 'catalog' %}">Каталог</a> / <span>{{ selected_category.name }}</span>
|
||||
{% else %}
|
||||
<span>Каталог</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="page-head">
|
||||
<h1>{% if selected_category %}{{ selected_category.name }}{% elif filters.search %}Поиск: {{ filters.search }}{% else %}Каталог{% endif %}</h1>
|
||||
{% if selected_category.description %}<p>{{ selected_category.description }}</p>{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="catalog-layout">
|
||||
<aside class="filters">
|
||||
<form method="get" action="{% url 'catalog' %}">
|
||||
<div class="filter-group">
|
||||
<h4>Категория</h4>
|
||||
<select name="category">
|
||||
<option value="">Все категории</option>
|
||||
{% for category in categories %}
|
||||
<option value="{{ category.slug }}"
|
||||
{% if filters.category == category.slug %}selected{% endif %}>{{ category.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="filter-group">
|
||||
<h4>Цена, ₽</h4>
|
||||
<div class="filter-price">
|
||||
<input type="number" name="price_min" min="0" inputmode="numeric"
|
||||
placeholder="{{ price_bounds.low|money|default:'0' }}"
|
||||
value="{{ filters.price_min|default:'' }}">
|
||||
<input type="number" name="price_max" min="0" inputmode="numeric"
|
||||
placeholder="{{ price_bounds.high|money|default:'—' }}"
|
||||
value="{{ filters.price_max|default:'' }}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if brands %}
|
||||
<div class="filter-group">
|
||||
<h4>Бренд</h4>
|
||||
<select name="brand">
|
||||
<option value="">Любой бренд</option>
|
||||
{% for brand in brands %}
|
||||
<option value="{{ brand }}" {% if filters.brand == brand %}selected{% endif %}>{{ brand }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="filter-group">
|
||||
<label class="form-note">
|
||||
<input type="checkbox" name="in_stock" value="1"
|
||||
{% if filters.in_stock == '1' %}checked{% endif %}>
|
||||
Только в наличии
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{% if filters.search %}<input type="hidden" name="search" value="{{ filters.search }}">{% endif %}
|
||||
<input type="hidden" name="ordering" value="{{ selected_ordering }}">
|
||||
|
||||
<div class="filter-actions">
|
||||
<button class="btn btn-block" type="submit">Применить</button>
|
||||
<a class="btn btn-outline btn-block" href="{% url 'catalog' %}">Сбросить</a>
|
||||
</div>
|
||||
</form>
|
||||
</aside>
|
||||
|
||||
<div>
|
||||
<div class="catalog-toolbar">
|
||||
<span class="count">{% if total %}Найдено товаров: {{ total }}{% else %}Ничего не найдено{% endif %}</span>
|
||||
<form method="get" action="{% url 'catalog' %}">
|
||||
{% for key, value in filters.items %}
|
||||
{% if key != 'ordering' %}<input type="hidden" name="{{ key }}" value="{{ value }}">{% endif %}
|
||||
{% endfor %}
|
||||
<select name="ordering" onchange="this.form.submit()" aria-label="Сортировка">
|
||||
{% for value, label in ordering_choices %}
|
||||
<option value="{{ value }}" {% if selected_ordering == value %}selected{% endif %}>{{ label }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{% if chips %}
|
||||
<div class="chips">
|
||||
{% for chip in chips %}
|
||||
<span class="chip">
|
||||
{{ chip.label }}{% if chip.value %}: {{ chip.value }}{% endif %}
|
||||
<a href="{% url 'catalog' %}{% if chip.qs %}?{{ chip.qs }}{% endif %}" aria-label="Убрать фильтр">×</a>
|
||||
</span>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if products %}
|
||||
<div class="product-grid">
|
||||
{% for product in products %}
|
||||
{% include "storefront/_product_card.html" %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
{% if page.paginator.num_pages > 1 %}
|
||||
<nav class="pagination" aria-label="Страницы">
|
||||
{% if page.has_previous %}
|
||||
<a href="?{{ querystring }}&page={{ page.previous_page_number }}">←</a>
|
||||
{% endif %}
|
||||
{% for number in page.paginator.page_range %}
|
||||
{% if number == page.number %}
|
||||
<span class="current">{{ number }}</span>
|
||||
{% elif number > page.number|add:"-3" and number < page.number|add:"3" %}
|
||||
<a href="?{{ querystring }}&page={{ number }}">{{ number }}</a>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% if page.has_next %}
|
||||
<a href="?{{ querystring }}&page={{ page.next_page_number }}">→</a>
|
||||
{% endif %}
|
||||
</nav>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<div class="empty-state">
|
||||
<h2>Товары не найдены</h2>
|
||||
<p>Попробуйте изменить фильтры или сбросить их.</p>
|
||||
<a class="btn btn-outline" href="{% url 'catalog' %}">Сбросить фильтры</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,115 @@
|
||||
{% extends "storefront/base.html" %}
|
||||
{% load static storefront %}
|
||||
|
||||
{% block title %}Оформление заказа — {{ site.site_name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-head">
|
||||
<h1>Оформление заказа</h1>
|
||||
</div>
|
||||
|
||||
<div class="cart-layout" data-checkout
|
||||
data-free-threshold="{{ site.free_delivery_threshold|default:'0' }}"
|
||||
data-delivery-cost="{{ site.default_delivery_cost|default:'0' }}"
|
||||
data-bonus-limit="{{ site.bonus_max_payment_percent|default:'0' }}">
|
||||
|
||||
<div>
|
||||
<form data-checkout-form novalidate>
|
||||
<div class="account-panel" style="margin-bottom:20px">
|
||||
<h2 style="font-size:20px">Контакты</h2>
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="customer_name">Имя и фамилия *</label>
|
||||
<input id="customer_name" name="customer_name" required autocomplete="name">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="phone">Телефон *</label>
|
||||
<input id="phone" name="phone" required autocomplete="tel" placeholder="+7 900 123-45-67">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="email">Email</label>
|
||||
<input id="email" name="email" type="email" autocomplete="email" placeholder="для чека и уведомлений">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="account-panel" style="margin-bottom:20px">
|
||||
<h2 style="font-size:20px">Доставка</h2>
|
||||
<div class="field">
|
||||
<label for="delivery_method">Способ получения</label>
|
||||
<select id="delivery_method" name="delivery_method">
|
||||
<option value="courier">Курьером</option>
|
||||
<option value="pickup">Самовывоз</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field" data-address-field>
|
||||
<label for="delivery_address">Адрес</label>
|
||||
<textarea id="delivery_address" name="delivery_address"
|
||||
placeholder="Город, улица, дом, квартира"></textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="comment">Комментарий к заказу</label>
|
||||
<textarea id="comment" name="comment" placeholder="Например: позвонить за час"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="account-panel" style="margin-bottom:20px">
|
||||
<h2 style="font-size:20px">Оплата</h2>
|
||||
<div class="field">
|
||||
<label for="payment_method">Способ оплаты</label>
|
||||
<select id="payment_method" name="payment_method">
|
||||
<option value="card">Картой онлайн</option>
|
||||
<option value="sbp">СБП</option>
|
||||
<option value="cash">При получении</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="account-panel">
|
||||
<h2 style="font-size:20px">Скидки</h2>
|
||||
<div class="field">
|
||||
<label for="promo_code">Промокод</label>
|
||||
<div class="field-row">
|
||||
<input id="promo_code" name="promo_code" placeholder="Например, WINTER15">
|
||||
<button class="btn btn-outline" type="button" data-apply-promo>Применить</button>
|
||||
</div>
|
||||
<div class="form-note" data-promo-note></div>
|
||||
</div>
|
||||
<div class="field" data-bonus-field hidden>
|
||||
<label for="bonus_amount">Списать бонусы (доступно: <span data-bonus-balance>0</span>)</label>
|
||||
<input id="bonus_amount" name="bonus_amount" type="number" min="0" step="1" value="0">
|
||||
<div class="form-note">Бонусами можно оплатить не более {{ site.bonus_max_payment_percent|floatformat:0 }}% заказа.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-error" data-checkout-error hidden></div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<aside class="summary">
|
||||
<h3>Ваш заказ</h3>
|
||||
<div data-checkout-items></div>
|
||||
<div class="summary-row"><span>Товары</span><span data-subtotal>0 ₽</span></div>
|
||||
<div class="summary-row"><span>Скидка по промокоду</span><span data-discount>0 ₽</span></div>
|
||||
<div class="summary-row"><span>Бонусы</span><span data-bonus>0 ₽</span></div>
|
||||
<div class="summary-row"><span>Доставка</span><span data-delivery>0 ₽</span></div>
|
||||
<div class="summary-row total"><span>К оплате</span><span data-total>0 ₽</span></div>
|
||||
<button class="btn btn-accent btn-block" type="button" data-submit-order>Подтвердить заказ</button>
|
||||
<p class="form-note" style="margin-top:10px">
|
||||
Нажимая кнопку, вы соглашаетесь с условиями обработки персональных данных.
|
||||
</p>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<div class="account-panel" data-order-success hidden style="margin-top:24px">
|
||||
<h2>Заказ оформлен</h2>
|
||||
<p>Номер заказа: <strong data-order-number></strong></p>
|
||||
<p class="form-note">Мы свяжемся с вами для подтверждения. Статус заказа виден в личном кабинете.</p>
|
||||
<a class="btn btn-accent" href="{% url 'account' %}">Перейти в кабинет</a>
|
||||
<a class="btn btn-outline" href="{% url 'catalog' %}">Вернуться в каталог</a>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{% static 'storefront/js/checkout-page.js' %}" defer></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,79 @@
|
||||
{% extends "storefront/base.html" %}
|
||||
{% load storefront %}
|
||||
|
||||
{% block title %}{{ site.site_name }} — одежда и аксессуары{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% if banners %}
|
||||
<div class="hero">
|
||||
{% with banner=banners.0 %}
|
||||
{% if banner.image_url %}<img class="hero-image" src="{{ banner.image_url }}" alt="">{% endif %}
|
||||
<h1>{{ banner.title }}</h1>
|
||||
<p>{{ site.site_name }}: одежда, обувь и аксессуары. Ассортимент и наличие синхронизированы с 1С.</p>
|
||||
{% if banner.link_url %}
|
||||
<a class="btn btn-accent" href="{{ banner.link_url }}">Смотреть</a>
|
||||
{% else %}
|
||||
<a class="btn btn-accent" href="{% url 'catalog' %}">Смотреть каталог</a>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="hero">
|
||||
<h1>{{ site.site_name }} — вещи, которые носят годами</h1>
|
||||
<p>Одежда, обувь и аксессуары. Цены и наличие обновляются из 1С в реальном времени.</p>
|
||||
<a class="btn btn-accent" href="{% url 'catalog' %}">Смотреть каталог</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if categories %}
|
||||
<section class="section">
|
||||
<div class="section-head">
|
||||
<h2>Категории</h2>
|
||||
<a href="{% url 'catalog' %}">Весь каталог</a>
|
||||
</div>
|
||||
<div class="category-grid">
|
||||
{% for category in categories %}
|
||||
<a class="category-tile" href="{% url 'catalog' %}?category={{ category.slug }}">
|
||||
{% if category.image_url %}<img src="{{ category.image_url }}" alt="">{% endif %}
|
||||
<span>{{ category.name }}</span>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% if hits %}
|
||||
<section class="section">
|
||||
<div class="section-head">
|
||||
<h2>Хиты продаж</h2>
|
||||
<a href="{% url 'catalog' %}?ordering=-is_hit">Все хиты</a>
|
||||
</div>
|
||||
<div class="product-grid">
|
||||
{% for product in hits %}
|
||||
{% include "storefront/_product_card.html" %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% if new %}
|
||||
<section class="section">
|
||||
<div class="section-head">
|
||||
<h2>Новинки</h2>
|
||||
<a href="{% url 'catalog' %}?ordering=-created_at">Все новинки</a>
|
||||
</div>
|
||||
<div class="product-grid">
|
||||
{% for product in new %}
|
||||
{% include "storefront/_product_card.html" %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% if not hits and not new %}
|
||||
<div class="empty-state">
|
||||
<h2>Каталог пока пуст</h2>
|
||||
<p>Товары появятся после первой синхронизации с 1С.</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,60 @@
|
||||
{% extends "storefront/base.html" %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}Вход — {{ site.site_name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div style="max-width:460px;margin:0 auto">
|
||||
<div class="page-head">
|
||||
<h1>Вход в личный кабинет</h1>
|
||||
<p>Войдите по номеру телефона — код придёт в SMS. Пароль нужен, только если вы его задавали.</p>
|
||||
</div>
|
||||
|
||||
<div class="account-panel">
|
||||
<div class="account-nav" style="flex-direction:row;gap:8px;margin-bottom:20px">
|
||||
<button type="button" class="active" data-tab="otp">Код из SMS</button>
|
||||
<button type="button" data-tab="password">Телефон и пароль</button>
|
||||
</div>
|
||||
|
||||
<form data-otp-form>
|
||||
<div class="field">
|
||||
<label for="otp_phone">Номер телефона</label>
|
||||
<input id="otp_phone" name="phone" required autocomplete="tel" placeholder="+7 900 123-45-67">
|
||||
</div>
|
||||
<button class="btn btn-accent btn-block" type="button" data-request-code>Получить код</button>
|
||||
|
||||
<div data-code-block hidden>
|
||||
<div class="field" style="margin-top:16px">
|
||||
<label for="otp_code">Код из SMS</label>
|
||||
<input id="otp_code" name="code" inputmode="numeric" autocomplete="one-time-code"
|
||||
placeholder="4 цифры" maxlength="8">
|
||||
</div>
|
||||
<button class="btn btn-accent btn-block" type="submit">Войти</button>
|
||||
<div class="form-note" data-code-note></div>
|
||||
</div>
|
||||
<div class="form-error" data-otp-error hidden></div>
|
||||
</form>
|
||||
|
||||
<form data-password-form hidden>
|
||||
<div class="field">
|
||||
<label for="login_phone">Номер телефона</label>
|
||||
<input id="login_phone" name="phone" required autocomplete="username">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="login_password">Пароль</label>
|
||||
<input id="login_password" name="password" type="password" required autocomplete="current-password">
|
||||
</div>
|
||||
<button class="btn btn-accent btn-block" type="submit">Войти</button>
|
||||
<div class="form-error" data-password-error hidden></div>
|
||||
</form>
|
||||
|
||||
<p class="form-note" style="margin-top:18px">
|
||||
Нет аккаунта? Он создастся автоматически при первом входе по коду.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{% static 'storefront/js/login-page.js' %}" defer></script>
|
||||
{% endblock %}
|
||||
@@ -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 %}
|
||||
<div class="breadcrumbs">
|
||||
<a href="{% url 'home' %}">Главная</a> / <span>{{ page.title }}</span>
|
||||
</div>
|
||||
<h1>{{ page.title }}</h1>
|
||||
<div class="product-desc" style="max-width:820px">{{ page.content|linebreaks }}</div>
|
||||
{% endblock %}
|
||||
@@ -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 %}
|
||||
<div class="breadcrumbs">
|
||||
<a href="{% url 'home' %}">Главная</a> /
|
||||
<a href="{% url 'catalog' %}">Каталог</a> /
|
||||
{% if product.category %}
|
||||
<a href="{% url 'catalog' %}?category={{ product.category.slug }}">{{ product.category.name }}</a> /
|
||||
{% endif %}
|
||||
<span>{{ product.name }}</span>
|
||||
</div>
|
||||
|
||||
<div class="product-layout">
|
||||
<div>
|
||||
<div class="gallery-main" data-gallery-main>
|
||||
{% if images %}
|
||||
<img src="{{ images.0.url }}" alt="{{ product.name }}" data-main-image>
|
||||
{% else %}
|
||||
<span class="placeholder">{{ product.name|slice:":1" }}</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if images|length > 1 %}
|
||||
<div class="gallery-thumbs">
|
||||
{% for image in images %}
|
||||
<button type="button" data-thumb="{{ image.url }}"
|
||||
class="{% if forloop.first %}active{% endif %}"
|
||||
aria-label="Фото {{ forloop.counter }}">
|
||||
<img src="{{ image.url }}" alt="{{ image.alt|default:product.name }}" loading="lazy">
|
||||
</button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="product-info">
|
||||
{% if product.brand %}<span class="product-brand">{{ product.brand }}</span>{% endif %}
|
||||
<h1>{{ product.name }}</h1>
|
||||
<div class="product-sku">Артикул: {{ product.sku }}</div>
|
||||
|
||||
<div class="product-price-lg">
|
||||
<span class="price-now">{{ product.price|money }} ₽</span>
|
||||
{% if product.old_price %}
|
||||
<span class="price-old">{{ product.old_price|money }} ₽</span>
|
||||
<span class="badge badge-new">−{{ product.price|discount_percent:product.old_price }}%</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if product.stock > 0 %}
|
||||
<div class="stock"><span class="dot"></span> В наличии: {{ product.stock }} шт.</div>
|
||||
{% elif product.stock_status == 'preorder' %}
|
||||
<div class="stock out"><span class="dot"></span> Под заказ</div>
|
||||
{% else %}
|
||||
<div class="stock out"><span class="dot"></span> Нет в наличии</div>
|
||||
{% endif %}
|
||||
|
||||
{% if product.short_description %}
|
||||
<p class="product-desc">{{ product.short_description }}</p>
|
||||
{% endif %}
|
||||
|
||||
{% if product.stock > 0 %}
|
||||
<div class="buy-row">
|
||||
<div class="qty">
|
||||
<button type="button" data-qty-minus aria-label="Меньше">−</button>
|
||||
<input type="number" value="1" min="1" max="{{ product.stock }}"
|
||||
data-qty-input aria-label="Количество">
|
||||
<button type="button" data-qty-plus aria-label="Больше">+</button>
|
||||
</div>
|
||||
<button class="btn btn-accent btn-block"
|
||||
data-add-to-cart
|
||||
data-id="{{ product.id }}"
|
||||
data-slug="{{ product.slug }}"
|
||||
data-name="{{ product.name }}"
|
||||
data-price="{{ product.price }}"
|
||||
data-image="{{ product.main_image|default:'' }}"
|
||||
data-stock="{{ product.stock }}"
|
||||
data-qty-source="[data-qty-input]">
|
||||
Добавить в корзину
|
||||
</button>
|
||||
</div>
|
||||
<a class="btn btn-outline btn-block" href="{% url 'cart' %}">Перейти в корзину</a>
|
||||
{% else %}
|
||||
<button class="btn btn-outline btn-block" disabled>Нет в наличии</button>
|
||||
{% endif %}
|
||||
|
||||
{% if product.description %}
|
||||
<div class="product-desc">{{ product.description|linebreaks }}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if attributes %}
|
||||
<section class="section" style="margin-top:48px">
|
||||
<h2>Характеристики</h2>
|
||||
<table class="specs">
|
||||
{% for name, value in attributes.items %}
|
||||
<tr><td>{{ name }}</td><td>{{ value|attr_value }}</td></tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% if related %}
|
||||
<section class="section">
|
||||
<div class="section-head">
|
||||
<h2>Похожие товары</h2>
|
||||
{% if product.category %}
|
||||
<a href="{% url 'catalog' %}?category={{ product.category.slug }}">Вся категория</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="product-grid">
|
||||
{% for item in related %}
|
||||
{% include "storefront/_product_card.html" with product=item %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script>
|
||||
document.querySelectorAll('[data-thumb]').forEach(function (button) {
|
||||
button.addEventListener('click', function () {
|
||||
var main = document.querySelector('[data-main-image]');
|
||||
if (!main) { return; }
|
||||
main.src = button.dataset.thumb;
|
||||
document.querySelectorAll('[data-thumb]').forEach(function (other) {
|
||||
other.classList.toggle('active', other === button);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
(function () {
|
||||
var input = document.querySelector('[data-qty-input]');
|
||||
if (!input) { return; }
|
||||
var minus = document.querySelector('[data-qty-minus]');
|
||||
var plus = document.querySelector('[data-qty-plus]');
|
||||
var max = parseInt(input.max || '999', 10);
|
||||
|
||||
function clamp(value) {
|
||||
return Math.max(1, Math.min(max, value || 1));
|
||||
}
|
||||
minus.addEventListener('click', function () { input.value = clamp(parseInt(input.value, 10) - 1); });
|
||||
plus.addEventListener('click', function () { input.value = clamp(parseInt(input.value, 10) + 1); });
|
||||
input.addEventListener('change', function () { input.value = clamp(parseInt(input.value, 10)); });
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
+30
-7
@@ -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/<slug>/` | Карточка товара | Галерея, характеристики, наличие, количество, похожие товары |
|
||||
| `/cart/` | Корзина | localStorage, пересчёт сумм на клиенте |
|
||||
| `/checkout/` | Оформление | Контакты, доставка, промокод, бонусы → `POST /api/v1/orders/` с `Idempotency-Key` |
|
||||
| `/login/` | Вход | OTP по телефону (в dev показывает отладочный код) или телефон+пароль |
|
||||
| `/account/` | Кабинет | Профиль, заказы, адреса, бонусы — через API с JWT |
|
||||
| `/pages/<slug>/` | Статические страницы | Контент из админки |
|
||||
|
||||
Особенности:
|
||||
|
||||
- **Корзина** — только в браузере (`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).
|
||||
|
||||
---
|
||||
|
||||
|
||||
Reference in new issue
Block a user