Compare commits
15 Commits
dedef454c8
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 980b31df06 | |||
| e81bd79607 | |||
| 7cb61d4242 | |||
| db6ab9a701 | |||
| c5e8653b30 | |||
| 9025677fd8 | |||
| f9f0446c12 | |||
| 4c37f4ac1a | |||
| d4166ec62a | |||
| af2901152d | |||
| 69dfd2a93a | |||
| d4dd1fb587 | |||
| 0c2cee410f | |||
| 9b688b2af4 | |||
| db4bc9bfe1 |
+7
-3
@@ -1,5 +1,6 @@
|
|||||||
# Скопируйте: cp .env.docker.example .env
|
# Docker: лучше запустить интерактивный установщик:
|
||||||
# Используется docker compose (переменные подставляются в compose)
|
# bash scripts/install.sh
|
||||||
|
# Или вручную: cp .env.docker.example .env
|
||||||
|
|
||||||
POSTGRES_USER=shop
|
POSTGRES_USER=shop
|
||||||
POSTGRES_PASSWORD=shop
|
POSTGRES_PASSWORD=shop
|
||||||
@@ -9,4 +10,7 @@ APP_PORT=3000
|
|||||||
SESSION_SECRET=change-me-to-a-long-random-string
|
SESSION_SECRET=change-me-to-a-long-random-string
|
||||||
TRUST_PROXY=0
|
TRUST_PROXY=0
|
||||||
|
|
||||||
# С профилем proxy (Caddy): TRUST_PROXY=1
|
ADMIN_EMAIL=admin@site.com
|
||||||
|
ADMIN_PASSWORD=admin
|
||||||
|
ADMIN_NAME=Администратор
|
||||||
|
SITE_URL=http://localhost:3000
|
||||||
|
|||||||
@@ -13,6 +13,14 @@ ADMIN_NAME=Администратор
|
|||||||
# URL сайта (ссылки в письмах, WebAuthn origin)
|
# URL сайта (ссылки в письмах, WebAuthn origin)
|
||||||
SITE_URL=http://localhost:3000
|
SITE_URL=http://localhost:3000
|
||||||
|
|
||||||
|
# Капча: google (reCAPTCHA) или cloudflare (Turnstile). yandex — заблокирован
|
||||||
|
CAPTCHA_PROVIDER=google
|
||||||
|
# CAPTCHA_ENABLED=0
|
||||||
|
RECAPTCHA_SITE_KEY=
|
||||||
|
RECAPTCHA_SECRET_KEY=
|
||||||
|
# TURNSTILE_SITE_KEY=
|
||||||
|
# TURNSTILE_SECRET_KEY=
|
||||||
|
|
||||||
# Passkey (WebAuthn) — по умолчанию hostname из SITE_URL
|
# Passkey (WebAuthn) — по умолчанию hostname из SITE_URL
|
||||||
# WEBAUTHN_RP_ID=shop.example.com
|
# WEBAUTHN_RP_ID=shop.example.com
|
||||||
# WEBAUTHN_RP_NAME=Shop
|
# WEBAUTHN_RP_NAME=Shop
|
||||||
@@ -26,6 +34,13 @@ SMTP_USER=
|
|||||||
SMTP_PASS=
|
SMTP_PASS=
|
||||||
SMTP_FROM=shop@example.com
|
SMTP_FROM=shop@example.com
|
||||||
|
|
||||||
|
# Обновление из админки (/admin/system)
|
||||||
|
# SHOP_ROOT=/opt/shop/shop10
|
||||||
|
# ADMIN_UPDATE_ENABLED=1
|
||||||
|
# ADMIN_UPDATE_USE_SUDO=1
|
||||||
|
# SHOP_GIT_USER=root
|
||||||
|
# SHOP_SERVICE_USER=www-data
|
||||||
|
|
||||||
# PostgreSQL 17 (одна строка или отдельные переменные)
|
# PostgreSQL 17 (одна строка или отдельные переменные)
|
||||||
DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop
|
DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop
|
||||||
# PGHOST=127.0.0.1
|
# PGHOST=127.0.0.1
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
## 1.0.0
|
||||||
|
|
||||||
|
Стабильный релиз **1.0** — всё новое после **v0.20.0**.
|
||||||
|
|
||||||
|
### Магазин
|
||||||
|
|
||||||
|
- Промокоды (%, фикс. сумма), баллы лояльности, таймер акции в корзине
|
||||||
|
- Акционная цена на товаре: старая цена зачёркнута, новая цена и % скидки
|
||||||
|
- Подписка «сообщить о поступлении» + email при появлении на складе
|
||||||
|
|
||||||
|
### Вход и админ
|
||||||
|
|
||||||
|
- Passkey (WebAuthn) в профиле и на странице входа
|
||||||
|
- Один админ — только `ADMIN_EMAIL` в `.env`
|
||||||
|
- Админка: цены/скидки на товарах, промокоды, **обновление с Git** (`/admin/system`)
|
||||||
|
- Иконки и улучшенное отображение цен
|
||||||
|
|
||||||
|
### Сервер
|
||||||
|
|
||||||
|
- `scripts/install.sh` — интерактивная установка
|
||||||
|
- `SHOP_ROOT`, `server-update.sh`, `git-sync.sh`, systemd-скрипты
|
||||||
|
- Wiki: Server-Operations, Troubleshooting
|
||||||
|
|
||||||
|
### Обновление с 0.20
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export SHOP_ROOT=/opt/shop/shop10 # ваш каталог
|
||||||
|
git fetch origin && git checkout main && git pull
|
||||||
|
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||||
|
```
|
||||||
|
|
||||||
|
Или после настройки sudo: **Админ → Обновление →** ввести `update`.
|
||||||
|
|
||||||
|
### Новые переменные (.env)
|
||||||
|
|
||||||
|
```env
|
||||||
|
SHOP_ROOT=/opt/shop
|
||||||
|
ADMIN_EMAIL=admin@site.com
|
||||||
|
# Обновление из админки (опционально):
|
||||||
|
ADMIN_UPDATE_ENABLED=1
|
||||||
|
ADMIN_UPDATE_USE_SUDO=1
|
||||||
|
```
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
## 1.0.1
|
||||||
|
|
||||||
|
Патч после **v1.0.0**.
|
||||||
|
|
||||||
|
### Новое
|
||||||
|
|
||||||
|
- Капча **Google reCAPTCHA** или **Cloudflare Turnstile** (вход, регистрация, сброс пароля)
|
||||||
|
- **Яндекс SmartCaptcha** заблокирован — японский сервис недоступен по решению администратора
|
||||||
|
|
||||||
|
### Исправления
|
||||||
|
|
||||||
|
- Обновление из админки: `safe.directory`, `git ls-remote`, pull от владельца `.git`
|
||||||
|
|
||||||
|
### Настройка (.env)
|
||||||
|
|
||||||
|
```env
|
||||||
|
CAPTCHA_PROVIDER=google
|
||||||
|
RECAPTCHA_SITE_KEY=...
|
||||||
|
RECAPTCHA_SECRET_KEY=...
|
||||||
|
# или cloudflare: TURNSTILE_SITE_KEY / TURNSTILE_SECRET_KEY
|
||||||
|
```
|
||||||
|
|
||||||
|
### Обновление
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export SHOP_ROOT=/opt/shop/shop10
|
||||||
|
git pull && bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||||
|
```
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# v1.2.0
|
||||||
|
|
||||||
|
**Дата:** 2026-05-16
|
||||||
|
|
||||||
|
## Каталог
|
||||||
|
|
||||||
|
- Сортировка: название, цена, новинки
|
||||||
|
- Фильтр «только со скидкой» и показ товаров без остатка
|
||||||
|
- Бейдж низкого остатка и блок «Вы недавно смотрели»
|
||||||
|
|
||||||
|
## Заказы
|
||||||
|
|
||||||
|
- Email-подтверждение заказа (нужен `SMTP_*` и `SITE_URL`)
|
||||||
|
- Вкладка «Заказы» в `/account`
|
||||||
|
|
||||||
|
## Прочее
|
||||||
|
|
||||||
|
- `robots.txt`, `sitemap.xml`
|
||||||
|
- Защита от перебора на login/register
|
||||||
|
- Админ: фильтр заказов, экспорт CSV
|
||||||
|
|
||||||
|
## Обновление
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /opt/shop/shop10 # или ваш SHOP_ROOT
|
||||||
|
git pull
|
||||||
|
bash scripts/server-update.sh
|
||||||
|
# или: npm install --omit=dev && systemctl restart shop
|
||||||
|
```
|
||||||
|
|
||||||
|
Переменные для писем и sitemap: `SITE_URL`, `SMTP_HOST`, `SMTP_FROM`.
|
||||||
@@ -1,5 +1,89 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## [1.2.0] — 2026-05-16
|
||||||
|
|
||||||
|
Улучшения каталога, уведомлений и админки.
|
||||||
|
|
||||||
|
### Каталог и UX
|
||||||
|
|
||||||
|
- **Сортировка:** по названию, цене (↑/↓), дате добавления
|
||||||
|
- **Фильтры:** только товары со скидкой; показ позиций «нет в наличии»
|
||||||
|
- **Бейдж «Осталось N»** при остатке ≤ 5
|
||||||
|
- **Недавно просмотренные** товары на главной (сессия, до 8 позиций)
|
||||||
|
- **Meta description** на странице товара
|
||||||
|
|
||||||
|
### Заказы и почта
|
||||||
|
|
||||||
|
- **Письмо после оформления** заказа (SMTP или лог в консоль)
|
||||||
|
- Вкладка **«Заказы»** в личном кабинете
|
||||||
|
|
||||||
|
### SEO и безопасность
|
||||||
|
|
||||||
|
- **`/robots.txt`** и **`/sitemap.xml`**
|
||||||
|
- Заголовки **X-Content-Type-Options**, **X-Frame-Options**, **Referrer-Policy**
|
||||||
|
- **Rate limit** на вход и регистрацию (429 при превышении)
|
||||||
|
|
||||||
|
### Админка
|
||||||
|
|
||||||
|
- **Фильтр заказов** по статусу
|
||||||
|
- **Экспорт заказов в CSV**
|
||||||
|
|
||||||
|
[1.2.0]: https://git.evilfox.cc/test/shop10/releases/tag/v1.2.0
|
||||||
|
|
||||||
|
## [1.0.1] — 2026-05-17
|
||||||
|
|
||||||
|
Патч после **v1.0.0**: капча, доработка обновления из админки.
|
||||||
|
|
||||||
|
### Безопасность
|
||||||
|
|
||||||
|
- **Капча:** Google reCAPTCHA или Cloudflare Turnstile на входе, регистрации и сбросе пароля
|
||||||
|
- **Яндекс SmartCaptcha заблокирован** — сообщение администратора на формах; попытки отправки отклоняются
|
||||||
|
|
||||||
|
### Админка и сервер
|
||||||
|
|
||||||
|
- **Обновление с Git** (`/admin/system`): исправлены `safe.directory`, проверка через `git ls-remote` без прав на `.git`, pull от владельца репозитория
|
||||||
|
- Подсказки по `SHOP_GIT_USER`, sudoers в интерфейсе
|
||||||
|
|
||||||
|
[1.0.1]: https://git.evilfox.cc/test/shop10/releases/tag/v1.0.1
|
||||||
|
|
||||||
|
## [1.0.0] — 2026-05-17
|
||||||
|
|
||||||
|
Первый мажорный релиз после **v0.20.0**: безопасность, лояльность, акции на товары, удобная установка и обновление с сервера.
|
||||||
|
|
||||||
|
### Безопасность и вход
|
||||||
|
|
||||||
|
- **Passkey (WebAuthn):** привязка в профиле, вход без пароля
|
||||||
|
- **Один администратор:** только email из `ADMIN_EMAIL`; остальные регистрируются как `customer`
|
||||||
|
- Документация только под **PostgreSQL 17** (SQLite убран из описаний)
|
||||||
|
|
||||||
|
### Магазин и маркетинг
|
||||||
|
|
||||||
|
- **Промокоды:** процент или фиксированная скидка, мин. сумма, лимит использований, таймер до конца акции в корзине
|
||||||
|
- **Баллы лояльности:** списание при оплате, начисление с заказа
|
||||||
|
- **Цена со скидкой на товар:** `sale_price_cents`, дата окончания акции; в каталоге — зачёркнутая старая цена и бейдж
|
||||||
|
- **Уведомление о поступлении:** подписка при нулевом остатке, email при пополнении склада
|
||||||
|
|
||||||
|
### Админ-панель
|
||||||
|
|
||||||
|
- Товары: цена, цена со скидкой, срок акции, остаток
|
||||||
|
- Промокоды: создание и редактирование
|
||||||
|
- **Обновление с Git:** `/admin/system` — `git pull`, `npm install`, перезапуск `shop` (с подтверждением)
|
||||||
|
- Улучшенный UI: SVG-иконки, наглядные цены со скидкой
|
||||||
|
|
||||||
|
### Установка и эксплуатация
|
||||||
|
|
||||||
|
- Интерактивный **`scripts/install.sh`** (Docker или Ubuntu, админ, БД, SMTP)
|
||||||
|
- **`SHOP_ROOT`**, **`git-sync.sh`**, **`server-update.sh`** — обновление без detached HEAD
|
||||||
|
- **`install-shop-service.sh`**, **`wait-postgres.sh`**, освобождение порта 3000
|
||||||
|
- Wiki: [Server-Operations](wiki/Server-Operations.md), универсальное развёртывание
|
||||||
|
|
||||||
|
### Исправления
|
||||||
|
|
||||||
|
- Пути `include` иконок в EJS (Internal Server Error после UI-обновления)
|
||||||
|
- Быстрое развёртывание Ubuntu: PGDG PostgreSQL 17, корректный каталог репозитория
|
||||||
|
|
||||||
|
[1.0.0]: https://git.evilfox.cc/test/shop10/releases/tag/v1.0.0
|
||||||
|
|
||||||
## [0.20.0] — 2026-05-17
|
## [0.20.0] — 2026-05-17
|
||||||
|
|
||||||
### Роли и администрирование
|
### Роли и администрирование
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
# Shop
|
# Shop
|
||||||
|
|
||||||
**v0.20.0** — интернет-магазин на **Node.js** и **PostgreSQL 17**.
|
**v1.2.0** — интернет-магазин на **Node.js** и **PostgreSQL 17**.
|
||||||
|
|
||||||
Два способа установки: [Docker Compose](#docker-compose-рекомендуется-для-теста) | [без Docker (Ubuntu)](#postgresql-17-без-docker)
|
Два способа установки: [Docker Compose](#docker-compose-рекомендуется-для-теста) | [без Docker (Ubuntu)](#postgresql-17-без-docker)
|
||||||
|
|
||||||
Подробности релиза: [CHANGELOG.md](CHANGELOG.md) · [docs/RELEASE-0.20.md](docs/RELEASE-0.20.md)
|
Подробности релиза: [CHANGELOG.md](CHANGELOG.md) · [docs/RELEASE-1.0.1.md](docs/RELEASE-1.0.1.md) · [1.0.0](docs/RELEASE-1.0.md)
|
||||||
|
|
||||||
**Сервер (установка, обновление, ошибки):** [wiki/Server-Operations.md](wiki/Server-Operations.md) · [wiki/Troubleshooting.md](wiki/Troubleshooting.md)
|
**Сервер (установка, обновление, ошибки):** [wiki/Server-Operations.md](wiki/Server-Operations.md) · [wiki/Troubleshooting.md](wiki/Troubleshooting.md)
|
||||||
|
|
||||||
@@ -17,6 +17,7 @@
|
|||||||
- Роли: клиент (`customer`) и **один** администратор (`admin`) — аккаунт из `ADMIN_EMAIL` в `.env`
|
- Роли: клиент (`customer`) и **один** администратор (`admin`) — аккаунт из `ADMIN_EMAIL` в `.env`
|
||||||
- Согласие на cookies
|
- Согласие на cookies
|
||||||
- Подписка «сообщить о поступлении», если товара нет в наличии
|
- Подписка «сообщить о поступлении», если товара нет в наличии
|
||||||
|
- Лояльность (баллы), промокоды со скидкой и таймером до конца акции
|
||||||
|
|
||||||
## Требования
|
## Требования
|
||||||
|
|
||||||
@@ -111,6 +112,19 @@ bash scripts/setup-postgres-ubuntu.sh
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Интерактивный установщик
|
||||||
|
|
||||||
|
Задаёт вопросы: **Docker или Ubuntu**, данные **администратора**, **PostgreSQL**, URL сайта, опционально SMTP.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /path/to/shop
|
||||||
|
bash scripts/install.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Нативная установка на сервере — от root: `sudo bash scripts/install.sh`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Быстрый развёртывание на Ubuntu
|
## Быстрый развёртывание на Ubuntu
|
||||||
|
|
||||||
Подставьте **URL своего репозитория** и каталог клона `SHOP_ROOT` (часто `/opt/shop`):
|
Подставьте **URL своего репозитория** и каталог клона `SHOP_ROOT` (часто `/opt/shop`):
|
||||||
@@ -338,6 +352,7 @@ caddy/Caddyfile.docker.example
|
|||||||
deploy/shop.service
|
deploy/shop.service
|
||||||
scripts/
|
scripts/
|
||||||
setup-postgres-ubuntu.sh
|
setup-postgres-ubuntu.sh
|
||||||
|
install.sh
|
||||||
install-postgresql-ubuntu.sh
|
install-postgresql-ubuntu.sh
|
||||||
quick-deploy-ubuntu.sh
|
quick-deploy-ubuntu.sh
|
||||||
fix-db-connection.sh
|
fix-db-connection.sh
|
||||||
@@ -346,19 +361,22 @@ scripts/
|
|||||||
src/
|
src/
|
||||||
```
|
```
|
||||||
|
|
||||||
## Релиз 0.20.0
|
## Релиз 1.0.1
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone <URL-вашего-репозитория> /opt/shop
|
git clone <URL-вашего-репозитория> /opt/shop
|
||||||
cd /opt/shop
|
cd /opt/shop
|
||||||
git checkout v0.20.0
|
git checkout v1.0.1
|
||||||
```
|
```
|
||||||
|
|
||||||
| Способ | Команда |
|
| Способ | Команда |
|
||||||
|--------|---------|
|
|--------|---------|
|
||||||
|
| Интерактивно | `bash scripts/install.sh` |
|
||||||
| Docker | `docker compose up -d --build` |
|
| Docker | `docker compose up -d --build` |
|
||||||
| Без Docker | `bash scripts/setup-postgres-ubuntu.sh` → `systemctl start shop` |
|
| Без Docker | `bash scripts/setup-postgres-ubuntu.sh` → `systemctl start shop` |
|
||||||
|
|
||||||
|
Обновление с **0.20**: `bash "$SHOP_ROOT/scripts/server-update.sh"` или **Админ → Обновление**.
|
||||||
|
|
||||||
## Репозиторий
|
## Репозиторий
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
+1
-1
@@ -9,7 +9,7 @@ User=www-data
|
|||||||
Group=www-data
|
Group=www-data
|
||||||
WorkingDirectory=/opt/shop
|
WorkingDirectory=/opt/shop
|
||||||
EnvironmentFile=/opt/shop/.env
|
EnvironmentFile=/opt/shop/.env
|
||||||
ExecStartPre=+/opt/shop/scripts/wait-postgres.sh
|
ExecStartPre=+/bin/bash /opt/shop/scripts/wait-postgres.sh
|
||||||
ExecStart=/usr/bin/node src/server.js
|
ExecStart=/usr/bin/node src/server.js
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
RestartSec=5
|
RestartSec=5
|
||||||
|
|||||||
+2
-1
@@ -23,6 +23,8 @@ services:
|
|||||||
build: .
|
build: .
|
||||||
container_name: shop-app
|
container_name: shop-app
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -31,7 +33,6 @@ services:
|
|||||||
HOST: 0.0.0.0
|
HOST: 0.0.0.0
|
||||||
PORT: 3000
|
PORT: 3000
|
||||||
TRUST_PROXY: ${TRUST_PROXY:-0}
|
TRUST_PROXY: ${TRUST_PROXY:-0}
|
||||||
SESSION_SECRET: ${SESSION_SECRET:-change-me-in-docker-compose-env}
|
|
||||||
DATABASE_URL: postgresql://${POSTGRES_USER:-shop}:${POSTGRES_PASSWORD:-shop}@postgres:5432/${POSTGRES_DB:-shop}
|
DATABASE_URL: postgresql://${POSTGRES_USER:-shop}:${POSTGRES_PASSWORD:-shop}@postgres:5432/${POSTGRES_DB:-shop}
|
||||||
ports:
|
ports:
|
||||||
- '${APP_PORT:-3000}:3000'
|
- '${APP_PORT:-3000}:3000'
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Релиз 1.0.1
|
||||||
|
|
||||||
|
Патч после [1.0.0](RELEASE-1.0.md): капча (Google / Cloudflare), блокировка Яндекс SmartCaptcha, исправления Git-обновления в админке.
|
||||||
|
|
||||||
|
## Что нового
|
||||||
|
|
||||||
|
| Изменение | Описание |
|
||||||
|
|-----------|----------|
|
||||||
|
| Капча | Google reCAPTCHA или Cloudflare Turnstile |
|
||||||
|
| Яндекс | SmartCaptcha заблокирован, предупреждение на формах |
|
||||||
|
| `/admin/system` | `safe.directory`, `ls-remote`, pull от владельца репозитория |
|
||||||
|
|
||||||
|
## Обновление с 1.0.0
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export SHOP_ROOT=/opt/shop/shop10
|
||||||
|
cd "$SHOP_ROOT"
|
||||||
|
git fetch origin && git checkout v1.0.1
|
||||||
|
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||||
|
```
|
||||||
|
|
||||||
|
Добавьте в `.env` ключи капчи (см. `.env.example`) и перезапустите `shop`.
|
||||||
|
|
||||||
|
Полный список: [CHANGELOG.md](../CHANGELOG.md)
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Релиз 1.0.0
|
||||||
|
|
||||||
|
Мажорный релиз после **v0.20.0**. Кратко: passkey, лояльность и промокоды, акционные цены, уведомления о поступлении, обновление из админки, установщик `install.sh`.
|
||||||
|
|
||||||
|
## Что нового после 0.20
|
||||||
|
|
||||||
|
| Область | Изменения |
|
||||||
|
|---------|-----------|
|
||||||
|
| Вход | Passkey (WebAuthn), один админ (`ADMIN_EMAIL`) |
|
||||||
|
| Цены | Скидка на товар, промокоды, баллы лояльности |
|
||||||
|
| Склад | Подписка на email при поступлении товара |
|
||||||
|
| Админка | Цены/скидки, промокоды, **/admin/system** — обновление с Git |
|
||||||
|
| UI | Иконки, зачёркнутая старая цена, бейдж «−N%» |
|
||||||
|
| Deploy | `install.sh`, `SHOP_ROOT`, `git-sync`, wiki Server-Operations |
|
||||||
|
|
||||||
|
## Быстрый старт
|
||||||
|
|
||||||
|
### Новая установка
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone <URL-репозитория> /opt/shop
|
||||||
|
cd /opt/shop
|
||||||
|
git checkout v1.0.0
|
||||||
|
bash scripts/install.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
### Обновление с v0.20.0
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export SHOP_ROOT=/opt/shop # или /opt/shop/shop10
|
||||||
|
cd "$SHOP_ROOT"
|
||||||
|
git fetch origin && git checkout main && git pull origin main
|
||||||
|
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Админ: обновление без SSH
|
||||||
|
|
||||||
|
1. В `.env`: `SHOP_ROOT`, `ADMIN_UPDATE_ENABLED=1`
|
||||||
|
2. Sudoers для `www-data` на `scripts/admin-web-update.sh` (см. `/admin/system`)
|
||||||
|
3. Админ → **Обновление** → проверить Git → ввести `update`
|
||||||
|
|
||||||
|
## Тег и Release в Gitea
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git tag -a v1.0.0 -m "Release 1.0.0"
|
||||||
|
git push origin v1.0.0
|
||||||
|
export GITEA_TOKEN=...
|
||||||
|
bash scripts/publish-gitea-release.sh 1.0.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Полный список: [CHANGELOG.md](../CHANGELOG.md)
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "shop",
|
"name": "shop",
|
||||||
"version": "0.20.0",
|
"version": "1.2.0",
|
||||||
"description": "Интернет-магазин на Node.js с PostgreSQL 17",
|
"description": "Интернет-магазин на Node.js с PostgreSQL 17",
|
||||||
"main": "src/server.js",
|
"main": "src/server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
-- Лояльность и промокоды
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS loyalty_points INTEGER NOT NULL DEFAULT 0
|
||||||
|
CHECK (loyalty_points >= 0);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS promo_codes (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
code TEXT NOT NULL UNIQUE,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
discount_type TEXT NOT NULL CHECK (discount_type IN ('percent', 'fixed')),
|
||||||
|
discount_value INTEGER NOT NULL CHECK (discount_value > 0),
|
||||||
|
starts_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
min_order_cents INTEGER NOT NULL DEFAULT 0 CHECK (min_order_cents >= 0),
|
||||||
|
max_uses INTEGER CHECK (max_uses IS NULL OR max_uses > 0),
|
||||||
|
use_count INTEGER NOT NULL DEFAULT 0 CHECK (use_count >= 0),
|
||||||
|
active BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_promo_codes_active ON promo_codes (active, expires_at);
|
||||||
|
|
||||||
|
ALTER TABLE orders ADD COLUMN IF NOT EXISTS subtotal_cents INTEGER;
|
||||||
|
ALTER TABLE orders ADD COLUMN IF NOT EXISTS discount_cents INTEGER NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE orders ADD COLUMN IF NOT EXISTS promo_code_id INTEGER REFERENCES promo_codes(id);
|
||||||
|
ALTER TABLE orders ADD COLUMN IF NOT EXISTS loyalty_points_used INTEGER NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE orders ADD COLUMN IF NOT EXISTS loyalty_points_earned INTEGER NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
UPDATE orders SET subtotal_cents = total_cents WHERE subtotal_cents IS NULL;
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
-- Цена со скидкой на товар (акция)
|
||||||
|
ALTER TABLE products ADD COLUMN IF NOT EXISTS sale_price_cents INTEGER
|
||||||
|
CHECK (sale_price_cents IS NULL OR sale_price_cents >= 0);
|
||||||
|
ALTER TABLE products ADD COLUMN IF NOT EXISTS sale_ends_at TIMESTAMPTZ;
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Обновление кода из админки (git pull + npm + перезапуск shop)
|
||||||
|
# Запуск: bash scripts/admin-web-update.sh
|
||||||
|
# С www-data: ADMIN_UPDATE_USE_SUDO=1 + sudoers NOPASSWD на этот скрипт
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
# shellcheck source=shop-root.sh
|
||||||
|
source "$SCRIPT_DIR/shop-root.sh"
|
||||||
|
|
||||||
|
PORT="${PORT:-3000}"
|
||||||
|
REPO_OWNER="${SHOP_GIT_USER:-$(stat -c '%U' "$SHOP_ROOT/.git" 2>/dev/null || stat -c '%U' "$SHOP_ROOT" 2>/dev/null || echo root)}"
|
||||||
|
SHOP_SERVICE_USER="${SHOP_SERVICE_USER:-www-data}"
|
||||||
|
|
||||||
|
ensure_git_safe() {
|
||||||
|
local user="$1"
|
||||||
|
if [ -z "$user" ]; then return; fi
|
||||||
|
if [ "$(id -u)" -eq 0 ]; then
|
||||||
|
sudo -u "$user" git config --global --add safe.directory "$SHOP_ROOT" 2>/dev/null || true
|
||||||
|
else
|
||||||
|
git config --global --add safe.directory "$SHOP_ROOT" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
run_as_owner() {
|
||||||
|
local cmd="$1"
|
||||||
|
if [ "$(id -u)" -eq 0 ] && [ "$(whoami)" != "$REPO_OWNER" ]; then
|
||||||
|
sudo -u "$REPO_OWNER" env SHOP_ROOT="$SHOP_ROOT" bash -c "cd \"$SHOP_ROOT\" && $cmd"
|
||||||
|
else
|
||||||
|
bash -c "cd \"$SHOP_ROOT\" && $cmd"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure_git_safe "$REPO_OWNER"
|
||||||
|
ensure_git_safe "$(whoami)"
|
||||||
|
|
||||||
|
echo "=== Обновление Shop (админка) ==="
|
||||||
|
echo "Каталог: $SHOP_ROOT"
|
||||||
|
echo "Git от пользователя: $REPO_OWNER (текущий: $(whoami))"
|
||||||
|
|
||||||
|
if [ ! -d .git ]; then
|
||||||
|
echo "Ошибка: нет .git в $SHOP_ROOT"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "Текущая версия:"
|
||||||
|
run_as_owner "git log -1 --oneline"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "--- git sync ---"
|
||||||
|
run_as_owner "bash scripts/git-sync.sh"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "--- npm install ---"
|
||||||
|
if [ "$(id -u)" -eq 0 ]; then
|
||||||
|
npm install --omit=dev
|
||||||
|
else
|
||||||
|
run_as_owner "npm install --omit=dev"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "--- права для службы shop ($SHOP_SERVICE_USER) ---"
|
||||||
|
if [ "$(id -u)" -eq 0 ]; then
|
||||||
|
bash "$SCRIPT_DIR/fix-shop-permissions.sh"
|
||||||
|
else
|
||||||
|
echo "WARN: запустите от root: sudo bash scripts/fix-shop-permissions.sh"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "Новая версия:"
|
||||||
|
run_as_owner "git log -1 --oneline"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "--- перезапуск shop ---"
|
||||||
|
if command -v systemctl >/dev/null 2>&1 && systemctl cat shop.service >/dev/null 2>&1; then
|
||||||
|
if systemctl restart shop; then
|
||||||
|
sleep 2
|
||||||
|
if curl -sf "http://127.0.0.1:${PORT}/health" >/dev/null; then
|
||||||
|
echo "OK: служба shop перезапущена, /health отвечает"
|
||||||
|
else
|
||||||
|
echo "WARN: shop перезапущен, но /health не ответил — journalctl -u shop -n 40"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "WARN: systemctl restart shop не удался. Выполните от root: systemctl restart shop"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "INFO: служба shop не найдена — перезапустите Node вручную"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "Готово."
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Права на каталог магазина для пользователя systemd (www-data)
|
||||||
|
# sudo bash "$SHOP_ROOT/scripts/fix-shop-permissions.sh"
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
# shellcheck source=shop-root.sh
|
||||||
|
source "$SCRIPT_DIR/shop-root.sh"
|
||||||
|
|
||||||
|
SHOP_SERVICE_USER="${SHOP_SERVICE_USER:-www-data}"
|
||||||
|
|
||||||
|
if [ "$(id -u)" -ne 0 ]; then
|
||||||
|
echo "Запустите от root: sudo bash $0"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! id "$SHOP_SERVICE_USER" &>/dev/null; then
|
||||||
|
echo "Ошибка: пользователь $SHOP_SERVICE_USER не найден"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== Права Shop: $SHOP_ROOT → $SHOP_SERVICE_USER ==="
|
||||||
|
|
||||||
|
# CRLF из Windows → 203/EXEC в systemd
|
||||||
|
if [ -d "$SHOP_ROOT/scripts" ]; then
|
||||||
|
find "$SHOP_ROOT/scripts" -name '*.sh' -type f -exec sed -i 's/\r$//' {} +
|
||||||
|
fi
|
||||||
|
|
||||||
|
chown -R "$SHOP_SERVICE_USER:$SHOP_SERVICE_USER" "$SHOP_ROOT"
|
||||||
|
|
||||||
|
# Исполняемые скрипты (wait-postgres.sh для ExecStartPre)
|
||||||
|
if [ -d "$SHOP_ROOT/scripts" ]; then
|
||||||
|
chmod +x "$SHOP_ROOT"/scripts/*.sh 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
# npm cache/logs для www-data
|
||||||
|
for dir in /var/www/.npm /var/www/.cache; do
|
||||||
|
mkdir -p "$dir"
|
||||||
|
chown -R "$SHOP_SERVICE_USER:$SHOP_SERVICE_USER" "$dir"
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ -f "$SHOP_ROOT/.env" ]; then
|
||||||
|
chmod 640 "$SHOP_ROOT/.env"
|
||||||
|
chown "$SHOP_SERVICE_USER:$SHOP_SERVICE_USER" "$SHOP_ROOT/.env"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Родительские каталоги — traverse для www-data
|
||||||
|
chmod o+x /opt /opt/shop 2>/dev/null || true
|
||||||
|
|
||||||
|
echo "OK: владелец $SHOP_SERVICE_USER, скрипты +x"
|
||||||
|
echo "Проверка unit: grep ExecStartPre /etc/systemd/system/shop.service"
|
||||||
|
echo " sudo systemctl daemon-reload && sudo systemctl restart shop"
|
||||||
@@ -58,16 +58,12 @@ fi
|
|||||||
|
|
||||||
npm install --omit=dev --prefix "$SHOP_ROOT"
|
npm install --omit=dev --prefix "$SHOP_ROOT"
|
||||||
|
|
||||||
# Доступ www-data: чтение кода и .env (systemd читает .env от root, но на всякий случай)
|
bash "$SCRIPT_DIR/fix-shop-permissions.sh"
|
||||||
chmod o+x /opt /opt/shop 2>/dev/null || true
|
|
||||||
chmod -R a+rX "$SHOP_ROOT"
|
|
||||||
chmod 640 "$SHOP_ROOT/.env"
|
|
||||||
chown root:www-data "$SHOP_ROOT/.env" 2>/dev/null || chmod 644 "$SHOP_ROOT/.env"
|
|
||||||
|
|
||||||
cp -f "$SHOP_ROOT/deploy/shop.service" /etc/systemd/system/shop.service
|
cp -f "$SHOP_ROOT/deploy/shop.service" /etc/systemd/system/shop.service
|
||||||
sed -i "s|WorkingDirectory=.*|WorkingDirectory=${SHOP_ROOT}|" /etc/systemd/system/shop.service
|
sed -i "s|WorkingDirectory=.*|WorkingDirectory=${SHOP_ROOT}|" /etc/systemd/system/shop.service
|
||||||
sed -i "s|EnvironmentFile=.*|EnvironmentFile=${SHOP_ROOT}/.env|" /etc/systemd/system/shop.service
|
sed -i "s|EnvironmentFile=.*|EnvironmentFile=${SHOP_ROOT}/.env|" /etc/systemd/system/shop.service
|
||||||
sed -i "s|ExecStartPre=.*|ExecStartPre=+${SHOP_ROOT}/scripts/wait-postgres.sh|" /etc/systemd/system/shop.service
|
sed -i "s|ExecStartPre=.*|ExecStartPre=+/bin/bash ${SHOP_ROOT}/scripts/wait-postgres.sh|" /etc/systemd/system/shop.service
|
||||||
sed -i "s|ExecStart=.*|ExecStart=${NODE_BIN} src/server.js|" /etc/systemd/system/shop.service
|
sed -i "s|ExecStart=.*|ExecStart=${NODE_BIN} src/server.js|" /etc/systemd/system/shop.service
|
||||||
|
|
||||||
if ! sudo -u www-data test -r "$SHOP_ROOT/package.json"; then
|
if ! sudo -u www-data test -r "$SHOP_ROOT/package.json"; then
|
||||||
|
|||||||
Executable
+257
@@ -0,0 +1,257 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Интерактивный установщик Shop
|
||||||
|
# bash scripts/install.sh
|
||||||
|
# sudo bash scripts/install.sh (нативная установка на Ubuntu)
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||||
|
|
||||||
|
# --- ввод ---
|
||||||
|
read_default() {
|
||||||
|
local prompt="$1"
|
||||||
|
local default="$2"
|
||||||
|
local value
|
||||||
|
if [ -n "$default" ]; then
|
||||||
|
read -rp "$prompt [$default]: " value
|
||||||
|
echo "${value:-$default}"
|
||||||
|
else
|
||||||
|
read -rp "$prompt: " value
|
||||||
|
echo "$value"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
read_secret() {
|
||||||
|
local prompt="$1"
|
||||||
|
local value
|
||||||
|
read -rsp "$prompt" value
|
||||||
|
echo ""
|
||||||
|
echo "$value"
|
||||||
|
}
|
||||||
|
|
||||||
|
read_secret_confirm() {
|
||||||
|
local prompt="$1"
|
||||||
|
local a b
|
||||||
|
while true; do
|
||||||
|
a=$(read_secret "$prompt")
|
||||||
|
b=$(read_secret "Повторите: ")
|
||||||
|
if [ "$a" = "$b" ]; then
|
||||||
|
echo "$a"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
echo "Пароли не совпадают. Попробуйте снова."
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
gen_secret() {
|
||||||
|
if command -v openssl >/dev/null; then
|
||||||
|
openssl rand -hex 32
|
||||||
|
else
|
||||||
|
head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n'
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Безопасная запись значения в .env (одинарные кавычки)
|
||||||
|
env_quote() {
|
||||||
|
printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
|
||||||
|
}
|
||||||
|
|
||||||
|
email_ok() {
|
||||||
|
[[ "$1" =~ ^[^\s@]+@[^\s@]+\.[^\s@]+$ ]]
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- главная ---
|
||||||
|
clear 2>/dev/null || true
|
||||||
|
echo "============================================"
|
||||||
|
echo " Shop — интерактивная установка"
|
||||||
|
echo "============================================"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Каталог установки
|
||||||
|
if [ -f "$REPO_ROOT/package.json" ]; then
|
||||||
|
INSTALL_DIR=$(read_default "Каталог установки" "$REPO_ROOT")
|
||||||
|
else
|
||||||
|
INSTALL_DIR=$(read_default "Каталог установки" "/opt/shop")
|
||||||
|
if [ ! -f "$INSTALL_DIR/package.json" ]; then
|
||||||
|
GIT_URL=$(read_default "URL git-репозитория" "")
|
||||||
|
if [ -z "$GIT_URL" ]; then
|
||||||
|
echo "Ошибка: укажите URL репозитория или запустите установщик из клона."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Клонирование $GIT_URL -> $INSTALL_DIR ..."
|
||||||
|
mkdir -p "$(dirname "$INSTALL_DIR")"
|
||||||
|
git clone "$GIT_URL" "$INSTALL_DIR"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
cd "$INSTALL_DIR"
|
||||||
|
export SHOP_ROOT="$INSTALL_DIR"
|
||||||
|
|
||||||
|
# Режим
|
||||||
|
echo ""
|
||||||
|
echo "Способ установки:"
|
||||||
|
echo " 1) Docker Compose (PostgreSQL + приложение в контейнерах)"
|
||||||
|
echo " 2) Без Docker (Ubuntu: Node.js + PostgreSQL + systemd)"
|
||||||
|
echo ""
|
||||||
|
MODE=$(read_default "Выберите [1/2]" "1")
|
||||||
|
|
||||||
|
# Администратор
|
||||||
|
echo ""
|
||||||
|
echo "--- Администратор магазина (единственный admin) ---"
|
||||||
|
ADMIN_EMAIL=$(read_default "Email администратора" "admin@site.com")
|
||||||
|
while ! email_ok "$ADMIN_EMAIL"; do
|
||||||
|
echo "Некорректный email."
|
||||||
|
ADMIN_EMAIL=$(read_default "Email администратора" "admin@site.com")
|
||||||
|
done
|
||||||
|
ADMIN_NAME=$(read_default "Имя администратора" "Администратор")
|
||||||
|
ADMIN_PASSWORD=$(read_secret_confirm "Пароль администратора: ")
|
||||||
|
|
||||||
|
# База данных
|
||||||
|
echo ""
|
||||||
|
echo "--- PostgreSQL ---"
|
||||||
|
PG_USER=$(read_default "Пользователь БД" "shop")
|
||||||
|
PG_PASS=$(read_secret_confirm "Пароль БД: ")
|
||||||
|
PG_DB=$(read_default "Имя базы данных" "shop")
|
||||||
|
|
||||||
|
if [ "$MODE" = "1" ]; then
|
||||||
|
PG_HOST="postgres"
|
||||||
|
PG_PORT="5432"
|
||||||
|
APP_PORT=$(read_default "Порт сайта на хосте" "3000")
|
||||||
|
TRUST_PROXY="0"
|
||||||
|
echo ""
|
||||||
|
read -rp "Включить Caddy (HTTPS, порты 80/443)? [y/N]: " USE_CADDY
|
||||||
|
if [[ "${USE_CADDY,,}" == "y" || "${USE_CADDY,,}" == "yes" ]]; then
|
||||||
|
TRUST_PROXY="1"
|
||||||
|
USE_CADDY=1
|
||||||
|
else
|
||||||
|
USE_CADDY=0
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
PG_HOST=$(read_default "Хост PostgreSQL" "127.0.0.1")
|
||||||
|
PG_PORT=$(read_default "Порт PostgreSQL" "5432")
|
||||||
|
APP_PORT="3000"
|
||||||
|
TRUST_PROXY=$(read_default "За reverse proxy (Caddy)? TRUST_PROXY [1/0]" "1")
|
||||||
|
USE_CADDY=0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Сайт и секрет
|
||||||
|
echo ""
|
||||||
|
echo "--- Прочие настройки ---"
|
||||||
|
if [ "$MODE" = "1" ] && [ "$USE_CADDY" = "1" ]; then
|
||||||
|
SITE_DEFAULT="https://shop.example.com"
|
||||||
|
else
|
||||||
|
SITE_DEFAULT="http://localhost:${APP_PORT}"
|
||||||
|
fi
|
||||||
|
SITE_URL=$(read_default "URL сайта (SITE_URL)" "$SITE_DEFAULT")
|
||||||
|
SESSION_SECRET=$(read_default "SESSION_SECRET (Enter = сгенерировать)" "")
|
||||||
|
SESSION_SECRET=${SESSION_SECRET:-$(gen_secret)}
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
read -rp "Настроить SMTP для писем? [y/N]: " SET_SMTP
|
||||||
|
SMTP_BLOCK=""
|
||||||
|
if [[ "${SET_SMTP,,}" == "y" || "${SET_SMTP,,}" == "yes" ]]; then
|
||||||
|
SMTP_HOST=$(read_default "SMTP_HOST" "smtp.example.com")
|
||||||
|
SMTP_PORT=$(read_default "SMTP_PORT" "587")
|
||||||
|
SMTP_USER=$(read_default "SMTP_USER" "")
|
||||||
|
SMTP_PASS=$(read_secret "SMTP_PASS: ")
|
||||||
|
SMTP_FROM=$(read_default "SMTP_FROM" "shop@example.com")
|
||||||
|
SMTP_BLOCK="# SMTP
|
||||||
|
SMTP_HOST=${SMTP_HOST}
|
||||||
|
SMTP_PORT=${SMTP_PORT}
|
||||||
|
SMTP_SECURE=false
|
||||||
|
SMTP_USER=${SMTP_USER}
|
||||||
|
SMTP_PASS=${SMTP_PASS}
|
||||||
|
SMTP_FROM=${SMTP_FROM}
|
||||||
|
"
|
||||||
|
fi
|
||||||
|
|
||||||
|
DATABASE_URL="postgresql://${PG_USER}:${PG_PASS}@${PG_HOST}:${PG_PORT}/${PG_DB}"
|
||||||
|
|
||||||
|
# --- запись .env ---
|
||||||
|
ENV_FILE="$INSTALL_DIR/.env"
|
||||||
|
APP_HOST=$([ "$MODE" = "1" ] && echo "0.0.0.0" || echo "127.0.0.1")
|
||||||
|
{
|
||||||
|
echo "# Создано scripts/install.sh $(date -Iseconds)"
|
||||||
|
echo ""
|
||||||
|
echo "PORT=${APP_PORT}"
|
||||||
|
echo "HOST=${APP_HOST}"
|
||||||
|
echo "NODE_ENV=production"
|
||||||
|
echo "TRUST_PROXY=${TRUST_PROXY}"
|
||||||
|
echo "SESSION_SECRET=$(env_quote "$SESSION_SECRET")"
|
||||||
|
echo ""
|
||||||
|
echo "ADMIN_EMAIL=$(env_quote "$ADMIN_EMAIL")"
|
||||||
|
echo "ADMIN_PASSWORD=$(env_quote "$ADMIN_PASSWORD")"
|
||||||
|
echo "ADMIN_NAME=$(env_quote "$ADMIN_NAME")"
|
||||||
|
echo ""
|
||||||
|
echo "SITE_URL=$(env_quote "$SITE_URL")"
|
||||||
|
echo ""
|
||||||
|
if [ -n "$SMTP_BLOCK" ]; then
|
||||||
|
echo "$SMTP_BLOCK"
|
||||||
|
fi
|
||||||
|
echo "# PostgreSQL"
|
||||||
|
echo "POSTGRES_USER=$(env_quote "$PG_USER")"
|
||||||
|
echo "POSTGRES_PASSWORD=$(env_quote "$PG_PASS")"
|
||||||
|
echo "POSTGRES_DB=$(env_quote "$PG_DB")"
|
||||||
|
echo "DATABASE_URL=$(env_quote "$DATABASE_URL")"
|
||||||
|
echo "PGHOST=$(env_quote "$PG_HOST")"
|
||||||
|
echo "PGPORT=${PG_PORT}"
|
||||||
|
echo "PGUSER=$(env_quote "$PG_USER")"
|
||||||
|
echo "PGPASSWORD=$(env_quote "$PG_PASS")"
|
||||||
|
echo "PGDATABASE=$(env_quote "$PG_DB")"
|
||||||
|
} > "$ENV_FILE"
|
||||||
|
chmod 600 "$ENV_FILE" 2>/dev/null || true
|
||||||
|
echo ""
|
||||||
|
echo "Сохранено: $ENV_FILE"
|
||||||
|
|
||||||
|
# --- установка ---
|
||||||
|
echo ""
|
||||||
|
if [ "$MODE" = "1" ]; then
|
||||||
|
echo "=== Установка через Docker ==="
|
||||||
|
if ! command -v docker >/dev/null; then
|
||||||
|
echo "Ошибка: Docker не установлен. Установите Docker и повторите."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if ! docker compose version >/dev/null 2>&1; then
|
||||||
|
echo "Ошибка: нужен Docker Compose v2 (docker compose)."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
COMPOSE_CMD=(docker compose)
|
||||||
|
if [ "$USE_CADDY" = "1" ]; then
|
||||||
|
echo "Запуск: postgres + app + caddy ..."
|
||||||
|
"${COMPOSE_CMD[@]}" --profile proxy up -d --build
|
||||||
|
else
|
||||||
|
echo "Запуск: postgres + app ..."
|
||||||
|
"${COMPOSE_CMD[@]}" up -d --build
|
||||||
|
fi
|
||||||
|
echo "Ожидание health..."
|
||||||
|
sleep 5
|
||||||
|
curl -sf "http://127.0.0.1:${APP_PORT}/health" && echo "" || echo "Проверьте: docker compose logs app"
|
||||||
|
else
|
||||||
|
echo "=== Установка без Docker (Ubuntu) ==="
|
||||||
|
if [ "$(id -u)" -ne 0 ]; then
|
||||||
|
echo "Запустите с root: sudo bash scripts/install.sh"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
bash "$SCRIPT_DIR/install-postgresql-ubuntu.sh"
|
||||||
|
export DB_USER="$PG_USER" DB_PASS="$PG_PASS" DB_NAME="$PG_DB"
|
||||||
|
bash "$SCRIPT_DIR/setup-postgres-ubuntu.sh"
|
||||||
|
npm install --omit=dev
|
||||||
|
bash "$SCRIPT_DIR/install-shop-service.sh"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "============================================"
|
||||||
|
echo " Установка завершена"
|
||||||
|
echo "============================================"
|
||||||
|
echo " Каталог: $INSTALL_DIR"
|
||||||
|
echo " Сайт: $SITE_URL"
|
||||||
|
echo " Админ: $ADMIN_EMAIL"
|
||||||
|
if [ "$MODE" = "1" ]; then
|
||||||
|
echo " Порт: $APP_PORT"
|
||||||
|
echo " Логи: docker compose -f $INSTALL_DIR/docker-compose.yml logs -f"
|
||||||
|
else
|
||||||
|
echo " Служба: systemctl status shop"
|
||||||
|
echo " Health: curl http://127.0.0.1:3000/health"
|
||||||
|
fi
|
||||||
|
echo " Обновление: bash $INSTALL_DIR/scripts/server-update.sh"
|
||||||
|
echo "============================================"
|
||||||
@@ -20,7 +20,13 @@ fi
|
|||||||
|
|
||||||
bash "$SCRIPT_DIR/git-sync.sh"
|
bash "$SCRIPT_DIR/git-sync.sh"
|
||||||
|
|
||||||
|
if [ "$(id -u)" -eq 0 ]; then
|
||||||
npm install --omit=dev
|
npm install --omit=dev
|
||||||
|
bash "$SCRIPT_DIR/fix-shop-permissions.sh"
|
||||||
|
else
|
||||||
|
npm install --omit=dev
|
||||||
|
echo "ВНИМАНИЕ: для прав www-data выполните: sudo bash $SCRIPT_DIR/fix-shop-permissions.sh"
|
||||||
|
fi
|
||||||
|
|
||||||
if [ -f .env ] && ! grep -q '^DATABASE_URL=' .env; then
|
if [ -f .env ] && ! grep -q '^DATABASE_URL=' .env; then
|
||||||
echo "ВНИМАНИЕ: добавьте DATABASE_URL в .env (см. .env.example)"
|
echo "ВНИМАНИЕ: добавьте DATABASE_URL в .env (см. .env.example)"
|
||||||
|
|||||||
@@ -32,3 +32,7 @@ fi
|
|||||||
|
|
||||||
export SHOP_ROOT
|
export SHOP_ROOT
|
||||||
cd "$SHOP_ROOT"
|
cd "$SHOP_ROOT"
|
||||||
|
|
||||||
|
if [ -d "$SHOP_ROOT/.git" ]; then
|
||||||
|
git config --global --add safe.directory "$SHOP_ROOT" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|||||||
+11
-4
@@ -1,4 +1,5 @@
|
|||||||
const { query } = require('./db');
|
const { query } = require('./db');
|
||||||
|
const { getEffectivePriceCents, isSaleActive } = require('./utils/productPrice');
|
||||||
|
|
||||||
function getCart(req) {
|
function getCart(req) {
|
||||||
if (!req.session.cart) {
|
if (!req.session.cart) {
|
||||||
@@ -22,11 +23,17 @@ async function cartItems(cart) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
return products
|
return products
|
||||||
.map((p) => ({
|
.map((p) => {
|
||||||
|
const effective = getEffectivePriceCents(p);
|
||||||
|
const qty = cart[p.id] || 0;
|
||||||
|
return {
|
||||||
...p,
|
...p,
|
||||||
quantity: cart[p.id] || 0,
|
quantity: qty,
|
||||||
line_total: (cart[p.id] || 0) * p.price_cents,
|
effective_price_cents: effective,
|
||||||
}))
|
on_sale: isSaleActive(p),
|
||||||
|
line_total: qty * effective,
|
||||||
|
};
|
||||||
|
})
|
||||||
.filter((p) => p.quantity > 0);
|
.filter((p) => p.quantity > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
const {
|
||||||
|
getCaptchaConfig,
|
||||||
|
YANDEX_BLOCKED_MSG,
|
||||||
|
isYandexCaptchaAttempt,
|
||||||
|
} = require('../services/captcha');
|
||||||
|
|
||||||
|
function loadCaptchaLocals(req, res, next) {
|
||||||
|
res.locals.captcha = getCaptchaConfig();
|
||||||
|
res.locals.yandexCaptchaBlockedMsg = YANDEX_BLOCKED_MSG;
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Блокировка попыток отправить Яндекс-капчу */
|
||||||
|
function rejectYandexCaptcha(req, res, next) {
|
||||||
|
if (req.method === 'POST' && isYandexCaptchaAttempt(req)) {
|
||||||
|
return res.status(403).render('error', {
|
||||||
|
title: 'Доступ запрещён',
|
||||||
|
message: YANDEX_BLOCKED_MSG,
|
||||||
|
code: 403,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { loadCaptchaLocals, rejectYandexCaptcha };
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
const buckets = new Map();
|
||||||
|
|
||||||
|
function rateLimit({ windowMs = 15 * 60 * 1000, max = 20, keyPrefix = '' }) {
|
||||||
|
return (req, res, next) => {
|
||||||
|
const ip = req.ip || req.socket?.remoteAddress || 'unknown';
|
||||||
|
const key = `${keyPrefix}:${ip}`;
|
||||||
|
const now = Date.now();
|
||||||
|
let entry = buckets.get(key);
|
||||||
|
if (!entry || now > entry.resetAt) {
|
||||||
|
entry = { count: 0, resetAt: now + windowMs };
|
||||||
|
buckets.set(key, entry);
|
||||||
|
}
|
||||||
|
entry.count += 1;
|
||||||
|
if (entry.count > max) {
|
||||||
|
return res.status(429).render('error', {
|
||||||
|
title: 'Слишком много запросов',
|
||||||
|
message: 'Подождите несколько минут и попробуйте снова.',
|
||||||
|
code: 429,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { rateLimit };
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
function securityHeaders(_req, res, next) {
|
||||||
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||||
|
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
|
||||||
|
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||||
|
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { securityHeaders };
|
||||||
+542
-10
@@ -10,6 +10,8 @@
|
|||||||
--success: #00b894;
|
--success: #00b894;
|
||||||
--warn: #fdcb6e;
|
--warn: #fdcb6e;
|
||||||
--error: #ff7675;
|
--error: #ff7675;
|
||||||
|
--sale: #ff6b6b;
|
||||||
|
--sale-bg: rgba(255, 107, 107, 0.12);
|
||||||
--radius: 12px;
|
--radius: 12px;
|
||||||
--shadow: 0 8px 32px rgba(0, 0, 0, 0.35);
|
--shadow: 0 8px 32px rgba(0, 0, 0, 0.35);
|
||||||
font-family: 'DM Sans', system-ui, sans-serif;
|
font-family: 'DM Sans', system-ui, sans-serif;
|
||||||
@@ -63,6 +65,9 @@ a:hover {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.logo {
|
.logo {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.45rem;
|
||||||
font-size: 1.35rem;
|
font-size: 1.35rem;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
color: var(--text);
|
color: var(--text);
|
||||||
@@ -70,6 +75,10 @@ a:hover {
|
|||||||
letter-spacing: -0.02em;
|
letter-spacing: -0.02em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.logo__icon {
|
||||||
|
color: var(--accent-hover);
|
||||||
|
}
|
||||||
|
|
||||||
.logo:hover {
|
.logo:hover {
|
||||||
color: var(--accent-hover);
|
color: var(--accent-hover);
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
@@ -78,13 +87,24 @@ a:hover {
|
|||||||
.search {
|
.search {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
display: flex;
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
min-width: 200px;
|
min-width: 200px;
|
||||||
max-width: 420px;
|
max-width: 420px;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search__icon {
|
||||||
|
position: absolute;
|
||||||
|
left: 0.75rem;
|
||||||
|
color: var(--muted);
|
||||||
|
pointer-events: none;
|
||||||
|
display: flex;
|
||||||
}
|
}
|
||||||
|
|
||||||
.search input {
|
.search input {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
|
padding-left: 2.35rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.nav {
|
.nav {
|
||||||
@@ -103,10 +123,25 @@ a:hover {
|
|||||||
color: var(--text);
|
color: var(--text);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.nav__link--icon {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav__link--icon:hover {
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
.nav__cart {
|
.nav__cart {
|
||||||
position: relative;
|
position: relative;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.nav__admin {
|
||||||
|
color: var(--warn);
|
||||||
|
}
|
||||||
|
|
||||||
.badge {
|
.badge {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -144,7 +179,8 @@ a:hover {
|
|||||||
letter-spacing: -0.03em;
|
letter-spacing: -0.03em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.hero p {
|
.hero p,
|
||||||
|
.hero__lead {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
}
|
}
|
||||||
@@ -185,7 +221,7 @@ a:hover {
|
|||||||
border: 1px solid var(--border);
|
border: 1px solid var(--border);
|
||||||
border-radius: var(--radius);
|
border-radius: var(--radius);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
transition: transform 0.2s, box-shadow 0.2s;
|
transition: transform 0.2s, box-shadow 0.2s, border-color 0.2s;
|
||||||
}
|
}
|
||||||
|
|
||||||
.card:hover {
|
.card:hover {
|
||||||
@@ -193,13 +229,40 @@ a:hover {
|
|||||||
box-shadow: var(--shadow);
|
box-shadow: var(--shadow);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.card--sale {
|
||||||
|
border-color: rgba(255, 107, 107, 0.35);
|
||||||
|
box-shadow: 0 0 0 1px rgba(255, 107, 107, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
.card--sale:hover {
|
||||||
|
border-color: rgba(255, 107, 107, 0.55);
|
||||||
|
}
|
||||||
|
|
||||||
.card__image-wrap {
|
.card__image-wrap {
|
||||||
display: block;
|
display: block;
|
||||||
|
position: relative;
|
||||||
aspect-ratio: 1;
|
aspect-ratio: 1;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
background: var(--surface-2);
|
background: var(--surface-2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.card__sale-ribbon {
|
||||||
|
position: absolute;
|
||||||
|
top: 0.65rem;
|
||||||
|
left: 0.65rem;
|
||||||
|
z-index: 2;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.3rem;
|
||||||
|
padding: 0.3rem 0.55rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #fff;
|
||||||
|
background: linear-gradient(135deg, #ff6b6b, #ee5a5a);
|
||||||
|
border-radius: 6px;
|
||||||
|
box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
.card__image {
|
.card__image {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
@@ -240,10 +303,8 @@ a:hover {
|
|||||||
color: var(--accent-hover);
|
color: var(--accent-hover);
|
||||||
}
|
}
|
||||||
|
|
||||||
.card__price {
|
.card .price-block {
|
||||||
margin: 0 0 0.75rem;
|
margin-bottom: 0.75rem;
|
||||||
font-size: 1.1rem;
|
|
||||||
font-weight: 700;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.card__form {
|
.card__form {
|
||||||
@@ -272,9 +333,16 @@ a:hover {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.product-detail__price {
|
.product-detail__price {
|
||||||
font-size: 1.75rem;
|
margin: 0.75rem 0 1rem;
|
||||||
font-weight: 700;
|
padding: 1rem 1.15rem;
|
||||||
margin: 0.5rem 0;
|
background: var(--surface-2);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
.product-detail__price:has(.price-block--sale) {
|
||||||
|
border-color: rgba(255, 107, 107, 0.3);
|
||||||
|
background: var(--sale-bg);
|
||||||
}
|
}
|
||||||
|
|
||||||
.product-detail__desc {
|
.product-detail__desc {
|
||||||
@@ -323,15 +391,29 @@ a:hover {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.link-back {
|
.link-back {
|
||||||
display: inline-block;
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
margin-top: 1rem;
|
margin-top: 1rem;
|
||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.link-back:hover {
|
||||||
|
color: var(--text);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
vertical-align: middle;
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn {
|
.btn {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
|
gap: 0.45rem;
|
||||||
padding: 0.55rem 1.1rem;
|
padding: 0.55rem 1.1rem;
|
||||||
border: none;
|
border: none;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
@@ -547,6 +629,106 @@ a:hover {
|
|||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.cart-sidebar {
|
||||||
|
display: grid;
|
||||||
|
gap: 1rem;
|
||||||
|
margin-top: 1.25rem;
|
||||||
|
max-width: 420px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 900px) {
|
||||||
|
.cart-table-wrap {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr minmax(280px, 360px);
|
||||||
|
gap: 1.5rem;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-sidebar {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.promo-box__title {
|
||||||
|
margin: 0 0 0.75rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.promo-box__form {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.promo-box__form .input {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 120px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.promo-box__applied {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.promo-box__discount {
|
||||||
|
color: var(--success);
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.promo-countdown {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
background: rgba(253, 203, 110, 0.12);
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid rgba(253, 203, 110, 0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
.promo-countdown__timer {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--warn);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.promo-countdown__timer--ended {
|
||||||
|
color: var(--error);
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-summary__dl {
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-summary__dl dt {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-summary__dl dd {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-summary__dl dt,
|
||||||
|
.cart-summary__dl dd {
|
||||||
|
display: inline-block;
|
||||||
|
width: 48%;
|
||||||
|
vertical-align: top;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-summary__discount {
|
||||||
|
color: var(--success);
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-summary__total-label,
|
||||||
|
.cart-summary__total {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkout-promo {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
margin: 0.75rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
.cart-actions {
|
.cart-actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
@@ -906,3 +1088,353 @@ a:hover {
|
|||||||
body:has(.cookie-banner) .main {
|
body:has(.cookie-banner) .main {
|
||||||
padding-bottom: 7rem;
|
padding-bottom: 7rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.price-block {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block__meta {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block__tag {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.25rem;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
font-weight: 600;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
color: var(--sale);
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block__badge {
|
||||||
|
font-size: 0.7rem;
|
||||||
|
font-weight: 700;
|
||||||
|
padding: 0.15rem 0.45rem;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: var(--sale-bg);
|
||||||
|
color: var(--sale);
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block__prices {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 0.5rem 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block__old {
|
||||||
|
position: relative;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.95em;
|
||||||
|
font-weight: 500;
|
||||||
|
text-decoration: line-through;
|
||||||
|
text-decoration-thickness: 2px;
|
||||||
|
text-decoration-color: var(--sale);
|
||||||
|
opacity: 0.85;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block__current {
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--text);
|
||||||
|
letter-spacing: -0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block__current--solo {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block--sale .price-block__current {
|
||||||
|
color: var(--sale);
|
||||||
|
font-weight: 800;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block__savings {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--success);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block--md .price-block__current {
|
||||||
|
font-size: 1.2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block--md .price-block__old {
|
||||||
|
font-size: 0.95rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block--lg .price-block__current {
|
||||||
|
font-size: clamp(1.75rem, 4vw, 2.25rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block--lg .price-block__old {
|
||||||
|
font-size: 1.15rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block--sm .price-block__meta {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block--sm .price-block__prices {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 0.15rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block--sm .price-block__current {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-table__price .price-block {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.promo-countdown--product {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
margin: 0.75rem 0 0;
|
||||||
|
padding: 0;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.promo-countdown--product strong {
|
||||||
|
color: var(--warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge--sale {
|
||||||
|
background: var(--sale-bg);
|
||||||
|
color: var(--sale);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
padding: 0.15rem 0.45rem;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-pricing-form {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: flex-end;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-pricing-form--ends {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.label--inline {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.2rem;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-hint {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-promo-form {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.35rem;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form--grid {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.promo-countdown--sm {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge--warn {
|
||||||
|
background: rgba(253, 203, 110, 0.15);
|
||||||
|
color: var(--warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-system__meta {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-system__path {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-system__actions {
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-system__hr {
|
||||||
|
border: none;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
margin: 1.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-system__form {
|
||||||
|
max-width: 360px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-system__pre {
|
||||||
|
margin: 0;
|
||||||
|
padding: 1rem;
|
||||||
|
background: var(--bg);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
line-height: 1.45;
|
||||||
|
overflow-x: auto;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-system__log {
|
||||||
|
margin-top: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-system__help {
|
||||||
|
margin-top: 1.25rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.captcha-block {
|
||||||
|
margin: 1rem 0;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--surface-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.captcha-block__yandex-notice {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 0.4rem;
|
||||||
|
margin: 0 0 0.75rem;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--warn);
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.captcha-widget {
|
||||||
|
min-height: 78px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.captcha-block__provider {
|
||||||
|
margin: 0.5rem 0 0;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.catalog-toolbar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem 1.5rem;
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
background: var(--surface-2);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.catalog-toolbar__field {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.catalog-toolbar__label {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.catalog-toolbar__check {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card__stock-badge {
|
||||||
|
position: absolute;
|
||||||
|
top: 0.5rem;
|
||||||
|
left: 0.5rem;
|
||||||
|
z-index: 2;
|
||||||
|
padding: 0.2rem 0.5rem;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
font-weight: 600;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: rgba(253, 203, 110, 0.95);
|
||||||
|
color: #2d3436;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card__stock-badge--out {
|
||||||
|
background: rgba(99, 110, 114, 0.9);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card--out-of-stock {
|
||||||
|
opacity: 0.85;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card--out-of-stock .card__image {
|
||||||
|
filter: grayscale(0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.recently-viewed {
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recently-viewed__title {
|
||||||
|
margin: 0 0 0.75rem;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recently-viewed__grid {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.75rem;
|
||||||
|
overflow-x: auto;
|
||||||
|
padding-bottom: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recently-viewed__card {
|
||||||
|
flex: 0 0 120px;
|
||||||
|
padding: 0.5rem;
|
||||||
|
text-decoration: none;
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recently-viewed__img {
|
||||||
|
width: 100%;
|
||||||
|
height: 72px;
|
||||||
|
object-fit: cover;
|
||||||
|
border-radius: 6px;
|
||||||
|
margin-bottom: 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recently-viewed__name {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-header__actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
(function () {
|
||||||
|
function pad(n) {
|
||||||
|
return String(n).padStart(2, '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRemaining(ms) {
|
||||||
|
if (ms <= 0) return 'акция завершена';
|
||||||
|
const s = Math.floor(ms / 1000);
|
||||||
|
const d = Math.floor(s / 86400);
|
||||||
|
const h = Math.floor((s % 86400) / 3600);
|
||||||
|
const m = Math.floor((s % 3600) / 60);
|
||||||
|
const sec = s % 60;
|
||||||
|
if (d > 0) return `${d} д ${pad(h)}:${pad(m)}:${pad(sec)}`;
|
||||||
|
return `${pad(h)}:${pad(m)}:${pad(sec)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelectorAll('.promo-countdown[data-expires]').forEach((el) => {
|
||||||
|
const expires = new Date(el.dataset.expires).getTime();
|
||||||
|
const timer = el.querySelector('.promo-countdown__timer');
|
||||||
|
if (!timer || Number.isNaN(expires)) return;
|
||||||
|
|
||||||
|
function tick() {
|
||||||
|
const left = expires - Date.now();
|
||||||
|
timer.textContent = formatRemaining(left);
|
||||||
|
if (left <= 0) timer.classList.add('promo-countdown__timer--ended');
|
||||||
|
}
|
||||||
|
|
||||||
|
tick();
|
||||||
|
const id = setInterval(tick, 1000);
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.addEventListener('beforeunload', () => clearInterval(id));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})();
|
||||||
+11
-1
@@ -22,7 +22,7 @@ router.use((req, res, next) => {
|
|||||||
|
|
||||||
async function loadAccountUser(userId) {
|
async function loadAccountUser(userId) {
|
||||||
const { rows } = await query(
|
const { rows } = await query(
|
||||||
'SELECT id, email, name, role, created_at, passkey_enabled FROM users WHERE id = $1',
|
'SELECT id, email, name, role, created_at, passkey_enabled, loyalty_points FROM users WHERE id = $1',
|
||||||
[userId]
|
[userId]
|
||||||
);
|
);
|
||||||
return rows[0];
|
return rows[0];
|
||||||
@@ -47,11 +47,13 @@ function accountRender(res, options) {
|
|||||||
formatPrice,
|
formatPrice,
|
||||||
passkeys,
|
passkeys,
|
||||||
isAdmin,
|
isAdmin,
|
||||||
|
recentOrders,
|
||||||
} = options;
|
} = options;
|
||||||
res.render('account/index', {
|
res.render('account/index', {
|
||||||
title: 'Личный кабинет',
|
title: 'Личный кабинет',
|
||||||
user,
|
user,
|
||||||
orderCount,
|
orderCount,
|
||||||
|
recentOrders: recentOrders || [],
|
||||||
reservations: reservations || [],
|
reservations: reservations || [],
|
||||||
passkeys: passkeys || [],
|
passkeys: passkeys || [],
|
||||||
isAdmin: Boolean(isAdmin),
|
isAdmin: Boolean(isAdmin),
|
||||||
@@ -85,9 +87,17 @@ router.get(
|
|||||||
|
|
||||||
const passkeys = await webauthn.getCredentialsForUser(user.id);
|
const passkeys = await webauthn.getCredentialsForUser(user.id);
|
||||||
|
|
||||||
|
const { rows: recentOrders } = await query(
|
||||||
|
`SELECT id, status, total_cents, created_at
|
||||||
|
FROM orders WHERE user_id = $1
|
||||||
|
ORDER BY created_at DESC LIMIT 10`,
|
||||||
|
[user.id]
|
||||||
|
);
|
||||||
|
|
||||||
accountRender(res, {
|
accountRender(res, {
|
||||||
user,
|
user,
|
||||||
orderCount: countResult.rows[0].n,
|
orderCount: countResult.rows[0].n,
|
||||||
|
recentOrders,
|
||||||
reservations,
|
reservations,
|
||||||
passkeys,
|
passkeys,
|
||||||
isAdmin: user.role === ROLES.ADMIN,
|
isAdmin: user.role === ROLES.ADMIN,
|
||||||
|
|||||||
+287
-4
@@ -4,6 +4,7 @@ const { requireAdmin } = require('../middleware/auth');
|
|||||||
const { asyncHandler } = require('../utils/asyncHandler');
|
const { asyncHandler } = require('../utils/asyncHandler');
|
||||||
const { ROLE_LABELS } = require('../constants/roles');
|
const { ROLE_LABELS } = require('../constants/roles');
|
||||||
const { notifyIfBackInStock } = require('../services/stock-alerts');
|
const { notifyIfBackInStock } = require('../services/stock-alerts');
|
||||||
|
const gitDeploy = require('../services/git-deploy');
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -60,21 +61,62 @@ router.get(
|
|||||||
router.get(
|
router.get(
|
||||||
'/orders',
|
'/orders',
|
||||||
asyncHandler(async (req, res) => {
|
asyncHandler(async (req, res) => {
|
||||||
const { rows: orders } = await query(
|
const statusFilter = req.query.status || '';
|
||||||
`SELECT o.id, o.status, o.total_cents, o.created_at, o.customer_name, o.customer_email,
|
const allowed = ['pending', 'paid', 'shipped', 'cancelled'];
|
||||||
|
let sql = `
|
||||||
|
SELECT o.id, o.status, o.total_cents, o.created_at, o.customer_name, o.customer_email,
|
||||||
u.email AS account_email
|
u.email AS account_email
|
||||||
FROM orders o
|
FROM orders o
|
||||||
JOIN users u ON u.id = o.user_id
|
JOIN users u ON u.id = o.user_id
|
||||||
ORDER BY o.created_at DESC`
|
`;
|
||||||
);
|
const params = [];
|
||||||
|
if (statusFilter && allowed.includes(statusFilter)) {
|
||||||
|
sql += ' WHERE o.status = $1';
|
||||||
|
params.push(statusFilter);
|
||||||
|
}
|
||||||
|
sql += ' ORDER BY o.created_at DESC';
|
||||||
|
|
||||||
|
const { rows: orders } = await query(sql, params);
|
||||||
res.render('admin/orders', {
|
res.render('admin/orders', {
|
||||||
title: 'Заказы',
|
title: 'Заказы',
|
||||||
orders,
|
orders,
|
||||||
formatPrice,
|
formatPrice,
|
||||||
|
statusFilter,
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
'/orders/export.csv',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const { rows } = await query(
|
||||||
|
`SELECT o.id, o.status, o.total_cents, o.created_at,
|
||||||
|
o.customer_name, o.customer_email, o.customer_phone, o.address
|
||||||
|
FROM orders o
|
||||||
|
ORDER BY o.created_at DESC`
|
||||||
|
);
|
||||||
|
const esc = (v) => `"${String(v ?? '').replace(/"/g, '""')}"`;
|
||||||
|
const lines = [
|
||||||
|
'id;status;total_rub;customer;email;phone;address;created_at',
|
||||||
|
...rows.map((o) =>
|
||||||
|
[
|
||||||
|
o.id,
|
||||||
|
o.status,
|
||||||
|
(o.total_cents / 100).toFixed(2),
|
||||||
|
esc(o.customer_name),
|
||||||
|
esc(o.customer_email),
|
||||||
|
esc(o.customer_phone),
|
||||||
|
esc(o.address),
|
||||||
|
new Date(o.created_at).toISOString(),
|
||||||
|
].join(';')
|
||||||
|
),
|
||||||
|
];
|
||||||
|
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
|
||||||
|
res.setHeader('Content-Disposition', 'attachment; filename="orders.csv"');
|
||||||
|
res.send('\uFEFF' + lines.join('\n'));
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
router.post(
|
router.post(
|
||||||
'/orders/:id/status',
|
'/orders/:id/status',
|
||||||
asyncHandler(async (req, res) => {
|
asyncHandler(async (req, res) => {
|
||||||
@@ -99,12 +141,20 @@ router.get(
|
|||||||
LEFT JOIN categories c ON c.id = p.category_id
|
LEFT JOIN categories c ON c.id = p.category_id
|
||||||
ORDER BY p.id`
|
ORDER BY p.id`
|
||||||
);
|
);
|
||||||
|
const productPrice = require('../utils/productPrice');
|
||||||
res.render('admin/products', {
|
res.render('admin/products', {
|
||||||
title: 'Товары',
|
title: 'Товары',
|
||||||
products,
|
products,
|
||||||
formatPrice,
|
formatPrice,
|
||||||
|
isSaleActive: productPrice.isSaleActive,
|
||||||
|
effectivePrice: productPrice.getEffectivePriceCents,
|
||||||
|
salePercent: productPrice.salePercent,
|
||||||
stockUpdated: req.query.stock_updated === '1',
|
stockUpdated: req.query.stock_updated === '1',
|
||||||
notified: req.query.notified ? parseInt(req.query.notified, 10) : 0,
|
notified: req.query.notified ? parseInt(req.query.notified, 10) : 0,
|
||||||
|
pricingUpdated: req.query.pricing_updated === '1',
|
||||||
|
pricingError: req.query.pricing_error
|
||||||
|
? decodeURIComponent(String(req.query.pricing_error))
|
||||||
|
: null,
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
@@ -135,6 +185,114 @@ router.post(
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/products/:id/pricing',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const productId = parseInt(req.params.id, 10);
|
||||||
|
const priceRub = parseFloat(String(req.body.price_rub || '').replace(',', '.'));
|
||||||
|
const saleRubRaw = String(req.body.sale_price_rub ?? '').trim();
|
||||||
|
const clearSale = req.body.clear_sale === '1';
|
||||||
|
|
||||||
|
if (clearSale) {
|
||||||
|
const price_cents = Number.isFinite(priceRub) ? Math.round(priceRub * 100) : null;
|
||||||
|
if (!Number.isFinite(productId) || price_cents == null || price_cents < 0) {
|
||||||
|
return res.redirect('/admin/products?pricing_error=' + encodeURIComponent('Некорректная цена'));
|
||||||
|
}
|
||||||
|
await query(
|
||||||
|
`UPDATE products SET price_cents = $1, sale_price_cents = NULL, sale_ends_at = NULL WHERE id = $2`,
|
||||||
|
[price_cents, productId]
|
||||||
|
);
|
||||||
|
return res.redirect('/admin/products?pricing_updated=1');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Number.isFinite(productId) || !Number.isFinite(priceRub) || priceRub < 0) {
|
||||||
|
return res.redirect('/admin/products?pricing_error=' + encodeURIComponent('Некорректная цена'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const { rows: existingRows } = await query(
|
||||||
|
'SELECT sale_price_cents, sale_ends_at FROM products WHERE id = $1',
|
||||||
|
[productId]
|
||||||
|
);
|
||||||
|
const existing = existingRows[0] || {};
|
||||||
|
|
||||||
|
const price_cents = Math.round(priceRub * 100);
|
||||||
|
let sale_price_cents = existing.sale_price_cents ?? null;
|
||||||
|
let sale_ends_at = existing.sale_ends_at ?? null;
|
||||||
|
|
||||||
|
if (saleRubRaw !== '') {
|
||||||
|
const saleRub = parseFloat(saleRubRaw.replace(',', '.'));
|
||||||
|
if (!Number.isFinite(saleRub) || saleRub < 0) {
|
||||||
|
return res.redirect(
|
||||||
|
'/admin/products?pricing_error=' + encodeURIComponent('Некорректная цена со скидкой')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
sale_price_cents = Math.round(saleRub * 100);
|
||||||
|
if (sale_price_cents >= price_cents) {
|
||||||
|
return res.redirect(
|
||||||
|
'/admin/products?pricing_error=' +
|
||||||
|
encodeURIComponent('Цена со скидкой должна быть ниже обычной')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else if (!('sale_ends_at' in req.body)) {
|
||||||
|
sale_price_cents = null;
|
||||||
|
sale_ends_at = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ('sale_ends_at' in req.body) {
|
||||||
|
sale_ends_at = req.body.sale_ends_at
|
||||||
|
? new Date(req.body.sale_ends_at).toISOString()
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
await query(
|
||||||
|
`UPDATE products SET price_cents = $1, sale_price_cents = $2, sale_ends_at = $3 WHERE id = $4`,
|
||||||
|
[price_cents, sale_price_cents, sale_ends_at, productId]
|
||||||
|
);
|
||||||
|
|
||||||
|
res.redirect('/admin/products?pricing_updated=1');
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/promo-codes/:id/update',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const id = parseInt(req.params.id, 10);
|
||||||
|
const description = (req.body.description || '').trim();
|
||||||
|
const discount_type = req.body.discount_type === 'fixed' ? 'fixed' : 'percent';
|
||||||
|
const discount_value = parseInt(req.body.discount_value, 10);
|
||||||
|
const min_order_cents = Math.max(0, parseInt(req.body.min_order_rub, 10) || 0) * 100;
|
||||||
|
const max_uses =
|
||||||
|
req.body.max_uses === '' || req.body.max_uses == null
|
||||||
|
? null
|
||||||
|
: parseInt(req.body.max_uses, 10);
|
||||||
|
|
||||||
|
const { rows: promoRows } = await query('SELECT expires_at FROM promo_codes WHERE id = $1', [
|
||||||
|
id,
|
||||||
|
]);
|
||||||
|
let expires_at = promoRows[0]?.expires_at;
|
||||||
|
if (req.body.valid_days) {
|
||||||
|
const days = Math.max(1, parseInt(req.body.valid_days, 10) || 7);
|
||||||
|
const expires = new Date();
|
||||||
|
expires.setDate(expires.getDate() + days);
|
||||||
|
expires_at = expires.toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
const value =
|
||||||
|
discount_type === 'percent'
|
||||||
|
? Math.min(100, discount_value)
|
||||||
|
: discount_value * 100;
|
||||||
|
|
||||||
|
await query(
|
||||||
|
`UPDATE promo_codes SET
|
||||||
|
description = $1, discount_type = $2, discount_value = $3,
|
||||||
|
expires_at = $4, min_order_cents = $5, max_uses = $6
|
||||||
|
WHERE id = $7`,
|
||||||
|
[description, discount_type, value, expires_at, min_order_cents, max_uses, id]
|
||||||
|
);
|
||||||
|
res.redirect('/admin/promo-codes?updated=1');
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
router.get(
|
router.get(
|
||||||
'/reservations',
|
'/reservations',
|
||||||
asyncHandler(async (req, res) => {
|
asyncHandler(async (req, res) => {
|
||||||
@@ -173,4 +331,129 @@ router.post(
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
'/promo-codes',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const { rows: promos } = await query(
|
||||||
|
`SELECT * FROM promo_codes ORDER BY created_at DESC`
|
||||||
|
);
|
||||||
|
res.render('admin/promo-codes', {
|
||||||
|
title: 'Промокоды',
|
||||||
|
promos,
|
||||||
|
formatPrice,
|
||||||
|
created: req.query.created === '1',
|
||||||
|
updated: req.query.updated === '1',
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/promo-codes',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const code = (req.body.code || '').trim().toUpperCase();
|
||||||
|
const description = (req.body.description || '').trim();
|
||||||
|
const discount_type = req.body.discount_type === 'fixed' ? 'fixed' : 'percent';
|
||||||
|
const discount_value = parseInt(req.body.discount_value, 10);
|
||||||
|
const days = Math.max(1, parseInt(req.body.valid_days, 10) || 30);
|
||||||
|
const min_order_cents = Math.max(0, parseInt(req.body.min_order_rub, 10) || 0) * 100;
|
||||||
|
const max_uses = req.body.max_uses ? parseInt(req.body.max_uses, 10) : null;
|
||||||
|
|
||||||
|
if (!code || !discount_value) {
|
||||||
|
return res.redirect('/admin/promo-codes?error=1');
|
||||||
|
}
|
||||||
|
|
||||||
|
const expires = new Date();
|
||||||
|
expires.setDate(expires.getDate() + days);
|
||||||
|
|
||||||
|
const value =
|
||||||
|
discount_type === 'percent'
|
||||||
|
? Math.min(100, discount_value)
|
||||||
|
: discount_value * 100;
|
||||||
|
|
||||||
|
await query(
|
||||||
|
`INSERT INTO promo_codes (code, description, discount_type, discount_value, expires_at, min_order_cents, max_uses)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
||||||
|
[code, description, discount_type, value, expires.toISOString(), min_order_cents, max_uses]
|
||||||
|
);
|
||||||
|
|
||||||
|
res.redirect('/admin/promo-codes?created=1');
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/promo-codes/:id/toggle',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
await query(
|
||||||
|
`UPDATE promo_codes SET active = NOT active WHERE id = $1`,
|
||||||
|
[req.params.id]
|
||||||
|
);
|
||||||
|
res.redirect('/admin/promo-codes');
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
'/system',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const fetchRemote =
|
||||||
|
req.query.checked === '1' || req.query.done === '1' || req.query.failed === '1';
|
||||||
|
|
||||||
|
let updateLog = null;
|
||||||
|
let updateOk = false;
|
||||||
|
let updateFail = false;
|
||||||
|
let updateCode = null;
|
||||||
|
|
||||||
|
if (req.query.done === '1' || req.query.failed === '1') {
|
||||||
|
updateLog = req.session.adminUpdateLog || null;
|
||||||
|
updateOk = req.session.adminUpdateOk === true;
|
||||||
|
updateFail = req.session.adminUpdateOk === false;
|
||||||
|
updateCode = req.session.adminUpdateCode ?? null;
|
||||||
|
delete req.session.adminUpdateLog;
|
||||||
|
delete req.session.adminUpdateOk;
|
||||||
|
delete req.session.adminUpdateCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
const git = await gitDeploy.getGitInfo({ fetchRemote: !!fetchRemote });
|
||||||
|
res.render('admin/system', {
|
||||||
|
title: 'Обновление',
|
||||||
|
git,
|
||||||
|
updateLog,
|
||||||
|
updateOk,
|
||||||
|
updateFail,
|
||||||
|
updateCode,
|
||||||
|
confirmError: req.query.error === 'confirm',
|
||||||
|
disabledError: req.query.error === 'disabled',
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/system/check',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
res.redirect('/admin/system?checked=1');
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/system/update',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
if (!gitDeploy.isUpdateEnabled()) {
|
||||||
|
return res.redirect('/admin/system?error=disabled');
|
||||||
|
}
|
||||||
|
const confirm = (req.body.confirm || '').trim().toLowerCase();
|
||||||
|
if (confirm !== 'update') {
|
||||||
|
return res.redirect('/admin/system?error=confirm');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await gitDeploy.runDeployUpdate();
|
||||||
|
req.session.adminUpdateLog = result.output;
|
||||||
|
req.session.adminUpdateOk = result.ok;
|
||||||
|
req.session.adminUpdateCode = result.code;
|
||||||
|
|
||||||
|
if (result.ok) {
|
||||||
|
return res.redirect('/admin/system?done=1');
|
||||||
|
}
|
||||||
|
return res.redirect('/admin/system?failed=1');
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
@@ -6,8 +6,11 @@ const { requireAuth } = require('../middleware/auth');
|
|||||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||||
const { ROLES } = require('../constants/roles');
|
const { ROLES } = require('../constants/roles');
|
||||||
const { asyncHandler } = require('../utils/asyncHandler');
|
const { asyncHandler } = require('../utils/asyncHandler');
|
||||||
|
const { verifyCaptcha } = require('../services/captcha');
|
||||||
|
const { rateLimit } = require('../middleware/rateLimit');
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
const authRateLimit = rateLimit({ windowMs: 15 * 60 * 1000, max: 30, keyPrefix: 'auth' });
|
||||||
|
|
||||||
router.use((req, res, next) => {
|
router.use((req, res, next) => {
|
||||||
const cart = getCart(req);
|
const cart = getCart(req);
|
||||||
@@ -24,10 +27,20 @@ router.get('/register', requireCookieConsent, (req, res) => {
|
|||||||
router.post(
|
router.post(
|
||||||
'/register',
|
'/register',
|
||||||
requireCookieConsent,
|
requireCookieConsent,
|
||||||
|
authRateLimit,
|
||||||
asyncHandler(async (req, res) => {
|
asyncHandler(async (req, res) => {
|
||||||
const { name, email, password, password2 } = req.body;
|
const { name, email, password, password2 } = req.body;
|
||||||
const values = { name, email };
|
const values = { name, email };
|
||||||
|
|
||||||
|
const captchaCheck = await verifyCaptcha(req);
|
||||||
|
if (!captchaCheck.ok) {
|
||||||
|
return res.status(400).render('register', {
|
||||||
|
title: 'Регистрация',
|
||||||
|
error: captchaCheck.error,
|
||||||
|
values,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (!name?.trim() || !email?.trim() || !password) {
|
if (!name?.trim() || !email?.trim() || !password) {
|
||||||
return res.status(400).render('register', {
|
return res.status(400).render('register', {
|
||||||
title: 'Регистрация',
|
title: 'Регистрация',
|
||||||
@@ -85,11 +98,22 @@ router.get('/login', requireCookieConsent, (req, res) => {
|
|||||||
router.post(
|
router.post(
|
||||||
'/login',
|
'/login',
|
||||||
requireCookieConsent,
|
requireCookieConsent,
|
||||||
|
authRateLimit,
|
||||||
asyncHandler(async (req, res) => {
|
asyncHandler(async (req, res) => {
|
||||||
const { email, password } = req.body;
|
const { email, password } = req.body;
|
||||||
const next = req.body.next || '/';
|
const next = req.body.next || '/';
|
||||||
const values = { email };
|
const values = { email };
|
||||||
|
|
||||||
|
const captchaCheck = await verifyCaptcha(req);
|
||||||
|
if (!captchaCheck.ok) {
|
||||||
|
return res.status(400).render('login', {
|
||||||
|
title: 'Вход',
|
||||||
|
error: captchaCheck.error,
|
||||||
|
next,
|
||||||
|
values,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const { rows } = await query('SELECT * FROM users WHERE email = $1', [
|
const { rows } = await query('SELECT * FROM users WHERE email = $1', [
|
||||||
(email || '').trim().toLowerCase(),
|
(email || '').trim().toLowerCase(),
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ const { getCart, cartCount } = require('../cart');
|
|||||||
const { formatPrice } = require('../db');
|
const { formatPrice } = require('../db');
|
||||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||||
const { asyncHandler } = require('../utils/asyncHandler');
|
const { asyncHandler } = require('../utils/asyncHandler');
|
||||||
|
const { verifyCaptcha } = require('../services/captcha');
|
||||||
const { sendPasswordResetEmail, siteUrl } = require('../services/mail');
|
const { sendPasswordResetEmail, siteUrl } = require('../services/mail');
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
@@ -39,6 +40,16 @@ router.post(
|
|||||||
const genericSuccess =
|
const genericSuccess =
|
||||||
'Если аккаунт с таким email существует, мы отправили ссылку для сброса пароля.';
|
'Если аккаунт с таким email существует, мы отправили ссылку для сброса пароля.';
|
||||||
|
|
||||||
|
const captchaCheck = await verifyCaptcha(req);
|
||||||
|
if (!captchaCheck.ok) {
|
||||||
|
return res.status(400).render('auth/forgot-password', {
|
||||||
|
title: 'Сброс пароля',
|
||||||
|
error: captchaCheck.error,
|
||||||
|
success: null,
|
||||||
|
values,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (!email) {
|
if (!email) {
|
||||||
return res.status(400).render('auth/forgot-password', {
|
return res.status(400).render('auth/forgot-password', {
|
||||||
title: 'Сброс пароля',
|
title: 'Сброс пароля',
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { formatPrice } = require('../db');
|
||||||
|
const { getCart, cartCount, cartItems } = require('../cart');
|
||||||
|
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||||
|
const { asyncHandler } = require('../utils/asyncHandler');
|
||||||
|
const promoService = require('../services/promo');
|
||||||
|
const loyaltyService = require('../services/loyalty');
|
||||||
|
const { buildCartPricing } = require('../services/pricing');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.use(requireCookieConsent);
|
||||||
|
router.use((req, res, next) => {
|
||||||
|
res.locals.cartCount = cartCount(getCart(req));
|
||||||
|
res.locals.formatPrice = formatPrice;
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
|
function cartRedirect(msg, type = 'error') {
|
||||||
|
const param = type === 'success' ? 'promo_ok' : 'promo_error';
|
||||||
|
return `/cart?${param}=${encodeURIComponent(msg)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/cart/promo',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const cart = getCart(req);
|
||||||
|
const items = await cartItems(cart);
|
||||||
|
if (!items.length) {
|
||||||
|
return res.redirect(cartRedirect('Корзина пуста'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const subtotal = items.reduce((s, i) => s + i.line_total, 0);
|
||||||
|
const promo = await promoService.findPromoByCode(req.body.code);
|
||||||
|
const check = promoService.validatePromo(promo, subtotal);
|
||||||
|
if (!check.ok) {
|
||||||
|
delete req.session.appliedPromoCode;
|
||||||
|
return res.redirect(cartRedirect(check.error));
|
||||||
|
}
|
||||||
|
|
||||||
|
req.session.appliedPromoCode = promo.code;
|
||||||
|
res.redirect(cartRedirect(`Промокод ${promo.code} применён`, 'success'));
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post('/cart/promo/remove', (req, res) => {
|
||||||
|
delete req.session.appliedPromoCode;
|
||||||
|
res.redirect(cartRedirect('Промокод удалён', 'success'));
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/cart/loyalty',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
if (!req.session.userId) {
|
||||||
|
return res.redirect('/login?next=/cart');
|
||||||
|
}
|
||||||
|
|
||||||
|
const cart = getCart(req);
|
||||||
|
const items = await cartItems(cart);
|
||||||
|
if (!items.length) {
|
||||||
|
return res.redirect(cartRedirect('Корзина пуста'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const pricing = await buildCartPricing(items, req.session, req.session.userId);
|
||||||
|
const maxPoints = loyaltyService.pointsForDiscount(
|
||||||
|
Math.max(0, pricing.subtotal - pricing.promoDiscount)
|
||||||
|
);
|
||||||
|
const balance = pricing.loyaltyBalance;
|
||||||
|
|
||||||
|
if (req.body.use_all === '1') {
|
||||||
|
req.session.loyaltyPointsToUse = Math.min(balance, maxPoints);
|
||||||
|
} else {
|
||||||
|
const pts = Math.max(0, parseInt(req.body.points, 10) || 0);
|
||||||
|
req.session.loyaltyPointsToUse = Math.min(pts, balance, maxPoints);
|
||||||
|
}
|
||||||
|
|
||||||
|
res.redirect(cartRedirect('Баллы лояльности применены', 'success'));
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post('/cart/loyalty/remove', (req, res) => {
|
||||||
|
delete req.session.loyaltyPointsToUse;
|
||||||
|
res.redirect(cartRedirect('Списание баллов отменено', 'success'));
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { query } = require('../db');
|
||||||
|
const { siteUrl } = require('../services/mail');
|
||||||
|
const { asyncHandler } = require('../utils/asyncHandler');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.get('/robots.txt', (_req, res) => {
|
||||||
|
const base = siteUrl();
|
||||||
|
res.type('text/plain').send(
|
||||||
|
`User-agent: *\nAllow: /\nDisallow: /admin\nDisallow: /account\nSitemap: ${base}/sitemap.xml\n`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
'/sitemap.xml',
|
||||||
|
asyncHandler(async (_req, res) => {
|
||||||
|
const base = siteUrl();
|
||||||
|
const { rows: products } = await query(
|
||||||
|
`SELECT slug, created_at FROM products ORDER BY id`
|
||||||
|
);
|
||||||
|
const urls = [
|
||||||
|
{ loc: `${base}/`, priority: '1.0' },
|
||||||
|
{ loc: `${base}/cart`, priority: '0.5' },
|
||||||
|
];
|
||||||
|
for (const p of products) {
|
||||||
|
urls.push({
|
||||||
|
loc: `${base}/product/${p.slug}`,
|
||||||
|
lastmod: new Date(p.created_at).toISOString().slice(0, 10),
|
||||||
|
priority: '0.8',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const xml = `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||||
|
${urls
|
||||||
|
.map(
|
||||||
|
(u) => ` <url>
|
||||||
|
<loc>${u.loc}</loc>
|
||||||
|
${u.lastmod ? `<lastmod>${u.lastmod}</lastmod>` : ''}
|
||||||
|
<priority>${u.priority}</priority>
|
||||||
|
</url>`
|
||||||
|
)
|
||||||
|
.join('\n')}
|
||||||
|
</urlset>`;
|
||||||
|
res.type('application/xml').send(xml);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
+129
-12
@@ -4,6 +4,12 @@ const { getCart, cartCount, cartItems, cartTotal } = require('../cart');
|
|||||||
const { requireAuth } = require('../middleware/auth');
|
const { requireAuth } = require('../middleware/auth');
|
||||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||||
const { asyncHandler } = require('../utils/asyncHandler');
|
const { asyncHandler } = require('../utils/asyncHandler');
|
||||||
|
const { buildCartPricing } = require('../services/pricing');
|
||||||
|
const productPrice = require('../utils/productPrice');
|
||||||
|
const promoService = require('../services/promo');
|
||||||
|
const loyaltyService = require('../services/loyalty');
|
||||||
|
const recentlyViewed = require('../services/recentlyViewed');
|
||||||
|
const { sendOrderConfirmationEmail } = require('../services/mail');
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -15,24 +21,42 @@ function enrichLocals(req, res) {
|
|||||||
|
|
||||||
router.use((req, res, next) => {
|
router.use((req, res, next) => {
|
||||||
enrichLocals(req, res);
|
enrichLocals(req, res);
|
||||||
|
res.locals.isSaleActive = productPrice.isSaleActive;
|
||||||
|
res.locals.effectivePrice = productPrice.getEffectivePriceCents;
|
||||||
|
res.locals.salePercent = productPrice.salePercent;
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const EFFECTIVE_PRICE_SQL = `CASE
|
||||||
|
WHEN p.sale_price_cents IS NOT NULL
|
||||||
|
AND p.sale_price_cents < p.price_cents
|
||||||
|
AND (p.sale_ends_at IS NULL OR p.sale_ends_at > NOW())
|
||||||
|
THEN p.sale_price_cents
|
||||||
|
ELSE p.price_cents
|
||||||
|
END`;
|
||||||
|
|
||||||
router.get(
|
router.get(
|
||||||
'/',
|
'/',
|
||||||
asyncHandler(async (req, res) => {
|
asyncHandler(async (req, res) => {
|
||||||
const category = req.query.category || '';
|
const category = req.query.category || '';
|
||||||
const q = (req.query.q || '').trim();
|
const q = (req.query.q || '').trim();
|
||||||
|
const sort = req.query.sort || 'name';
|
||||||
|
const saleOnly = req.query.sale === '1';
|
||||||
|
const showAll = req.query.all === '1';
|
||||||
|
|
||||||
let sql = `
|
let sql = `
|
||||||
SELECT p.*, c.name AS category_name, c.slug AS category_slug
|
SELECT p.*, c.name AS category_name, c.slug AS category_slug,
|
||||||
|
(${EFFECTIVE_PRICE_SQL}) AS catalog_price_cents
|
||||||
FROM products p
|
FROM products p
|
||||||
LEFT JOIN categories c ON c.id = p.category_id
|
LEFT JOIN categories c ON c.id = p.category_id
|
||||||
WHERE p.stock > 0
|
WHERE 1=1
|
||||||
`;
|
`;
|
||||||
const params = [];
|
const params = [];
|
||||||
let n = 1;
|
let n = 1;
|
||||||
|
|
||||||
|
if (!showAll) {
|
||||||
|
sql += ' AND p.stock > 0';
|
||||||
|
}
|
||||||
if (category) {
|
if (category) {
|
||||||
sql += ` AND c.slug = $${n++}`;
|
sql += ` AND c.slug = $${n++}`;
|
||||||
params.push(category);
|
params.push(category);
|
||||||
@@ -42,10 +66,23 @@ router.get(
|
|||||||
params.push(`%${q}%`);
|
params.push(`%${q}%`);
|
||||||
n++;
|
n++;
|
||||||
}
|
}
|
||||||
sql += ' ORDER BY p.name';
|
if (saleOnly) {
|
||||||
|
sql += ` AND p.sale_price_cents IS NOT NULL
|
||||||
|
AND p.sale_price_cents < p.price_cents
|
||||||
|
AND (p.sale_ends_at IS NULL OR p.sale_ends_at > NOW())`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const orderMap = {
|
||||||
|
name: 'p.name ASC',
|
||||||
|
price_asc: 'catalog_price_cents ASC, p.name ASC',
|
||||||
|
price_desc: 'catalog_price_cents DESC, p.name ASC',
|
||||||
|
newest: 'p.created_at DESC',
|
||||||
|
};
|
||||||
|
sql += ` ORDER BY ${orderMap[sort] || orderMap.name}`;
|
||||||
|
|
||||||
const { rows: products } = await query(sql, params);
|
const { rows: products } = await query(sql, params);
|
||||||
const { rows: categories } = await query('SELECT * FROM categories ORDER BY name');
|
const { rows: categories } = await query('SELECT * FROM categories ORDER BY name');
|
||||||
|
const recentProducts = await recentlyViewed.loadProducts(query, req.session);
|
||||||
|
|
||||||
res.render('home', {
|
res.render('home', {
|
||||||
title: 'Каталог',
|
title: 'Каталог',
|
||||||
@@ -53,6 +90,10 @@ router.get(
|
|||||||
categories,
|
categories,
|
||||||
activeCategory: category,
|
activeCategory: category,
|
||||||
searchQuery: q,
|
searchQuery: q,
|
||||||
|
sort,
|
||||||
|
saleOnly,
|
||||||
|
showAll,
|
||||||
|
recentProducts,
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
@@ -77,6 +118,8 @@ router.get(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
recentlyViewed.pushProduct(req.session, product.id);
|
||||||
|
|
||||||
let userReservation = null;
|
let userReservation = null;
|
||||||
if (req.session.userId) {
|
if (req.session.userId) {
|
||||||
const { rows: resRows } = await query(
|
const { rows: resRows } = await query(
|
||||||
@@ -109,8 +152,13 @@ router.get(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const metaDescription =
|
||||||
|
(product.description || product.name).replace(/\s+/g, ' ').trim().slice(0, 160) ||
|
||||||
|
product.name;
|
||||||
|
|
||||||
res.render('product', {
|
res.render('product', {
|
||||||
title: product.name,
|
title: product.name,
|
||||||
|
metaDescription,
|
||||||
product,
|
product,
|
||||||
userReservation,
|
userReservation,
|
||||||
error: errorMsg,
|
error: errorMsg,
|
||||||
@@ -128,14 +176,21 @@ router.get(
|
|||||||
asyncHandler(async (req, res) => {
|
asyncHandler(async (req, res) => {
|
||||||
const cart = getCart(req);
|
const cart = getCart(req);
|
||||||
const items = await cartItems(cart);
|
const items = await cartItems(cart);
|
||||||
const total = cartTotal(items);
|
const pricing = await buildCartPricing(items, req.session, req.session.userId);
|
||||||
const errorMsg = req.query.error ? decodeURIComponent(String(req.query.error)) : null;
|
const errorMsg = req.query.error ? decodeURIComponent(String(req.query.error)) : null;
|
||||||
|
const promoOk = req.query.promo_ok ? decodeURIComponent(String(req.query.promo_ok)) : null;
|
||||||
|
const promoErr = req.query.promo_error
|
||||||
|
? decodeURIComponent(String(req.query.promo_error))
|
||||||
|
: null;
|
||||||
|
|
||||||
res.render('cart', {
|
res.render('cart', {
|
||||||
title: 'Корзина',
|
title: 'Корзина',
|
||||||
items,
|
items,
|
||||||
total,
|
pricing,
|
||||||
|
total: pricing.total,
|
||||||
error: errorMsg,
|
error: errorMsg,
|
||||||
|
promoOk,
|
||||||
|
promoErr,
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
@@ -207,10 +262,13 @@ router.get(
|
|||||||
return res.redirect('/cart');
|
return res.redirect('/cart');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const pricing = await buildCartPricing(items, req.session, req.session.userId);
|
||||||
|
|
||||||
res.render('checkout', {
|
res.render('checkout', {
|
||||||
title: 'Оформление заказа',
|
title: 'Оформление заказа',
|
||||||
items,
|
items,
|
||||||
total: cartTotal(items),
|
pricing,
|
||||||
|
total: pricing.total,
|
||||||
error: null,
|
error: null,
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
@@ -227,17 +285,19 @@ router.post(
|
|||||||
return res.redirect('/cart');
|
return res.redirect('/cart');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const pricing = await buildCartPricing(items, req.session, req.session.userId);
|
||||||
const { name, email, phone, address } = req.body;
|
const { name, email, phone, address } = req.body;
|
||||||
|
|
||||||
if (!name?.trim() || !email?.trim() || !address?.trim()) {
|
if (!name?.trim() || !email?.trim() || !address?.trim()) {
|
||||||
return res.status(400).render('checkout', {
|
return res.status(400).render('checkout', {
|
||||||
title: 'Оформление заказа',
|
title: 'Оформление заказа',
|
||||||
items,
|
items,
|
||||||
total: cartTotal(items),
|
pricing,
|
||||||
|
total: pricing.total,
|
||||||
error: 'Заполните имя, email и адрес доставки',
|
error: 'Заполните имя, email и адрес доставки',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const total = cartTotal(items);
|
|
||||||
const client = await pool.connect();
|
const client = await pool.connect();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -253,13 +313,40 @@ router.post(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let promoId = null;
|
||||||
|
if (pricing.promo) {
|
||||||
|
const promoRow = await promoService.findPromoByCode(pricing.promo.code);
|
||||||
|
const check = promoService.validatePromo(
|
||||||
|
promoRow,
|
||||||
|
pricing.subtotal
|
||||||
|
);
|
||||||
|
if (!check.ok) throw new Error(check.error);
|
||||||
|
promoId = promoRow.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pricing.loyaltyPointsUsed > 0) {
|
||||||
|
const bal = await loyaltyService.getBalance(req.session.userId);
|
||||||
|
if (bal < pricing.loyaltyPointsUsed) {
|
||||||
|
throw new Error('Недостаточно баллов лояльности');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const orderResult = await client.query(
|
const orderResult = await client.query(
|
||||||
`INSERT INTO orders (user_id, status, total_cents, customer_name, customer_email, customer_phone, address)
|
`INSERT INTO orders (
|
||||||
VALUES ($1, 'pending', $2, $3, $4, $5, $6)
|
user_id, status, subtotal_cents, discount_cents, total_cents,
|
||||||
|
promo_code_id, loyalty_points_used, loyalty_points_earned,
|
||||||
|
customer_name, customer_email, customer_phone, address
|
||||||
|
)
|
||||||
|
VALUES ($1, 'pending', $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||||
RETURNING id`,
|
RETURNING id`,
|
||||||
[
|
[
|
||||||
req.session.userId,
|
req.session.userId,
|
||||||
total,
|
pricing.subtotal,
|
||||||
|
pricing.promoDiscount + pricing.loyaltyDiscount,
|
||||||
|
pricing.total,
|
||||||
|
promoId,
|
||||||
|
pricing.loyaltyPointsUsed,
|
||||||
|
pricing.pointsEarned,
|
||||||
name.trim(),
|
name.trim(),
|
||||||
email.trim(),
|
email.trim(),
|
||||||
(phone || '').trim(),
|
(phone || '').trim(),
|
||||||
@@ -268,11 +355,24 @@ router.post(
|
|||||||
);
|
);
|
||||||
const orderId = orderResult.rows[0].id;
|
const orderId = orderResult.rows[0].id;
|
||||||
|
|
||||||
|
if (promoId) {
|
||||||
|
await promoService.incrementPromoUse(promoId, client);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pricing.loyaltyPointsUsed > 0 || pricing.pointsEarned > 0) {
|
||||||
|
await loyaltyService.applyLoyaltyOnOrder(
|
||||||
|
client,
|
||||||
|
req.session.userId,
|
||||||
|
pricing.loyaltyPointsUsed,
|
||||||
|
pricing.pointsEarned
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
await client.query(
|
await client.query(
|
||||||
`INSERT INTO order_items (order_id, product_id, quantity, price_cents)
|
`INSERT INTO order_items (order_id, product_id, quantity, price_cents)
|
||||||
VALUES ($1, $2, $3, $4)`,
|
VALUES ($1, $2, $3, $4)`,
|
||||||
[orderId, item.id, item.quantity, item.price_cents]
|
[orderId, item.id, item.quantity, item.effective_price_cents ?? item.price_cents]
|
||||||
);
|
);
|
||||||
await client.query('UPDATE products SET stock = stock - $1 WHERE id = $2', [
|
await client.query('UPDATE products SET stock = stock - $1 WHERE id = $2', [
|
||||||
item.quantity,
|
item.quantity,
|
||||||
@@ -282,6 +382,23 @@ router.post(
|
|||||||
|
|
||||||
await client.query('COMMIT');
|
await client.query('COMMIT');
|
||||||
req.session.cart = {};
|
req.session.cart = {};
|
||||||
|
delete req.session.appliedPromoCode;
|
||||||
|
delete req.session.loyaltyPointsToUse;
|
||||||
|
|
||||||
|
const emailItems = items.map((item) => ({
|
||||||
|
name: item.name,
|
||||||
|
quantity: item.quantity,
|
||||||
|
lineFormatted: formatPrice(
|
||||||
|
(item.effective_price_cents ?? item.price_cents) * item.quantity
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
sendOrderConfirmationEmail(
|
||||||
|
email.trim(),
|
||||||
|
orderId,
|
||||||
|
formatPrice(pricing.total),
|
||||||
|
emailItems
|
||||||
|
).catch((err) => console.error('order email:', err.message));
|
||||||
|
|
||||||
res.redirect(`/orders/${orderId}?success=1`);
|
res.redirect(`/orders/${orderId}?success=1`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await client.query('ROLLBACK');
|
await client.query('ROLLBACK');
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
const { query } = require('./db');
|
||||||
|
|
||||||
|
async function seedPromoCodes() {
|
||||||
|
const { rows } = await query('SELECT COUNT(*)::int AS n FROM promo_codes');
|
||||||
|
if (rows[0].n > 0) return;
|
||||||
|
|
||||||
|
const expires = new Date();
|
||||||
|
expires.setDate(expires.getDate() + 30);
|
||||||
|
|
||||||
|
await query(
|
||||||
|
`INSERT INTO promo_codes (code, description, discount_type, discount_value, expires_at, min_order_cents)
|
||||||
|
VALUES
|
||||||
|
('WELCOME10', 'Скидка 10% новым покупателям', 'percent', 10, $1, 0),
|
||||||
|
('SALE500', 'Скидка 500 ₽ от 3000 ₽', 'fixed', 50000, $1, 300000)`,
|
||||||
|
[expires.toISOString()]
|
||||||
|
);
|
||||||
|
console.log('Демо-промокоды: WELCOME10, SALE500');
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { seedPromoCodes };
|
||||||
@@ -7,8 +7,10 @@ const pgSession = require('connect-pg-simple')(session);
|
|||||||
const { pool, initSchema, checkConnection } = require('./db');
|
const { pool, initSchema, checkConnection } = require('./db');
|
||||||
const { runSeed } = require('./seed');
|
const { runSeed } = require('./seed');
|
||||||
const { seedAdmin } = require('./seed-admin');
|
const { seedAdmin } = require('./seed-admin');
|
||||||
|
const { seedPromoCodes } = require('./seed-promo');
|
||||||
const { loadUser } = require('./middleware/auth');
|
const { loadUser } = require('./middleware/auth');
|
||||||
const { loadCookieConsent } = require('./middleware/cookieConsent');
|
const { loadCookieConsent } = require('./middleware/cookieConsent');
|
||||||
|
const { loadCaptchaLocals, rejectYandexCaptcha } = require('./middleware/captcha');
|
||||||
const healthRoutes = require('./routes/health');
|
const healthRoutes = require('./routes/health');
|
||||||
const shopRoutes = require('./routes/shop');
|
const shopRoutes = require('./routes/shop');
|
||||||
const authRoutes = require('./routes/auth');
|
const authRoutes = require('./routes/auth');
|
||||||
@@ -19,6 +21,9 @@ const passwordResetRoutes = require('./routes/password-reset');
|
|||||||
const reservationsRoutes = require('./routes/reservations');
|
const reservationsRoutes = require('./routes/reservations');
|
||||||
const passkeyRoutes = require('./routes/passkey');
|
const passkeyRoutes = require('./routes/passkey');
|
||||||
const stockAlertsRoutes = require('./routes/stock-alerts');
|
const stockAlertsRoutes = require('./routes/stock-alerts');
|
||||||
|
const promoRoutes = require('./routes/promo');
|
||||||
|
const seoRoutes = require('./routes/seo');
|
||||||
|
const { securityHeaders } = require('./middleware/securityHeaders');
|
||||||
|
|
||||||
const PORT = process.env.PORT || 3000;
|
const PORT = process.env.PORT || 3000;
|
||||||
const HOST = process.env.HOST || '0.0.0.0';
|
const HOST = process.env.HOST || '0.0.0.0';
|
||||||
@@ -29,6 +34,7 @@ async function start() {
|
|||||||
await initSchema();
|
await initSchema();
|
||||||
await runSeed();
|
await runSeed();
|
||||||
await seedAdmin();
|
await seedAdmin();
|
||||||
|
await seedPromoCodes();
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
@@ -40,6 +46,8 @@ async function start() {
|
|||||||
app.set('views', path.join(__dirname, 'views'));
|
app.set('views', path.join(__dirname, 'views'));
|
||||||
|
|
||||||
app.use(healthRoutes);
|
app.use(healthRoutes);
|
||||||
|
app.use(securityHeaders);
|
||||||
|
app.use(seoRoutes);
|
||||||
app.use(express.static(path.join(__dirname, 'public')));
|
app.use(express.static(path.join(__dirname, 'public')));
|
||||||
app.use(express.urlencoded({ extended: true }));
|
app.use(express.urlencoded({ extended: true }));
|
||||||
app.use(express.json({ limit: '64kb' }));
|
app.use(express.json({ limit: '64kb' }));
|
||||||
@@ -65,11 +73,14 @@ async function start() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
app.use(loadCookieConsent);
|
app.use(loadCookieConsent);
|
||||||
|
app.use(loadCaptchaLocals);
|
||||||
|
app.use(rejectYandexCaptcha);
|
||||||
app.use(loadUser);
|
app.use(loadUser);
|
||||||
app.use('/cookies', cookiesRoutes);
|
app.use('/cookies', cookiesRoutes);
|
||||||
app.use('/', passwordResetRoutes);
|
app.use('/', passwordResetRoutes);
|
||||||
app.use('/reservations', reservationsRoutes);
|
app.use('/reservations', reservationsRoutes);
|
||||||
app.use('/', stockAlertsRoutes);
|
app.use('/', stockAlertsRoutes);
|
||||||
|
app.use('/', promoRoutes);
|
||||||
app.use('/', shopRoutes);
|
app.use('/', shopRoutes);
|
||||||
app.use('/', authRoutes);
|
app.use('/', authRoutes);
|
||||||
app.use('/webauthn', passkeyRoutes);
|
app.use('/webauthn', passkeyRoutes);
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
const YANDEX_BLOCKED_MSG =
|
||||||
|
'Яндекс SmartCaptcha (японский сервис) заблокирован администратором сайта. Используйте проверку Google или Cloudflare.';
|
||||||
|
|
||||||
|
function clientIp(req) {
|
||||||
|
return (
|
||||||
|
req.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
|
||||||
|
req.socket?.remoteAddress ||
|
||||||
|
''
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isYandexCaptchaAttempt(req) {
|
||||||
|
const b = req.body || {};
|
||||||
|
return Boolean(
|
||||||
|
b['smart-token'] ||
|
||||||
|
b.smartcaptcha ||
|
||||||
|
b.yandex_captcha ||
|
||||||
|
b['yandex-token'] ||
|
||||||
|
(typeof b.captcha_provider === 'string' && b.captcha_provider.toLowerCase() === 'yandex')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCaptchaConfig() {
|
||||||
|
const raw = (process.env.CAPTCHA_PROVIDER || 'google').toLowerCase().trim();
|
||||||
|
|
||||||
|
if (raw === 'yandex' || raw === 'yandex-smartcaptcha') {
|
||||||
|
return {
|
||||||
|
enabled: true,
|
||||||
|
provider: 'yandex',
|
||||||
|
blocked: true,
|
||||||
|
siteKey: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.env.CAPTCHA_ENABLED === '0') {
|
||||||
|
return { enabled: false, provider: null, blocked: false, siteKey: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (raw === 'cloudflare' || raw === 'turnstile') {
|
||||||
|
const siteKey = process.env.TURNSTILE_SITE_KEY || '';
|
||||||
|
const secret = process.env.TURNSTILE_SECRET_KEY || '';
|
||||||
|
if (!siteKey || !secret) {
|
||||||
|
return { enabled: false, provider: 'cloudflare', blocked: false, siteKey: null };
|
||||||
|
}
|
||||||
|
return { enabled: true, provider: 'cloudflare', blocked: false, siteKey };
|
||||||
|
}
|
||||||
|
|
||||||
|
const siteKey = process.env.RECAPTCHA_SITE_KEY || '';
|
||||||
|
const secret = process.env.RECAPTCHA_SECRET_KEY || '';
|
||||||
|
if (!siteKey || !secret) {
|
||||||
|
return { enabled: false, provider: 'google', blocked: false, siteKey: null };
|
||||||
|
}
|
||||||
|
return { enabled: true, provider: 'google', blocked: false, siteKey };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verifyGoogle(token, secret, ip) {
|
||||||
|
const params = new URLSearchParams({ secret, response: token });
|
||||||
|
if (ip) params.set('remoteip', ip);
|
||||||
|
const res = await fetch('https://www.google.com/recaptcha/api/siteverify', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
|
body: params.toString(),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
return Boolean(data.success);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verifyTurnstile(token, secret, ip) {
|
||||||
|
const params = new URLSearchParams({ secret, response: token });
|
||||||
|
if (ip) params.set('remoteip', ip);
|
||||||
|
const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
|
body: params.toString(),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
return Boolean(data.success);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verifyCaptcha(req) {
|
||||||
|
if (isYandexCaptchaAttempt(req)) {
|
||||||
|
return { ok: false, error: YANDEX_BLOCKED_MSG };
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = getCaptchaConfig();
|
||||||
|
|
||||||
|
if (config.blocked) {
|
||||||
|
return { ok: false, error: YANDEX_BLOCKED_MSG };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!config.enabled) {
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const ip = clientIp(req);
|
||||||
|
const secret =
|
||||||
|
config.provider === 'cloudflare'
|
||||||
|
? process.env.TURNSTILE_SECRET_KEY
|
||||||
|
: process.env.RECAPTCHA_SECRET_KEY;
|
||||||
|
|
||||||
|
const token =
|
||||||
|
config.provider === 'cloudflare'
|
||||||
|
? req.body?.['cf-turnstile-response']
|
||||||
|
: req.body?.['g-recaptcha-response'];
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return { ok: false, error: 'Подтвердите, что вы не робот (капча)' };
|
||||||
|
}
|
||||||
|
|
||||||
|
let valid = false;
|
||||||
|
if (config.provider === 'cloudflare') {
|
||||||
|
valid = await verifyTurnstile(token, secret, ip);
|
||||||
|
} else {
|
||||||
|
valid = await verifyGoogle(token, secret, ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!valid) {
|
||||||
|
return { ok: false, error: 'Проверка капчи не пройдена. Попробуйте снова.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
YANDEX_BLOCKED_MSG,
|
||||||
|
getCaptchaConfig,
|
||||||
|
verifyCaptcha,
|
||||||
|
isYandexCaptchaAttempt,
|
||||||
|
};
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
const { execFile, spawn } = require('child_process');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { promisify } = require('util');
|
||||||
|
|
||||||
|
const execFileAsync = promisify(execFile);
|
||||||
|
|
||||||
|
function resolveShopRoot() {
|
||||||
|
const candidates = [
|
||||||
|
process.env.SHOP_ROOT,
|
||||||
|
path.resolve(__dirname, '../..'),
|
||||||
|
'/opt/shop',
|
||||||
|
].filter(Boolean);
|
||||||
|
|
||||||
|
for (const dir of candidates) {
|
||||||
|
const resolved = path.resolve(dir);
|
||||||
|
if (fs.existsSync(path.join(resolved, 'package.json'))) {
|
||||||
|
return resolved;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isUpdateEnabled() {
|
||||||
|
if (process.env.ADMIN_UPDATE_ENABLED === '0') return false;
|
||||||
|
const root = resolveShopRoot();
|
||||||
|
if (!root) return false;
|
||||||
|
if (!fs.existsSync(path.join(root, '.git'))) return false;
|
||||||
|
if (process.platform === 'win32') return false;
|
||||||
|
return fs.existsSync(path.join(root, 'scripts', 'admin-web-update.sh'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function gitEnv(root) {
|
||||||
|
const resolved = path.resolve(root);
|
||||||
|
return {
|
||||||
|
...process.env,
|
||||||
|
GIT_TERMINAL_PROMPT: '0',
|
||||||
|
GIT_CONFIG_COUNT: '1',
|
||||||
|
GIT_CONFIG_KEY_0: 'safe.directory',
|
||||||
|
GIT_CONFIG_VALUE_0: resolved,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getRepoOwner(root) {
|
||||||
|
if (process.env.SHOP_GIT_USER) {
|
||||||
|
return process.env.SHOP_GIT_USER.trim();
|
||||||
|
}
|
||||||
|
if (process.platform === 'win32') return null;
|
||||||
|
const gitPath = path.join(root, '.git');
|
||||||
|
try {
|
||||||
|
const target = fs.statSync(gitPath).isDirectory() ? gitPath : root;
|
||||||
|
const { stdout } = await execFileAsync('stat', ['-c', '%U', target], { timeout: 5000 });
|
||||||
|
const user = stdout.trim();
|
||||||
|
return user || null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureSafeDirectory(root, user) {
|
||||||
|
const resolved = path.resolve(root);
|
||||||
|
const targets = [{ home: process.env.HOME || '/var/www' }];
|
||||||
|
if (user) {
|
||||||
|
try {
|
||||||
|
const { stdout } = await execFileAsync('getent', ['passwd', user], { timeout: 5000 });
|
||||||
|
const home = stdout.split(':')[5];
|
||||||
|
if (home) targets.push({ home });
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const { home } of targets) {
|
||||||
|
try {
|
||||||
|
await execFileAsync('git', ['config', '--global', '--add', 'safe.directory', resolved], {
|
||||||
|
timeout: 15000,
|
||||||
|
env: { ...process.env, HOME: home },
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function execGit(args, cwd, runAs) {
|
||||||
|
const root = path.resolve(cwd);
|
||||||
|
const gitArgs = ['-c', `safe.directory=${root}`, ...args];
|
||||||
|
const opts = {
|
||||||
|
cwd: root,
|
||||||
|
maxBuffer: 1024 * 1024,
|
||||||
|
timeout: 120000,
|
||||||
|
env: gitEnv(root),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (runAs && process.env.ADMIN_UPDATE_USE_SUDO === '1') {
|
||||||
|
const { stdout, stderr } = await execFileAsync('sudo', ['-n', '-u', runAs, 'git', ...gitArgs], opts);
|
||||||
|
return `${stdout}${stderr}`.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
const { stdout, stderr } = await execFileAsync('git', gitArgs, opts);
|
||||||
|
return `${stdout}${stderr}`.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function gitCmd(args, cwd, { needsWrite = false } = {}) {
|
||||||
|
const root = path.resolve(cwd);
|
||||||
|
const owner = await getRepoOwner(root);
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await execGit(args, root, null);
|
||||||
|
} catch (err) {
|
||||||
|
const msg = err.message || '';
|
||||||
|
const denied = /permission denied|EACCES|FETCH_HEAD/i.test(msg);
|
||||||
|
if ((needsWrite || denied) && owner) {
|
||||||
|
await ensureSafeDirectory(root, owner);
|
||||||
|
return execGit(args, root, owner);
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сравнение с origin/main через ls-remote + merge-base (без fetch, без записи в .git).
|
||||||
|
*/
|
||||||
|
async function getRemoteSyncStatus(root) {
|
||||||
|
const localHead = (await gitCmd(['rev-parse', 'HEAD'], root)).split('\n')[0].trim();
|
||||||
|
const remoteOut = await gitCmd(['ls-remote', 'origin', 'refs/heads/main'], root);
|
||||||
|
const remoteSha = remoteOut.split(/\s+/)[0]?.trim();
|
||||||
|
if (!remoteSha) {
|
||||||
|
throw new Error('Не найден refs/heads/main на origin');
|
||||||
|
}
|
||||||
|
|
||||||
|
const remoteShort = (
|
||||||
|
await gitCmd(['rev-parse', '--short', remoteSha], root)
|
||||||
|
).split('\n')[0].trim();
|
||||||
|
|
||||||
|
if (remoteSha === localHead) {
|
||||||
|
return { behind: 0, ahead: 0, diverged: false, remoteShort, remoteSha };
|
||||||
|
}
|
||||||
|
|
||||||
|
let mergeBase;
|
||||||
|
try {
|
||||||
|
mergeBase = (await gitCmd(['merge-base', localHead, remoteSha], root)).split('\n')[0].trim();
|
||||||
|
} catch {
|
||||||
|
throw new Error(
|
||||||
|
'Не удалось сравнить с origin/main (нет общего предка). Выполните на сервере: git fetch && git reset --hard origin/main'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mergeBase) {
|
||||||
|
throw new Error('Нет общего предка с origin/main');
|
||||||
|
}
|
||||||
|
|
||||||
|
let behind = 0;
|
||||||
|
let ahead = 0;
|
||||||
|
|
||||||
|
if (mergeBase !== remoteSha) {
|
||||||
|
const behindStr = await gitCmd(['rev-list', '--count', `${mergeBase}..${remoteSha}`], root);
|
||||||
|
behind = parseInt(behindStr, 10) || 0;
|
||||||
|
}
|
||||||
|
if (mergeBase !== localHead) {
|
||||||
|
const aheadStr = await gitCmd(['rev-list', '--count', `${mergeBase}..${localHead}`], root);
|
||||||
|
ahead = parseInt(aheadStr, 10) || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
behind,
|
||||||
|
ahead,
|
||||||
|
diverged: behind > 0 && ahead > 0,
|
||||||
|
remoteShort,
|
||||||
|
remoteSha,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getGitInfo({ fetchRemote = false } = {}) {
|
||||||
|
const root = resolveShopRoot();
|
||||||
|
const pkg = root ? JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) : null;
|
||||||
|
const repoOwner = root ? await getRepoOwner(root) : null;
|
||||||
|
|
||||||
|
if (!root || !fs.existsSync(path.join(root, '.git'))) {
|
||||||
|
return {
|
||||||
|
available: false,
|
||||||
|
packageVersion: pkg?.version || null,
|
||||||
|
shopRoot: root,
|
||||||
|
reason: 'Каталог не является git-репозиторием. Задайте SHOP_ROOT в .env.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const info = {
|
||||||
|
available: true,
|
||||||
|
shopRoot: root,
|
||||||
|
repoOwner,
|
||||||
|
packageVersion: pkg?.version || null,
|
||||||
|
branch: null,
|
||||||
|
commit: null,
|
||||||
|
commitShort: null,
|
||||||
|
commitSubject: null,
|
||||||
|
commitDate: null,
|
||||||
|
dirty: false,
|
||||||
|
dirtyHint: null,
|
||||||
|
behind: null,
|
||||||
|
ahead: null,
|
||||||
|
diverged: false,
|
||||||
|
remoteShort: null,
|
||||||
|
updateEnabled: isUpdateEnabled(),
|
||||||
|
platform: process.platform,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
await ensureSafeDirectory(root, repoOwner);
|
||||||
|
info.branch = await gitCmd(['branch', '--show-current'], root);
|
||||||
|
if (!info.branch) {
|
||||||
|
info.branch = '(detached)';
|
||||||
|
info.commitShort = await gitCmd(['rev-parse', '--short', 'HEAD'], root);
|
||||||
|
}
|
||||||
|
info.commit = await gitCmd(['rev-parse', 'HEAD'], root);
|
||||||
|
info.commitShort = info.commitShort || (await gitCmd(['rev-parse', '--short', 'HEAD'], root));
|
||||||
|
info.commitSubject = await gitCmd(['log', '-1', '--pretty=%s'], root);
|
||||||
|
info.commitDate = await gitCmd(['log', '-1', '--pretty=%ci'], root);
|
||||||
|
try {
|
||||||
|
const status = await gitCmd(['status', '--porcelain'], root);
|
||||||
|
info.dirty = status.length > 0;
|
||||||
|
if (info.dirty) {
|
||||||
|
info.dirtyHint =
|
||||||
|
'На сервере есть локальные изменения. Обновление может их перезаписать; при ошибке выполните git stash или git reset --hard с машины администратора.';
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
info.dirty = null;
|
||||||
|
info.dirtyHint = 'Не удалось прочитать статус (права на .git).';
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
info.available = false;
|
||||||
|
info.reason = err.message;
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fetchRemote) {
|
||||||
|
try {
|
||||||
|
const sync = await getRemoteSyncStatus(root);
|
||||||
|
info.behind = sync.behind;
|
||||||
|
info.ahead = sync.ahead;
|
||||||
|
info.diverged = sync.diverged;
|
||||||
|
info.remoteShort = sync.remoteShort;
|
||||||
|
} catch (err) {
|
||||||
|
info.fetchError = err.message;
|
||||||
|
if (repoOwner) {
|
||||||
|
info.fetchError += ` Владелец репозитория: ${repoOwner}. Задайте SHOP_GIT_USER=${repoOwner} и ADMIN_UPDATE_USE_SUDO=1 в .env.`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
function runDeployUpdate() {
|
||||||
|
const root = resolveShopRoot();
|
||||||
|
const scriptPath = path.join(root, 'scripts', 'admin-web-update.sh');
|
||||||
|
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const useSudo = process.env.ADMIN_UPDATE_USE_SUDO === '1';
|
||||||
|
const cmd = useSudo ? 'sudo' : 'bash';
|
||||||
|
const args = useSudo ? ['-n', scriptPath] : [scriptPath];
|
||||||
|
|
||||||
|
const child = spawn(cmd, args, {
|
||||||
|
cwd: root,
|
||||||
|
env: { ...gitEnv(root), SHOP_ROOT: root },
|
||||||
|
timeout: 300000,
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = '';
|
||||||
|
child.stdout.on('data', (chunk) => {
|
||||||
|
output += chunk.toString();
|
||||||
|
});
|
||||||
|
child.stderr.on('data', (chunk) => {
|
||||||
|
output += chunk.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('error', (err) => {
|
||||||
|
resolve({
|
||||||
|
ok: false,
|
||||||
|
code: -1,
|
||||||
|
output: `${output}\n${err.message}`.trim(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('close', (code) => {
|
||||||
|
resolve({
|
||||||
|
ok: code === 0,
|
||||||
|
code: code ?? 1,
|
||||||
|
output: output.trim() || '(нет вывода)',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
resolveShopRoot,
|
||||||
|
isUpdateEnabled,
|
||||||
|
getGitInfo,
|
||||||
|
runDeployUpdate,
|
||||||
|
getRepoOwner,
|
||||||
|
};
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
const { query } = require('../db');
|
||||||
|
|
||||||
|
/** Баллов за каждые 100 ₽ subtotal после скидок */
|
||||||
|
const EARN_PER_100_RUB = 10;
|
||||||
|
/** 1 балл = 1 копейка скидки */
|
||||||
|
const POINT_VALUE_CENTS = 1;
|
||||||
|
|
||||||
|
async function getBalance(userId) {
|
||||||
|
const { rows } = await query('SELECT loyalty_points FROM users WHERE id = $1', [
|
||||||
|
userId,
|
||||||
|
]);
|
||||||
|
return rows[0]?.loyalty_points ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function calcEarnedPoints(payableCents) {
|
||||||
|
if (payableCents <= 0) return 0;
|
||||||
|
return Math.floor((payableCents / 10000) * EARN_PER_100_RUB);
|
||||||
|
}
|
||||||
|
|
||||||
|
function calcLoyaltyDiscountCents(pointsToUse, balance, maxCents) {
|
||||||
|
const use = Math.min(
|
||||||
|
Math.max(0, parseInt(pointsToUse, 10) || 0),
|
||||||
|
balance,
|
||||||
|
maxCents
|
||||||
|
);
|
||||||
|
return use * POINT_VALUE_CENTS;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pointsForDiscount(discountCents) {
|
||||||
|
return Math.floor(discountCents / POINT_VALUE_CENTS);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyLoyaltyOnOrder(client, userId, pointsUsed, pointsEarned) {
|
||||||
|
await client.query(
|
||||||
|
`UPDATE users SET loyalty_points = loyalty_points - $1 + $2 WHERE id = $3`,
|
||||||
|
[pointsUsed, pointsEarned, userId]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
EARN_PER_100_RUB,
|
||||||
|
POINT_VALUE_CENTS,
|
||||||
|
getBalance,
|
||||||
|
calcEarnedPoints,
|
||||||
|
calcLoyaltyDiscountCents,
|
||||||
|
pointsForDiscount,
|
||||||
|
applyLoyaltyOnOrder,
|
||||||
|
};
|
||||||
@@ -68,6 +68,28 @@ async function sendReservationEmail(to, productName, quantity, expiresAt) {
|
|||||||
return sendMail({ to, subject, text, html });
|
return sendMail({ to, subject, text, html });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function sendOrderConfirmationEmail(to, orderId, totalFormatted, items) {
|
||||||
|
const orderUrl = `${siteUrl()}/orders/${orderId}`;
|
||||||
|
const subject = `Заказ #${orderId} оформлен — Shop`;
|
||||||
|
const lines = items
|
||||||
|
.map((i) => `• ${i.name} × ${i.quantity} — ${i.lineFormatted}`)
|
||||||
|
.join('\n');
|
||||||
|
const text = `Спасибо за заказ #${orderId}!\n\n${lines}\n\nИтого: ${totalFormatted}\n\nСтатус: ${orderUrl}`;
|
||||||
|
const htmlItems = items
|
||||||
|
.map(
|
||||||
|
(i) =>
|
||||||
|
`<li>${i.name} × ${i.quantity} — <strong>${i.lineFormatted}</strong></li>`
|
||||||
|
)
|
||||||
|
.join('');
|
||||||
|
const html = `
|
||||||
|
<p>Спасибо за покупку! Заказ <strong>#${orderId}</strong> принят.</p>
|
||||||
|
<ul>${htmlItems}</ul>
|
||||||
|
<p><strong>Итого: ${totalFormatted}</strong></p>
|
||||||
|
<p><a href="${orderUrl}">Открыть заказ в личном кабинете</a></p>
|
||||||
|
`;
|
||||||
|
return sendMail({ to, subject, text, html });
|
||||||
|
}
|
||||||
|
|
||||||
async function sendStockAvailableEmail(to, productName, productUrl) {
|
async function sendStockAvailableEmail(to, productName, productUrl) {
|
||||||
const subject = `Снова в наличии: ${productName}`;
|
const subject = `Снова в наличии: ${productName}`;
|
||||||
const text = `Товар «${productName}» снова в наличии.\n\nПерейти: ${productUrl}`;
|
const text = `Товар «${productName}» снова в наличии.\n\nПерейти: ${productUrl}`;
|
||||||
@@ -85,5 +107,6 @@ module.exports = {
|
|||||||
sendPasswordResetEmail,
|
sendPasswordResetEmail,
|
||||||
sendReservationEmail,
|
sendReservationEmail,
|
||||||
sendStockAvailableEmail,
|
sendStockAvailableEmail,
|
||||||
|
sendOrderConfirmationEmail,
|
||||||
siteUrl,
|
siteUrl,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
const promoService = require('./promo');
|
||||||
|
const loyaltyService = require('./loyalty');
|
||||||
|
|
||||||
|
async function buildCartPricing(items, session, userId) {
|
||||||
|
const subtotal = items.reduce((s, i) => s + i.line_total, 0);
|
||||||
|
|
||||||
|
let promo = null;
|
||||||
|
let promoDiscount = 0;
|
||||||
|
let promoError = null;
|
||||||
|
|
||||||
|
if (session.appliedPromoCode) {
|
||||||
|
promo = await promoService.findPromoByCode(session.appliedPromoCode);
|
||||||
|
const check = promoService.validatePromo(promo, subtotal);
|
||||||
|
if (!check.ok) {
|
||||||
|
promoError = check.error;
|
||||||
|
promo = null;
|
||||||
|
delete session.appliedPromoCode;
|
||||||
|
} else {
|
||||||
|
promoDiscount = promoService.calcPromoDiscountCents(promo, subtotal);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const afterPromo = Math.max(0, subtotal - promoDiscount);
|
||||||
|
|
||||||
|
let loyaltyBalance = 0;
|
||||||
|
let loyaltyDiscount = 0;
|
||||||
|
let loyaltyPointsUsed = 0;
|
||||||
|
|
||||||
|
if (userId) {
|
||||||
|
loyaltyBalance = await loyaltyService.getBalance(userId);
|
||||||
|
const requested = session.loyaltyPointsToUse ?? 0;
|
||||||
|
loyaltyDiscount = loyaltyService.calcLoyaltyDiscountCents(
|
||||||
|
requested,
|
||||||
|
loyaltyBalance,
|
||||||
|
afterPromo
|
||||||
|
);
|
||||||
|
loyaltyPointsUsed = loyaltyService.pointsForDiscount(loyaltyDiscount);
|
||||||
|
}
|
||||||
|
|
||||||
|
const total = Math.max(0, afterPromo - loyaltyDiscount);
|
||||||
|
const pointsEarned =
|
||||||
|
userId && total > 0 ? loyaltyService.calcEarnedPoints(total) : 0;
|
||||||
|
|
||||||
|
return {
|
||||||
|
subtotal,
|
||||||
|
promoDiscount,
|
||||||
|
loyaltyDiscount,
|
||||||
|
loyaltyPointsUsed,
|
||||||
|
loyaltyPointsUsedDisplay: loyaltyPointsUsed,
|
||||||
|
loyaltyBalance,
|
||||||
|
pointsEarned,
|
||||||
|
total,
|
||||||
|
promo: promo
|
||||||
|
? {
|
||||||
|
code: promo.code,
|
||||||
|
description: promo.description,
|
||||||
|
discount_type: promo.discount_type,
|
||||||
|
discount_value: promo.discount_value,
|
||||||
|
expires_at: promo.expires_at,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
promoError,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { buildCartPricing };
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
const { query } = require('../db');
|
||||||
|
|
||||||
|
function normalizeCode(code) {
|
||||||
|
return String(code || '')
|
||||||
|
.trim()
|
||||||
|
.toUpperCase()
|
||||||
|
.replace(/\s+/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function findPromoByCode(code) {
|
||||||
|
const normalized = normalizeCode(code);
|
||||||
|
if (!normalized) return null;
|
||||||
|
|
||||||
|
const { rows } = await query(
|
||||||
|
`SELECT * FROM promo_codes WHERE UPPER(code) = $1 AND active = true`,
|
||||||
|
[normalized]
|
||||||
|
);
|
||||||
|
return rows[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validatePromo(promo, subtotalCents) {
|
||||||
|
if (!promo) return { ok: false, error: 'Промокод не найден' };
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
if (new Date(promo.starts_at) > now) {
|
||||||
|
return { ok: false, error: 'Промокод ещё не действует' };
|
||||||
|
}
|
||||||
|
if (new Date(promo.expires_at) <= now) {
|
||||||
|
return { ok: false, error: 'Срок действия промокода истёк' };
|
||||||
|
}
|
||||||
|
if (promo.max_uses != null && promo.use_count >= promo.max_uses) {
|
||||||
|
return { ok: false, error: 'Лимит использований промокода исчерпан' };
|
||||||
|
}
|
||||||
|
if (subtotalCents < promo.min_order_cents) {
|
||||||
|
const min = (promo.min_order_cents / 100).toFixed(0);
|
||||||
|
return { ok: false, error: `Минимальная сумма заказа ${min} ₽` };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
function calcPromoDiscountCents(promo, subtotalCents) {
|
||||||
|
if (!promo) return 0;
|
||||||
|
if (promo.discount_type === 'percent') {
|
||||||
|
const pct = Math.min(100, Math.max(1, promo.discount_value));
|
||||||
|
return Math.floor((subtotalCents * pct) / 100);
|
||||||
|
}
|
||||||
|
return Math.min(subtotalCents, promo.discount_value);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function incrementPromoUse(promoId, client) {
|
||||||
|
const q = client ? client.query.bind(client) : query;
|
||||||
|
await q('UPDATE promo_codes SET use_count = use_count + 1 WHERE id = $1', [promoId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
normalizeCode,
|
||||||
|
findPromoByCode,
|
||||||
|
validatePromo,
|
||||||
|
calcPromoDiscountCents,
|
||||||
|
incrementPromoUse,
|
||||||
|
};
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
const MAX = 8;
|
||||||
|
|
||||||
|
function getList(session) {
|
||||||
|
if (!session.recentlyViewed || !Array.isArray(session.recentlyViewed)) {
|
||||||
|
session.recentlyViewed = [];
|
||||||
|
}
|
||||||
|
return session.recentlyViewed;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pushProduct(session, productId) {
|
||||||
|
const id = parseInt(productId, 10);
|
||||||
|
if (!id) return;
|
||||||
|
const list = getList(session).filter((x) => x !== id);
|
||||||
|
list.unshift(id);
|
||||||
|
session.recentlyViewed = list.slice(0, MAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadProducts(query, session) {
|
||||||
|
const ids = getList(session);
|
||||||
|
if (!ids.length) return [];
|
||||||
|
const placeholders = ids.map((_, i) => `$${i + 1}`).join(',');
|
||||||
|
const { rows } = await query(
|
||||||
|
`SELECT p.*, c.name AS category_name, c.slug AS category_slug
|
||||||
|
FROM products p
|
||||||
|
LEFT JOIN categories c ON c.id = p.category_id
|
||||||
|
WHERE p.id IN (${placeholders})`,
|
||||||
|
ids
|
||||||
|
);
|
||||||
|
const byId = new Map(rows.map((p) => [p.id, p]));
|
||||||
|
return ids.map((id) => byId.get(id)).filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { pushProduct, loadProducts, MAX };
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
function isSaleActive(product) {
|
||||||
|
if (product.sale_price_cents == null) return false;
|
||||||
|
if (product.sale_price_cents >= product.price_cents) return false;
|
||||||
|
if (product.sale_ends_at && new Date(product.sale_ends_at) <= new Date()) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getEffectivePriceCents(product) {
|
||||||
|
return isSaleActive(product) ? product.sale_price_cents : product.price_cents;
|
||||||
|
}
|
||||||
|
|
||||||
|
function salePercent(product) {
|
||||||
|
if (!isSaleActive(product) || !product.price_cents) return 0;
|
||||||
|
return Math.round(
|
||||||
|
((product.price_cents - product.sale_price_cents) / product.price_cents) * 100
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { isSaleActive, getEffectivePriceCents, salePercent };
|
||||||
@@ -12,6 +12,7 @@
|
|||||||
<a href="/account?tab=password" class="account-tabs__link <%= activeTab === 'password' ? 'account-tabs__link--active' : '' %>">Смена пароля</a>
|
<a href="/account?tab=password" class="account-tabs__link <%= activeTab === 'password' ? 'account-tabs__link--active' : '' %>">Смена пароля</a>
|
||||||
<a href="/account?tab=passkey" class="account-tabs__link <%= activeTab === 'passkey' ? 'account-tabs__link--active' : '' %>">Passkey</a>
|
<a href="/account?tab=passkey" class="account-tabs__link <%= activeTab === 'passkey' ? 'account-tabs__link--active' : '' %>">Passkey</a>
|
||||||
<a href="/account?tab=reservations" class="account-tabs__link <%= activeTab === 'reservations' ? 'account-tabs__link--active' : '' %>">Бронирования</a>
|
<a href="/account?tab=reservations" class="account-tabs__link <%= activeTab === 'reservations' ? 'account-tabs__link--active' : '' %>">Бронирования</a>
|
||||||
|
<a href="/account?tab=orders" class="account-tabs__link <%= activeTab === 'orders' ? 'account-tabs__link--active' : '' %>">Заказы</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<% if (activeTab === 'profile') { %>
|
<% if (activeTab === 'profile') { %>
|
||||||
@@ -29,6 +30,8 @@
|
|||||||
<dd><%= new Date(user.created_at).toLocaleString('ru-RU') %></dd>
|
<dd><%= new Date(user.created_at).toLocaleString('ru-RU') %></dd>
|
||||||
<dt>Заказов</dt>
|
<dt>Заказов</dt>
|
||||||
<dd><%= orderCount %></dd>
|
<dd><%= orderCount %></dd>
|
||||||
|
<dt>Баллы лояльности</dt>
|
||||||
|
<dd><strong><%= user.loyalty_points || 0 %></strong> <span class="muted">(1 балл = 1 коп. скидки)</span></dd>
|
||||||
</dl>
|
</dl>
|
||||||
<div class="account-actions">
|
<div class="account-actions">
|
||||||
<a href="/orders" class="btn btn--primary">Мои заказы</a>
|
<a href="/orders" class="btn btn--primary">Мои заказы</a>
|
||||||
@@ -69,6 +72,40 @@
|
|||||||
</section>
|
</section>
|
||||||
<% } %>
|
<% } %>
|
||||||
|
|
||||||
|
<% if (activeTab === 'orders') { %>
|
||||||
|
<section class="card account-section">
|
||||||
|
<h2>Последние заказы</h2>
|
||||||
|
<% if (!recentOrders.length) { %>
|
||||||
|
<p class="muted">Заказов пока нет. <a href="/">Перейти в каталог</a></p>
|
||||||
|
<% } else { %>
|
||||||
|
<table class="cart-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>№</th>
|
||||||
|
<th>Дата</th>
|
||||||
|
<th>Статус</th>
|
||||||
|
<th>Сумма</th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% const statusLabels = { pending: 'Ожидает', paid: 'Оплачен', shipped: 'Отправлен', cancelled: 'Отменён' }; %>
|
||||||
|
<% recentOrders.forEach(o => { %>
|
||||||
|
<tr>
|
||||||
|
<td>#<%= o.id %></td>
|
||||||
|
<td><%= new Date(o.created_at).toLocaleString('ru-RU') %></td>
|
||||||
|
<td><span class="status status--<%= o.status %>"><%= statusLabels[o.status] || o.status %></span></td>
|
||||||
|
<td><%= formatPrice(o.total_cents) %></td>
|
||||||
|
<td><a href="/orders/<%= o.id %>">Подробнее</a></td>
|
||||||
|
</tr>
|
||||||
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<p class="account-actions"><a href="/orders" class="btn btn--ghost">Все заказы</a></p>
|
||||||
|
<% } %>
|
||||||
|
</section>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
<% if (activeTab === 'reservations') { %>
|
<% if (activeTab === 'reservations') { %>
|
||||||
<section class="card account-section">
|
<section class="card account-section">
|
||||||
<h2>Мои бронирования</h2>
|
<h2>Мои бронирования</h2>
|
||||||
|
|||||||
@@ -2,16 +2,15 @@
|
|||||||
|
|
||||||
<div class="admin-header">
|
<div class="admin-header">
|
||||||
<h1>Админ-панель</h1>
|
<h1>Админ-панель</h1>
|
||||||
<nav class="admin-nav">
|
<%- include('../partials/admin-nav', { adminNav: 'dashboard' }) %>
|
||||||
<a href="/admin" class="admin-nav__link admin-nav__link--active">Обзор</a>
|
|
||||||
<a href="/admin/orders" class="admin-nav__link">Заказы</a>
|
|
||||||
<a href="/admin/users" class="admin-nav__link">Пользователи</a>
|
|
||||||
<a href="/admin/products" class="admin-nav__link">Товары</a>
|
|
||||||
<a href="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
|
||||||
<a href="/" class="admin-nav__link">В магазин</a>
|
|
||||||
</nav>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<section class="card" style="margin-bottom:1.5rem">
|
||||||
|
<h2 style="margin-top:0">Обновление с Git</h2>
|
||||||
|
<p class="muted">Подтянуть новую версию и перезапустить магазин без SSH.</p>
|
||||||
|
<a href="/admin/system" class="btn btn--primary">Перейти к обновлению →</a>
|
||||||
|
</section>
|
||||||
|
|
||||||
<div class="stats-grid">
|
<div class="stats-grid">
|
||||||
<div class="stat-card">
|
<div class="stat-card">
|
||||||
<span class="stat-card__label">Пользователи</span>
|
<span class="stat-card__label">Пользователи</span>
|
||||||
|
|||||||
@@ -1,18 +1,25 @@
|
|||||||
<%- include('../partials/layout-start') %>
|
<%- include('../partials/layout-start') %>
|
||||||
|
<% const statusLabels = { pending: 'Ожидает', paid: 'Оплачен', shipped: 'Отправлен', cancelled: 'Отменён' }; %>
|
||||||
|
|
||||||
<div class="admin-header">
|
<div class="admin-header">
|
||||||
<h1>Заказы</h1>
|
<h1>Заказы</h1>
|
||||||
<nav class="admin-nav">
|
<div class="admin-header__actions">
|
||||||
<a href="/admin" class="admin-nav__link">Обзор</a>
|
<a href="/admin/orders/export.csv" class="btn btn--ghost btn--sm">Экспорт CSV</a>
|
||||||
<a href="/admin/orders" class="admin-nav__link admin-nav__link--active">Заказы</a>
|
<%- include('../partials/admin-nav', { adminNav: 'orders' }) %>
|
||||||
<a href="/admin/users" class="admin-nav__link">Пользователи</a>
|
</div>
|
||||||
<a href="/admin/products" class="admin-nav__link">Товары</a>
|
|
||||||
<a href="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
|
||||||
<a href="/" class="admin-nav__link">В магазин</a>
|
|
||||||
</nav>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<% const statusLabels = { pending: 'Ожидает', paid: 'Оплачен', shipped: 'Отправлен', cancelled: 'Отменён' }; %>
|
<form class="catalog-toolbar" method="get" action="/admin/orders">
|
||||||
|
<label class="catalog-toolbar__field">
|
||||||
|
<span class="catalog-toolbar__label">Статус</span>
|
||||||
|
<select name="status" class="input input--sm" onchange="this.form.submit()">
|
||||||
|
<option value="">Все</option>
|
||||||
|
<% ['pending','paid','shipped','cancelled'].forEach(s => { %>
|
||||||
|
<option value="<%= s %>" <%= statusFilter === s ? 'selected' : '' %>><%= statusLabels[s] %></option>
|
||||||
|
<% }) %>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</form>
|
||||||
|
|
||||||
<table class="cart-table">
|
<table class="cart-table">
|
||||||
<thead>
|
<thead>
|
||||||
|
|||||||
@@ -1,59 +1,89 @@
|
|||||||
<%- include('../partials/layout-start') %>
|
<%- include('../partials/layout-start') %>
|
||||||
|
|
||||||
<div class="admin-header">
|
<div class="admin-header">
|
||||||
<h1>Товары</h1>
|
<h1>Товары — цены и скидки</h1>
|
||||||
<nav class="admin-nav">
|
<%- include('../partials/admin-nav', { adminNav: 'products' }) %>
|
||||||
<a href="/admin" class="admin-nav__link">Обзор</a>
|
|
||||||
<a href="/admin/orders" class="admin-nav__link">Заказы</a>
|
|
||||||
<a href="/admin/users" class="admin-nav__link">Пользователи</a>
|
|
||||||
<a href="/admin/products" class="admin-nav__link admin-nav__link--active">Товары</a>
|
|
||||||
<a href="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
|
||||||
<a href="/" class="admin-nav__link">В магазин</a>
|
|
||||||
</nav>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<% if (stockUpdated) { %>
|
<% if (stockUpdated) { %>
|
||||||
<p class="alert alert--success">
|
<p class="alert alert--success">
|
||||||
Остаток обновлён.<% if (notified > 0) { %> Отправлено уведомлений подписчикам: <%= notified %>.<% } %>
|
Остаток обновлён.<% if (notified > 0) { %> Уведомления о поступлении: <%= notified %>.<% } %>
|
||||||
</p>
|
</p>
|
||||||
<% } %>
|
<% } %>
|
||||||
|
<% if (pricingUpdated) { %><p class="alert alert--success">Цены обновлены</p><% } %>
|
||||||
|
<% if (pricingError) { %><p class="alert alert--error"><%= pricingError %></p><% } %>
|
||||||
|
|
||||||
<table class="cart-table">
|
<p class="muted admin-hint">Укажите обычную цену и цену со скидкой (₽). Пустая скидка или «Сбросить» — без акции. Для акции можно задать дату окончания.</p>
|
||||||
|
|
||||||
|
<table class="cart-table admin-products-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>ID</th>
|
<th>Товар</th>
|
||||||
<th>Название</th>
|
<th>Цена / скидка (₽)</th>
|
||||||
<th>Категория</th>
|
<th>Акция до</th>
|
||||||
<th>Цена</th>
|
|
||||||
<th>Остаток</th>
|
<th>Остаток</th>
|
||||||
<th>Подписки</th>
|
|
||||||
<th></th>
|
<th></th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<% products.forEach(p => { %>
|
<% products.forEach(p => { %>
|
||||||
|
<% const onSale = isSaleActive(p); %>
|
||||||
|
<% const eff = effectivePrice(p); %>
|
||||||
<tr>
|
<tr>
|
||||||
<td><%= p.id %></td>
|
|
||||||
<td><%= p.name %></td>
|
|
||||||
<td><%= p.category_name || '—' %></td>
|
|
||||||
<td><%= formatPrice(p.price_cents) %></td>
|
|
||||||
<td>
|
<td>
|
||||||
<form action="/admin/products/<%= p.id %>/stock" method="post" class="inline-form admin-stock-form">
|
<strong><%= p.name %></strong><br>
|
||||||
<input type="number" name="stock" class="input input--sm" min="0" value="<%= p.stock %>" aria-label="Остаток">
|
<span class="muted"><%= p.category_name || '—' %></span>
|
||||||
<button type="submit" class="btn btn--ghost btn--sm">OK</button>
|
<% if (onSale) { %>
|
||||||
</form>
|
<br><span class="badge badge--sale">−<%= salePercent(p) %>% на сайте</span>
|
||||||
|
<% } %>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<% if (p.alert_count > 0) { %>
|
<form action="/admin/products/<%= p.id %>/pricing" method="post" class="admin-pricing-form">
|
||||||
<span class="badge" title="Ждут уведомления"><%= p.alert_count %></span>
|
<label class="label label--inline">
|
||||||
<% } else { %>
|
Цена
|
||||||
—
|
<input type="number" name="price_rub" class="input input--sm" min="0" step="0.01" required
|
||||||
|
value="<%= (p.price_cents / 100).toFixed(2) %>">
|
||||||
|
</label>
|
||||||
|
<label class="label label--inline">
|
||||||
|
Со скидкой
|
||||||
|
<input type="number" name="sale_price_rub" class="input input--sm" min="0" step="0.01" placeholder="—"
|
||||||
|
value="<%= p.sale_price_cents != null ? (p.sale_price_cents / 100).toFixed(2) : '' %>">
|
||||||
|
</label>
|
||||||
|
<button type="submit" class="btn btn--primary btn--sm">Сохранить</button>
|
||||||
|
</form>
|
||||||
|
<% if (onSale) { %>
|
||||||
|
<p class="muted" style="margin:0.35rem 0 0">На сайте: <strong><%= formatPrice(eff) %></strong> вместо <%= formatPrice(p.price_cents) %></p>
|
||||||
<% } %>
|
<% } %>
|
||||||
</td>
|
</td>
|
||||||
|
<td>
|
||||||
|
<form action="/admin/products/<%= p.id %>/pricing" method="post" class="admin-pricing-form admin-pricing-form--ends">
|
||||||
|
<input type="hidden" name="price_rub" value="<%= (p.price_cents / 100).toFixed(2) %>">
|
||||||
|
<input type="hidden" name="sale_price_rub" value="<%= p.sale_price_cents != null ? (p.sale_price_cents / 100).toFixed(2) : '' %>">
|
||||||
|
<input type="datetime-local" name="sale_ends_at" class="input input--sm"
|
||||||
|
value="<%= p.sale_ends_at ? new Date(p.sale_ends_at).toISOString().slice(0, 16) : '' %>">
|
||||||
|
<button type="submit" class="btn btn--ghost btn--sm">OK</button>
|
||||||
|
<% if (p.sale_price_cents != null) { %>
|
||||||
|
<button type="submit" formaction="/admin/products/<%= p.id %>/pricing" name="clear_sale" value="1" class="btn btn--ghost btn--sm">Сбросить скидку</button>
|
||||||
|
<% } %>
|
||||||
|
</form>
|
||||||
|
<% if (onSale && p.sale_ends_at) { %>
|
||||||
|
<div class="promo-countdown" data-expires="<%= p.sale_ends_at %>" style="margin-top:0.35rem">
|
||||||
|
<span class="promo-countdown__timer">—</span>
|
||||||
|
</div>
|
||||||
|
<% } %>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<form action="/admin/products/<%= p.id %>/stock" method="post" class="inline-form admin-stock-form">
|
||||||
|
<input type="number" name="stock" class="input input--sm" min="0" value="<%= p.stock %>">
|
||||||
|
<button type="submit" class="btn btn--ghost btn--sm">OK</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
<td><a href="/product/<%= p.slug %>">На сайте</a></td>
|
<td><a href="/product/<%= p.slug %>">На сайте</a></td>
|
||||||
</tr>
|
</tr>
|
||||||
<% }) %>
|
<% }) %>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
|
<script src="/js/promo-countdown.js"></script>
|
||||||
|
|
||||||
<%- include('../partials/layout-end') %>
|
<%- include('../partials/layout-end') %>
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
<%- include('../partials/layout-start') %>
|
||||||
|
|
||||||
|
<div class="admin-header">
|
||||||
|
<h1>Промокоды и скидки</h1>
|
||||||
|
<%- include('../partials/admin-nav', { adminNav: 'promo' }) %>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<% if (created) { %><p class="alert alert--success">Промокод создан</p><% } %>
|
||||||
|
<% if (updated) { %><p class="alert alert--success">Промокод обновлён</p><% } %>
|
||||||
|
|
||||||
|
<section class="card account-section--narrow" style="margin-bottom:1.5rem">
|
||||||
|
<h2>Новый промокод</h2>
|
||||||
|
<form action="/admin/promo-codes" method="post" class="form form--grid">
|
||||||
|
<label class="label">Код <input type="text" name="code" class="input" required placeholder="SUMMER20"></label>
|
||||||
|
<label class="label">Описание <input type="text" name="description" class="input" placeholder="Летняя скидка"></label>
|
||||||
|
<label class="label">Тип скидки
|
||||||
|
<select name="discount_type" class="input" id="promo-type-new">
|
||||||
|
<option value="percent">Процент (%)</option>
|
||||||
|
<option value="fixed">Фиксированная сумма (₽)</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="label">
|
||||||
|
<span id="promo-value-label-new">Размер скидки (%)</span>
|
||||||
|
<input type="number" name="discount_value" class="input" min="1" required placeholder="10">
|
||||||
|
</label>
|
||||||
|
<label class="label">Действует (дней с сегодня) <input type="number" name="valid_days" class="input" value="30" min="1"></label>
|
||||||
|
<label class="label">Мин. сумма заказа (₽) <input type="number" name="min_order_rub" class="input" value="0" min="0" step="1"></label>
|
||||||
|
<label class="label">Лимит использований <input type="number" name="max_uses" class="input" min="1" placeholder="без лимита"></label>
|
||||||
|
<button type="submit" class="btn btn--primary">Создать</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<table class="cart-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Код</th>
|
||||||
|
<th>Настройки скидки</th>
|
||||||
|
<th>Срок / лимит</th>
|
||||||
|
<th>Использовано</th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% promos.forEach(p => { %>
|
||||||
|
<tr>
|
||||||
|
<td><strong><%= p.code %></strong></td>
|
||||||
|
<td>
|
||||||
|
<form action="/admin/promo-codes/<%= p.id %>/update" method="post" class="admin-promo-form">
|
||||||
|
<input type="text" name="description" class="input input--sm" value="<%= p.description || '' %>" placeholder="Описание">
|
||||||
|
<select name="discount_type" class="input input--sm promo-type-select">
|
||||||
|
<option value="percent"<%= p.discount_type === 'percent' ? ' selected' : '' %>>%</option>
|
||||||
|
<option value="fixed"<%= p.discount_type === 'fixed' ? ' selected' : '' %>>₽</option>
|
||||||
|
</select>
|
||||||
|
<input type="number" name="discount_value" class="input input--sm" min="1" required
|
||||||
|
value="<%= p.discount_type === 'percent' ? p.discount_value : (p.discount_value / 100) %>"
|
||||||
|
title="<%= p.discount_type === 'percent' ? 'Процент' : 'Рубли' %>">
|
||||||
|
<label class="label label--inline muted">мин. заказ ₽
|
||||||
|
<input type="number" name="min_order_rub" class="input input--sm" min="0"
|
||||||
|
value="<%= Math.round(p.min_order_cents / 100) %>">
|
||||||
|
</label>
|
||||||
|
<button type="submit" class="btn btn--ghost btn--sm">Сохранить</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<form action="/admin/promo-codes/<%= p.id %>/update" method="post" class="admin-promo-form">
|
||||||
|
<input type="hidden" name="description" value="<%= p.description || '' %>">
|
||||||
|
<input type="hidden" name="discount_type" value="<%= p.discount_type %>">
|
||||||
|
<input type="hidden" name="discount_value" value="<%= p.discount_type === 'percent' ? p.discount_value : (p.discount_value / 100) %>">
|
||||||
|
<input type="hidden" name="min_order_rub" value="<%= Math.round(p.min_order_cents / 100) %>">
|
||||||
|
<label class="label label--inline">ещё дней
|
||||||
|
<input type="number" name="valid_days" class="input input--sm" value="7" min="1">
|
||||||
|
</label>
|
||||||
|
<label class="label label--inline">лимит
|
||||||
|
<input type="number" name="max_uses" class="input input--sm" min="1"
|
||||||
|
value="<%= p.max_uses || '' %>" placeholder="∞">
|
||||||
|
</label>
|
||||||
|
<button type="submit" class="btn btn--ghost btn--sm">Продлить</button>
|
||||||
|
<p class="muted" style="margin:0.25rem 0 0;font-size:0.85rem">до <%= new Date(p.expires_at).toLocaleString('ru-RU') %></p>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
<td><%= p.use_count %><% if (p.max_uses) { %> / <%= p.max_uses %><% } %></td>
|
||||||
|
<td>
|
||||||
|
<span class="badge<%= p.active ? '' : ' badge--muted' %>"><%= p.active ? 'Активен' : 'Выкл.' %></span>
|
||||||
|
<form action="/admin/promo-codes/<%= p.id %>/toggle" method="post" style="margin-top:0.35rem">
|
||||||
|
<button type="submit" class="btn btn--ghost btn--sm"><%= p.active ? 'Выключить' : 'Включить' %></button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function bindPromoType(selectId, labelId) {
|
||||||
|
const sel = document.getElementById(selectId);
|
||||||
|
const lab = document.getElementById(labelId);
|
||||||
|
if (!sel || !lab) return;
|
||||||
|
const sync = () => {
|
||||||
|
lab.textContent = sel.value === 'fixed' ? 'Скидка (₽)' : 'Размер скидки (%)';
|
||||||
|
};
|
||||||
|
sel.addEventListener('change', sync);
|
||||||
|
sync();
|
||||||
|
}
|
||||||
|
bindPromoType('promo-type-new', 'promo-value-label-new');
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<%- include('../partials/layout-end') %>
|
||||||
@@ -2,14 +2,7 @@
|
|||||||
|
|
||||||
<div class="admin-header">
|
<div class="admin-header">
|
||||||
<h1>Бронирования</h1>
|
<h1>Бронирования</h1>
|
||||||
<nav class="admin-nav">
|
<%- include('../partials/admin-nav', { adminNav: 'reservations' }) %>
|
||||||
<a href="/admin" class="admin-nav__link">Обзор</a>
|
|
||||||
<a href="/admin/orders" class="admin-nav__link">Заказы</a>
|
|
||||||
<a href="/admin/users" class="admin-nav__link">Пользователи</a>
|
|
||||||
<a href="/admin/products" class="admin-nav__link">Товары</a>
|
|
||||||
<a href="/admin/reservations" class="admin-nav__link admin-nav__link--active">Бронирования</a>
|
|
||||||
<a href="/" class="admin-nav__link">В магазин</a>
|
|
||||||
</nav>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<% const resStatus = { active: 'Активна', fulfilled: 'Выполнена', cancelled: 'Отменена', expired: 'Истекла' }; %>
|
<% const resStatus = { active: 'Активна', fulfilled: 'Выполнена', cancelled: 'Отменена', expired: 'Истекла' }; %>
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
<%- include('../partials/layout-start') %>
|
||||||
|
|
||||||
|
<div class="admin-header">
|
||||||
|
<h1>Обновление с Git</h1>
|
||||||
|
<%- include('../partials/admin-nav', { adminNav: 'system' }) %>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<% if (updateOk) { %>
|
||||||
|
<p class="alert alert--success">Обновление выполнено успешно. Если сайт не открывается — подождите 10–20 сек и обновите страницу.</p>
|
||||||
|
<% } %>
|
||||||
|
<% if (updateFail) { %>
|
||||||
|
<p class="alert alert--error">Обновление завершилось с ошибкой (код <%= updateCode %>).</p>
|
||||||
|
<% } %>
|
||||||
|
<% if (confirmError) { %>
|
||||||
|
<p class="alert alert--error">Введите <strong>update</strong> для подтверждения.</p>
|
||||||
|
<% } %>
|
||||||
|
<% if (disabledError) { %>
|
||||||
|
<p class="alert alert--warn">Обновление из админки отключено на этом сервере.</p>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
|
<section class="card admin-system">
|
||||||
|
<h2>Текущая версия</h2>
|
||||||
|
<% if (!git.available) { %>
|
||||||
|
<p class="alert alert--warn"><%= git.reason || 'Git недоступен' %></p>
|
||||||
|
<% } else { %>
|
||||||
|
<dl class="profile-dl admin-system__meta">
|
||||||
|
<dt>Версия приложения</dt>
|
||||||
|
<dd><strong>v<%= git.packageVersion || '?' %></strong></dd>
|
||||||
|
<dt>Каталог</dt>
|
||||||
|
<dd><code class="admin-system__path"><%= git.shopRoot %></code></dd>
|
||||||
|
<% if (git.repoOwner) { %>
|
||||||
|
<dt>Владелец .git</dt>
|
||||||
|
<dd><code><%= git.repoOwner %></code> <span class="muted">(git pull выполняется от этого пользователя)</span></dd>
|
||||||
|
<% } %>
|
||||||
|
<dt>Ветка</dt>
|
||||||
|
<dd><%= git.branch %></dd>
|
||||||
|
<dt>Коммит</dt>
|
||||||
|
<dd>
|
||||||
|
<code><%= git.commitShort %></code>
|
||||||
|
— <%= git.commitSubject %>
|
||||||
|
<span class="muted">(<%= git.commitDate %>)</span>
|
||||||
|
</dd>
|
||||||
|
<% if (git.dirty) { %>
|
||||||
|
<dt>Состояние</dt>
|
||||||
|
<dd>
|
||||||
|
<span class="badge badge--warn">Есть незакоммиченные изменения</span>
|
||||||
|
<% if (git.dirtyHint) { %><p class="muted" style="margin:0.35rem 0 0;font-size:0.85rem"><%= git.dirtyHint %></p><% } %>
|
||||||
|
</dd>
|
||||||
|
<% } %>
|
||||||
|
<% if (git.behind != null) { %>
|
||||||
|
<dt>На origin/main</dt>
|
||||||
|
<dd>
|
||||||
|
<% if (git.remoteShort) { %>
|
||||||
|
<span class="muted">Удалённо: <code><%= git.remoteShort %></code></span><br>
|
||||||
|
<% } %>
|
||||||
|
<% if (git.diverged) { %>
|
||||||
|
<span class="badge badge--warn">Истории разошлись</span>
|
||||||
|
<span class="badge badge--sale">Можно подтянуть: <%= git.behind %> комм.</span>
|
||||||
|
<span class="muted">Локально впереди на <%= git.ahead %> комм.</span>
|
||||||
|
<p class="muted" style="margin:0.35rem 0 0;font-size:0.85rem">Обновление из админки сделает <code>git pull</code> (как на origin). Локальные коммиты могут быть сброшены.</p>
|
||||||
|
<% } else if (git.behind > 0) { %>
|
||||||
|
<span class="badge badge--sale">Доступно обновлений: <%= git.behind %></span>
|
||||||
|
<% } else if (git.ahead > 0) { %>
|
||||||
|
<span class="badge badge--warn">Локально впереди origin на <%= git.ahead %> комм.</span>
|
||||||
|
<% } else { %>
|
||||||
|
<span class="badge">Актуально</span>
|
||||||
|
<% } %>
|
||||||
|
</dd>
|
||||||
|
<% } %>
|
||||||
|
<% if (git.fetchError) { %>
|
||||||
|
<dt>origin</dt>
|
||||||
|
<dd class="muted">Не удалось проверить: <%= git.fetchError %></dd>
|
||||||
|
<% } %>
|
||||||
|
</dl>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
|
<div class="admin-system__actions">
|
||||||
|
<form action="/admin/system/check" method="post" class="inline-form">
|
||||||
|
<button type="submit" class="btn btn--ghost">
|
||||||
|
<%- include('../partials/icon', { name: 'refresh', iconSize: 18 }) %>
|
||||||
|
Проверить на Git
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<% if (git.updateEnabled) { %>
|
||||||
|
<hr class="admin-system__hr">
|
||||||
|
<h2>Обновить сейчас</h2>
|
||||||
|
<p class="muted admin-hint">
|
||||||
|
Выполняется <code>git pull</code>, <code>npm install</code> и перезапуск службы <code>shop</code>.
|
||||||
|
Страница может оборваться на несколько секунд — это нормально.
|
||||||
|
</p>
|
||||||
|
<form action="/admin/system/update" method="post" class="form admin-system__form" onsubmit="return confirm('Обновить код с Git и перезапустить магазин?');">
|
||||||
|
<label class="label">
|
||||||
|
Подтверждение: введите <strong>update</strong>
|
||||||
|
<input type="text" name="confirm" class="input" required autocomplete="off" placeholder="update">
|
||||||
|
</label>
|
||||||
|
<button type="submit" class="btn btn--primary btn--lg">
|
||||||
|
<%- include('../partials/icon', { name: 'download', iconSize: 20 }) %>
|
||||||
|
Обновить с Git
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
<% } else if (git.available) { %>
|
||||||
|
<p class="alert alert--warn">
|
||||||
|
Обновление из админки отключено (Windows, нет .git или <code>ADMIN_UPDATE_ENABLED=0</code>).
|
||||||
|
На сервере: <code>bash "$SHOP_ROOT/scripts/server-update.sh"</code>
|
||||||
|
</p>
|
||||||
|
<% } %>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<% if (updateLog) { %>
|
||||||
|
<section class="card admin-system__log">
|
||||||
|
<h2>Журнал обновления</h2>
|
||||||
|
<pre class="admin-system__pre"><%= updateLog %></pre>
|
||||||
|
</section>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
|
<section class="card admin-system__help muted">
|
||||||
|
<h2>Настройка сервера</h2>
|
||||||
|
<p>В <code>.env</code>:</p>
|
||||||
|
<pre class="admin-system__pre">SHOP_ROOT=<%= git.shopRoot || '/opt/shop/shop10' %>
|
||||||
|
ADMIN_UPDATE_ENABLED=1
|
||||||
|
ADMIN_UPDATE_USE_SUDO=1
|
||||||
|
SHOP_GIT_USER=<%= git.repoOwner || 'root' %></pre>
|
||||||
|
<p>Sudoers для <code>www-data</code> (от root):</p>
|
||||||
|
<pre class="admin-system__pre">www-data ALL=(root) NOPASSWD: <%= git.shopRoot || '/opt/shop/shop10' %>/scripts/admin-web-update.sh
|
||||||
|
www-data ALL=(<%= git.repoOwner || 'root' %>) NOPASSWD: /usr/bin/git</pre>
|
||||||
|
<p class="muted">«Проверить на Git» — через <code>ls-remote</code> (без записи в .git). Pull — от владельца каталога.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<%- include('../partials/layout-end') %>
|
||||||
@@ -2,14 +2,7 @@
|
|||||||
|
|
||||||
<div class="admin-header">
|
<div class="admin-header">
|
||||||
<h1>Пользователи</h1>
|
<h1>Пользователи</h1>
|
||||||
<nav class="admin-nav">
|
<%- include('../partials/admin-nav', { adminNav: 'users' }) %>
|
||||||
<a href="/admin" class="admin-nav__link">Обзор</a>
|
|
||||||
<a href="/admin/orders" class="admin-nav__link">Заказы</a>
|
|
||||||
<a href="/admin/users" class="admin-nav__link admin-nav__link--active">Пользователи</a>
|
|
||||||
<a href="/admin/products" class="admin-nav__link">Товары</a>
|
|
||||||
<a href="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
|
||||||
<a href="/" class="admin-nav__link">В магазин</a>
|
|
||||||
</nav>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p class="muted admin-hint">
|
<p class="muted admin-hint">
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
Email
|
Email
|
||||||
<input type="email" name="email" class="input" required value="<%= values.email || '' %>" autocomplete="email">
|
<input type="email" name="email" class="input" required value="<%= values.email || '' %>" autocomplete="email">
|
||||||
</label>
|
</label>
|
||||||
|
<%- include('../partials/captcha-widget') %>
|
||||||
<button type="submit" class="btn btn--primary btn--block">Отправить ссылку</button>
|
<button type="submit" class="btn btn--primary btn--block">Отправить ссылку</button>
|
||||||
<p class="form-footer"><a href="/login">← Вход</a></p>
|
<p class="form-footer"><a href="/login">← Вход</a></p>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
+77
-6
@@ -3,6 +3,8 @@
|
|||||||
<h1>Корзина</h1>
|
<h1>Корзина</h1>
|
||||||
|
|
||||||
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %>
|
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %>
|
||||||
|
<% if (promoOk) { %><p class="alert alert--success"><%= promoOk %></p><% } %>
|
||||||
|
<% if (promoErr) { %><p class="alert alert--error"><%= promoErr %></p><% } %>
|
||||||
|
|
||||||
<% if (!items.length) { %>
|
<% if (!items.length) { %>
|
||||||
<p class="empty">Корзина пуста. <a href="/">Перейти в каталог</a></p>
|
<p class="empty">Корзина пуста. <a href="/">Перейти в каталог</a></p>
|
||||||
@@ -27,28 +29,97 @@
|
|||||||
<% } %>
|
<% } %>
|
||||||
<a href="/product/<%= item.slug %>"><%= item.name %></a>
|
<a href="/product/<%= item.slug %>"><%= item.name %></a>
|
||||||
</td>
|
</td>
|
||||||
<td><%= formatPrice(item.price_cents) %></td>
|
<td class="cart-table__price">
|
||||||
|
<%- include('partials/product-price', {
|
||||||
|
product: item,
|
||||||
|
forceOnSale: item.on_sale,
|
||||||
|
forceEffective: item.effective_price_cents,
|
||||||
|
priceSize: 'sm'
|
||||||
|
}) %>
|
||||||
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<input type="number" name="items[<%= item.id %>]" value="<%= item.quantity %>" min="0" max="<%= item.stock %>" class="input input--qty">
|
<input type="number" name="items[<%= item.id %>]" value="<%= item.quantity %>" min="0" max="<%= item.stock %>" class="input input--qty">
|
||||||
</td>
|
</td>
|
||||||
<td><%= formatPrice(item.line_total) %></td>
|
<td><%= formatPrice(item.line_total) %></td>
|
||||||
<td>
|
<td>
|
||||||
<button type="submit" formaction="/cart/remove/<%= item.id %>" formmethod="post" class="btn btn--ghost btn--sm" title="Удалить">×</button>
|
<button type="submit" formaction="/cart/remove/<%= item.id %>" formmethod="post" class="btn btn--ghost btn--sm btn--icon" title="Удалить" aria-label="Удалить">
|
||||||
|
<%- include('partials/icon', { name: 'trash', iconSize: 16 }) %>
|
||||||
|
</button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<% }) %>
|
<% }) %>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
<div class="cart-actions">
|
|
||||||
<button type="submit" class="btn btn--ghost">Обновить</button>
|
<div class="cart-sidebar">
|
||||||
<p class="cart-total">Итого: <strong><%= formatPrice(total) %></strong></p>
|
<section class="card promo-box">
|
||||||
|
<h2 class="promo-box__title">Промокод</h2>
|
||||||
|
<% if (pricing.promo) { %>
|
||||||
|
<p class="promo-box__applied">
|
||||||
|
<strong><%= pricing.promo.code %></strong>
|
||||||
|
<% if (pricing.promo.description) { %> — <%= pricing.promo.description %><% } %>
|
||||||
|
</p>
|
||||||
|
<p class="promo-box__discount">Скидка: −<%= formatPrice(pricing.promoDiscount) %></p>
|
||||||
|
<div class="promo-countdown" data-expires="<%= pricing.promo.expires_at %>">
|
||||||
|
<span class="promo-countdown__label">До конца акции:</span>
|
||||||
|
<span class="promo-countdown__timer">—</span>
|
||||||
|
</div>
|
||||||
|
<form action="/cart/promo/remove" method="post" class="inline-form">
|
||||||
|
<button type="submit" class="btn btn--ghost btn--sm">Убрать промокод</button>
|
||||||
|
</form>
|
||||||
|
<% } else { %>
|
||||||
|
<form action="/cart/promo" method="post" class="promo-box__form">
|
||||||
|
<input type="text" name="code" class="input" placeholder="WELCOME10" required autocomplete="off">
|
||||||
|
<button type="submit" class="btn btn--primary">Применить</button>
|
||||||
|
</form>
|
||||||
|
<% } %>
|
||||||
|
</section>
|
||||||
|
|
||||||
<% if (user) { %>
|
<% if (user) { %>
|
||||||
<a href="/checkout" class="btn btn--primary btn--lg">Оформить заказ</a>
|
<section class="card promo-box">
|
||||||
|
<h2 class="promo-box__title">Баллы лояльности</h2>
|
||||||
|
<p class="muted">На счёте: <strong><%= pricing.loyaltyBalance %></strong> баллов (1 балл = 1 коп.)</p>
|
||||||
|
<% if (pricing.pointsEarned > 0) { %>
|
||||||
|
<p class="muted">За этот заказ начислим: +<%= pricing.pointsEarned %> баллов</p>
|
||||||
|
<% } %>
|
||||||
|
<% if (pricing.loyaltyDiscount > 0) { %>
|
||||||
|
<p class="promo-box__discount">Списано: −<%= formatPrice(pricing.loyaltyDiscount) %> (<%= pricing.loyaltyPointsUsed %> баллов)</p>
|
||||||
|
<form action="/cart/loyalty/remove" method="post">
|
||||||
|
<button type="submit" class="btn btn--ghost btn--sm">Отменить списание</button>
|
||||||
|
</form>
|
||||||
|
<% } else if (pricing.loyaltyBalance > 0) { %>
|
||||||
|
<form action="/cart/loyalty" method="post" class="promo-box__form">
|
||||||
|
<button type="submit" name="use_all" value="1" class="btn btn--ghost">Списать все доступные</button>
|
||||||
|
</form>
|
||||||
|
<% } %>
|
||||||
|
</section>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
|
<section class="card cart-summary">
|
||||||
|
<dl class="cart-summary__dl">
|
||||||
|
<dt>Товары</dt>
|
||||||
|
<dd><%= formatPrice(pricing.subtotal) %></dd>
|
||||||
|
<% if (pricing.promoDiscount > 0) { %>
|
||||||
|
<dt>Промокод</dt>
|
||||||
|
<dd class="cart-summary__discount">−<%= formatPrice(pricing.promoDiscount) %></dd>
|
||||||
|
<% } %>
|
||||||
|
<% if (pricing.loyaltyDiscount > 0) { %>
|
||||||
|
<dt>Лояльность</dt>
|
||||||
|
<dd class="cart-summary__discount">−<%= formatPrice(pricing.loyaltyDiscount) %></dd>
|
||||||
|
<% } %>
|
||||||
|
<dt class="cart-summary__total-label">К оплате</dt>
|
||||||
|
<dd class="cart-summary__total"><%= formatPrice(pricing.total) %></dd>
|
||||||
|
</dl>
|
||||||
|
<% if (user) { %>
|
||||||
|
<a href="/checkout" class="btn btn--primary btn--lg btn--block">Оформить заказ</a>
|
||||||
<% } else { %>
|
<% } else { %>
|
||||||
<p class="hint"><a href="/login?next=/checkout">Войдите</a>, чтобы оформить заказ.</p>
|
<p class="hint"><a href="/login?next=/checkout">Войдите</a>, чтобы оформить заказ.</p>
|
||||||
<% } %>
|
<% } %>
|
||||||
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
<% } %>
|
<% } %>
|
||||||
|
|
||||||
|
<script src="/js/promo-countdown.js"></script>
|
||||||
|
|
||||||
<%- include('partials/layout-end') %>
|
<%- include('partials/layout-end') %>
|
||||||
|
|||||||
+29
-1
@@ -36,8 +36,36 @@
|
|||||||
</li>
|
</li>
|
||||||
<% }) %>
|
<% }) %>
|
||||||
</ul>
|
</ul>
|
||||||
<p class="checkout-total">Итого: <strong><%= formatPrice(total) %></strong></p>
|
<% if (pricing.promo) { %>
|
||||||
|
<p class="checkout-promo">
|
||||||
|
Промокод <strong><%= pricing.promo.code %></strong>
|
||||||
|
<span class="promo-countdown" data-expires="<%= pricing.promo.expires_at %>">
|
||||||
|
(<span class="promo-countdown__timer">—</span>)
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
<% } %>
|
||||||
|
<dl class="cart-summary__dl">
|
||||||
|
<dt>Товары</dt>
|
||||||
|
<dd><%= formatPrice(pricing.subtotal) %></dd>
|
||||||
|
<% if (pricing.promoDiscount > 0) { %>
|
||||||
|
<dt>Скидка по промокоду</dt>
|
||||||
|
<dd class="cart-summary__discount">−<%= formatPrice(pricing.promoDiscount) %></dd>
|
||||||
|
<% } %>
|
||||||
|
<% if (pricing.loyaltyDiscount > 0) { %>
|
||||||
|
<dt>Баллы лояльности</dt>
|
||||||
|
<dd class="cart-summary__discount">−<%= formatPrice(pricing.loyaltyDiscount) %></dd>
|
||||||
|
<% } %>
|
||||||
|
<% if (pricing.pointsEarned > 0) { %>
|
||||||
|
<dt>Начислим баллов</dt>
|
||||||
|
<dd>+<%= pricing.pointsEarned %></dd>
|
||||||
|
<% } %>
|
||||||
|
<dt class="cart-summary__total-label">К оплате</dt>
|
||||||
|
<dd class="cart-summary__total"><%= formatPrice(pricing.total) %></dd>
|
||||||
|
</dl>
|
||||||
|
<p class="muted"><a href="/cart">Изменить корзину или промокод</a></p>
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<script src="/js/promo-countdown.js"></script>
|
||||||
|
|
||||||
<%- include('partials/layout-end') %>
|
<%- include('partials/layout-end') %>
|
||||||
|
|||||||
+78
-6
@@ -1,26 +1,91 @@
|
|||||||
<%- include('partials/layout-start') %>
|
<%- include('partials/layout-start') %>
|
||||||
|
<%
|
||||||
|
function catalogHref(extra) {
|
||||||
|
const p = new URLSearchParams();
|
||||||
|
if (searchQuery) p.set('q', searchQuery);
|
||||||
|
if (saleOnly) p.set('sale', '1');
|
||||||
|
if (showAll) p.set('all', '1');
|
||||||
|
if (sort && sort !== 'name') p.set('sort', sort);
|
||||||
|
if (extra && extra.category) p.set('category', extra.category);
|
||||||
|
const s = p.toString();
|
||||||
|
return s ? '/?' + s : '/';
|
||||||
|
}
|
||||||
|
%>
|
||||||
|
|
||||||
<section class="hero">
|
<section class="hero">
|
||||||
<h1>Каталог товаров</h1>
|
<h1>Каталог товаров</h1>
|
||||||
<p>Доставка по России. Оплата при получении.</p>
|
<p class="hero__lead">Доставка по России · Оплата при получении · Акции со скидкой в каталоге</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<% if (categories.length) { %>
|
<% if (categories.length) { %>
|
||||||
<nav class="categories" aria-label="Категории">
|
<nav class="categories" aria-label="Категории">
|
||||||
<a href="/" class="chip <%= !activeCategory ? 'chip--active' : '' %>">Все</a>
|
<a href="<%= catalogHref() %>" class="chip <%= !activeCategory ? 'chip--active' : '' %>">Все</a>
|
||||||
<% categories.forEach(c => { %>
|
<% categories.forEach(c => { %>
|
||||||
<a href="/?category=<%= c.slug %>" class="chip <%= activeCategory === c.slug ? 'chip--active' : '' %>"><%= c.name %></a>
|
<a href="<%= catalogHref({ category: c.slug }) %>" class="chip <%= activeCategory === c.slug ? 'chip--active' : '' %>"><%= c.name %></a>
|
||||||
<% }) %>
|
<% }) %>
|
||||||
</nav>
|
</nav>
|
||||||
<% } %>
|
<% } %>
|
||||||
|
|
||||||
|
<form class="catalog-toolbar" method="get" action="/">
|
||||||
|
<% if (searchQuery) { %><input type="hidden" name="q" value="<%= searchQuery %>"><% } %>
|
||||||
|
<% if (activeCategory) { %><input type="hidden" name="category" value="<%= activeCategory %>"><% } %>
|
||||||
|
<label class="catalog-toolbar__field">
|
||||||
|
<span class="catalog-toolbar__label">Сортировка</span>
|
||||||
|
<select name="sort" class="input input--sm" onchange="this.form.submit()">
|
||||||
|
<option value="name" <%= sort === 'name' ? 'selected' : '' %>>По названию</option>
|
||||||
|
<option value="price_asc" <%= sort === 'price_asc' ? 'selected' : '' %>>Цена ↑</option>
|
||||||
|
<option value="price_desc" <%= sort === 'price_desc' ? 'selected' : '' %>>Цена ↓</option>
|
||||||
|
<option value="newest" <%= sort === 'newest' ? 'selected' : '' %>>Сначала новые</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="catalog-toolbar__check">
|
||||||
|
<input type="checkbox" name="sale" value="1" <%= saleOnly ? 'checked' : '' %> onchange="this.form.submit()">
|
||||||
|
Только со скидкой
|
||||||
|
</label>
|
||||||
|
<label class="catalog-toolbar__check">
|
||||||
|
<input type="checkbox" name="all" value="1" <%= showAll ? 'checked' : '' %> onchange="this.form.submit()">
|
||||||
|
Показать нет в наличии
|
||||||
|
</label>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<% if (recentProducts && recentProducts.length) { %>
|
||||||
|
<section class="recently-viewed">
|
||||||
|
<h2 class="recently-viewed__title">Вы недавно смотрели</h2>
|
||||||
|
<div class="recently-viewed__grid">
|
||||||
|
<% recentProducts.forEach(p => { %>
|
||||||
|
<a href="/product/<%= p.slug %>" class="recently-viewed__card card">
|
||||||
|
<% if (p.image_url) { %>
|
||||||
|
<img src="<%= p.image_url %>" alt="" class="recently-viewed__img" loading="lazy">
|
||||||
|
<% } %>
|
||||||
|
<span class="recently-viewed__name"><%= p.name %></span>
|
||||||
|
</a>
|
||||||
|
<% }) %>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
<% if (!products.length) { %>
|
<% if (!products.length) { %>
|
||||||
<p class="empty">Товары не найдены. Попробуйте другой запрос.</p>
|
<p class="empty">Товары не найдены. Попробуйте другой запрос.</p>
|
||||||
<% } else { %>
|
<% } else { %>
|
||||||
<div class="grid">
|
<div class="grid">
|
||||||
<% products.forEach(p => { %>
|
<% products.forEach(p => { %>
|
||||||
<article class="card">
|
<% const onSale = isSaleActive(p); %>
|
||||||
|
<% const outOfStock = p.stock <= 0; %>
|
||||||
|
<% const lowStock = !outOfStock && p.stock <= 5; %>
|
||||||
|
<article class="card<%= onSale ? ' card--sale' : '' %><%= outOfStock ? ' card--out-of-stock' : '' %>">
|
||||||
<a href="/product/<%= p.slug %>" class="card__image-wrap">
|
<a href="/product/<%= p.slug %>" class="card__image-wrap">
|
||||||
|
<% if (onSale) { %>
|
||||||
|
<span class="card__sale-ribbon" aria-hidden="true">
|
||||||
|
<%- include('partials/icon', { name: 'tag', iconSize: 14 }) %>
|
||||||
|
−<%= salePercent(p) %>%
|
||||||
|
</span>
|
||||||
|
<% } %>
|
||||||
|
<% if (lowStock) { %>
|
||||||
|
<span class="card__stock-badge">Осталось <%= p.stock %></span>
|
||||||
|
<% } %>
|
||||||
|
<% if (outOfStock) { %>
|
||||||
|
<span class="card__stock-badge card__stock-badge--out">Нет в наличии</span>
|
||||||
|
<% } %>
|
||||||
<% if (p.image_url) { %>
|
<% if (p.image_url) { %>
|
||||||
<img src="<%= p.image_url %>" alt="<%= p.name %>" class="card__image" loading="lazy">
|
<img src="<%= p.image_url %>" alt="<%= p.name %>" class="card__image" loading="lazy">
|
||||||
<% } else { %>
|
<% } else { %>
|
||||||
@@ -32,12 +97,19 @@
|
|||||||
<span class="card__category"><%= p.category_name %></span>
|
<span class="card__category"><%= p.category_name %></span>
|
||||||
<% } %>
|
<% } %>
|
||||||
<h2 class="card__title"><a href="/product/<%= p.slug %>"><%= p.name %></a></h2>
|
<h2 class="card__title"><a href="/product/<%= p.slug %>"><%= p.name %></a></h2>
|
||||||
<p class="card__price"><%= formatPrice(p.price_cents) %></p>
|
<%- include('partials/product-price', { product: p, priceSize: 'md' }) %>
|
||||||
|
<% if (!outOfStock) { %>
|
||||||
<form action="/cart/add" method="post" class="card__form">
|
<form action="/cart/add" method="post" class="card__form">
|
||||||
<input type="hidden" name="product_id" value="<%= p.id %>">
|
<input type="hidden" name="product_id" value="<%= p.id %>">
|
||||||
<input type="hidden" name="redirect" value="/cart">
|
<input type="hidden" name="redirect" value="/cart">
|
||||||
<button type="submit" class="btn btn--primary btn--block">В корзину</button>
|
<button type="submit" class="btn btn--primary btn--block">
|
||||||
|
<%- include('partials/icon', { name: 'cart', iconSize: 18 }) %>
|
||||||
|
В корзину
|
||||||
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
<% } else { %>
|
||||||
|
<a href="/product/<%= p.slug %>" class="btn btn--ghost btn--block">Подробнее</a>
|
||||||
|
<% } %>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
<% }) %>
|
<% }) %>
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
Пароль
|
Пароль
|
||||||
<input type="password" name="password" class="input" required autocomplete="current-password">
|
<input type="password" name="password" class="input" required autocomplete="current-password">
|
||||||
</label>
|
</label>
|
||||||
|
<%- include('partials/captcha-widget') %>
|
||||||
<button type="submit" class="btn btn--primary btn--block">Войти по паролю</button>
|
<button type="submit" class="btn btn--primary btn--block">Войти по паролю</button>
|
||||||
<p class="form-footer">
|
<p class="form-footer">
|
||||||
<a href="/forgot-password">Забыли пароль?</a><br>
|
<a href="/forgot-password">Забыли пароль?</a><br>
|
||||||
|
|||||||
+13
-1
@@ -22,7 +22,19 @@
|
|||||||
</li>
|
</li>
|
||||||
<% }) %>
|
<% }) %>
|
||||||
</ul>
|
</ul>
|
||||||
<p class="checkout-total">Итого: <strong><%= formatPrice(order.total_cents) %></strong></p>
|
<% const subtotal = order.subtotal_cents != null ? order.subtotal_cents : order.total_cents; %>
|
||||||
|
<% if (order.discount_cents > 0) { %>
|
||||||
|
<dl class="cart-summary__dl">
|
||||||
|
<dt>Товары</dt>
|
||||||
|
<dd><%= formatPrice(subtotal) %></dd>
|
||||||
|
<dt>Скидка</dt>
|
||||||
|
<dd class="cart-summary__discount">−<%= formatPrice(order.discount_cents) %></dd>
|
||||||
|
</dl>
|
||||||
|
<% } %>
|
||||||
|
<% if (order.loyalty_points_earned > 0) { %>
|
||||||
|
<p class="muted">Начислено баллов лояльности: +<%= order.loyalty_points_earned %></p>
|
||||||
|
<% } %>
|
||||||
|
<p class="checkout-total">К оплате: <strong><%= formatPrice(order.total_cents) %></strong></p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p><a href="/orders" class="link-back">← Все заказы</a></p>
|
<p><a href="/orders" class="link-back">← Все заказы</a></p>
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<%
|
||||||
|
const nav = typeof adminNav !== 'undefined' ? adminNav : '';
|
||||||
|
function navClass(id) {
|
||||||
|
return 'admin-nav__link' + (nav === id ? ' admin-nav__link--active' : '');
|
||||||
|
}
|
||||||
|
%>
|
||||||
|
<nav class="admin-nav">
|
||||||
|
<a href="/admin" class="<%= navClass('dashboard') %>">Обзор</a>
|
||||||
|
<a href="/admin/orders" class="<%= navClass('orders') %>">Заказы</a>
|
||||||
|
<a href="/admin/users" class="<%= navClass('users') %>">Пользователи</a>
|
||||||
|
<a href="/admin/products" class="<%= navClass('products') %>">Товары</a>
|
||||||
|
<a href="/admin/promo-codes" class="<%= navClass('promo') %>">Промокоды</a>
|
||||||
|
<a href="/admin/reservations" class="<%= navClass('reservations') %>">Бронирования</a>
|
||||||
|
<a href="/admin/system" class="<%= navClass('system') %>">Обновление</a>
|
||||||
|
<a href="/" class="admin-nav__link">В магазин</a>
|
||||||
|
</nav>
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<aside class="captcha-block" aria-label="Защита от ботов">
|
||||||
|
<p class="captcha-block__yandex-notice">
|
||||||
|
<%- include('icon', { name: 'shield', iconSize: 14 }) %>
|
||||||
|
<%= yandexCaptchaBlockedMsg %>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<% if (captcha && captcha.blocked) { %>
|
||||||
|
<p class="alert alert--error">Капча недоступна: выбран заблокированный провайдер. В .env укажите <code>CAPTCHA_PROVIDER=google</code> или <code>cloudflare</code>.</p>
|
||||||
|
<% } else if (captcha && captcha.enabled) { %>
|
||||||
|
<div class="captcha-widget">
|
||||||
|
<% if (captcha.provider === 'cloudflare') { %>
|
||||||
|
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
|
||||||
|
<div class="cf-turnstile" data-sitekey="<%= captcha.siteKey %>" data-theme="dark"></div>
|
||||||
|
<% } else { %>
|
||||||
|
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
|
||||||
|
<div class="g-recaptcha" data-sitekey="<%= captcha.siteKey %>" data-theme="dark"></div>
|
||||||
|
<% } %>
|
||||||
|
</div>
|
||||||
|
<p class="muted captcha-block__provider">
|
||||||
|
<% if (captcha.provider === 'cloudflare') { %>Проверка: Cloudflare Turnstile<% } else { %>Проверка: Google reCAPTCHA<% } %>
|
||||||
|
</p>
|
||||||
|
<% } %>
|
||||||
|
</aside>
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<%
|
||||||
|
const sz = typeof iconSize !== 'undefined' ? iconSize : 20;
|
||||||
|
const cls = 'icon' + (typeof iconClass !== 'undefined' ? ' ' + iconClass : '');
|
||||||
|
%>
|
||||||
|
<% if (name === 'cart') { %>
|
||||||
|
<svg class="<%= cls %>" width="<%= sz %>" height="<%= sz %>" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>
|
||||||
|
<% } else if (name === 'search') { %>
|
||||||
|
<svg class="<%= cls %>" width="<%= sz %>" height="<%= sz %>" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
|
||||||
|
<% } else if (name === 'tag') { %>
|
||||||
|
<svg class="<%= cls %>" width="<%= sz %>" height="<%= sz %>" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>
|
||||||
|
<% } else if (name === 'user') { %>
|
||||||
|
<svg class="<%= cls %>" width="<%= sz %>" height="<%= sz %>" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
|
||||||
|
<% } else if (name === 'shield') { %>
|
||||||
|
<svg class="<%= cls %>" width="<%= sz %>" height="<%= sz %>" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
|
||||||
|
<% } else if (name === 'plus') { %>
|
||||||
|
<svg class="<%= cls %>" width="<%= sz %>" height="<%= sz %>" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>
|
||||||
|
<% } else if (name === 'trash') { %>
|
||||||
|
<svg class="<%= cls %>" width="<%= sz %>" height="<%= sz %>" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||||
|
<% } else if (name === 'clock') { %>
|
||||||
|
<svg class="<%= cls %>" width="<%= sz %>" height="<%= sz %>" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
|
||||||
|
<% } else if (name === 'arrow-left') { %>
|
||||||
|
<svg class="<%= cls %>" width="<%= sz %>" height="<%= sz %>" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m12 19-7-7 7-7M19 12H5"/></svg>
|
||||||
|
<% } else if (name === 'refresh') { %>
|
||||||
|
<svg class="<%= cls %>" width="<%= sz %>" height="<%= sz %>" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>
|
||||||
|
<% } else if (name === 'download') { %>
|
||||||
|
<svg class="<%= cls %>" width="<%= sz %>" height="<%= sz %>" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
|
||||||
|
<% } else if (name === 'package') { %>
|
||||||
|
<svg class="<%= cls %>" width="<%= sz %>" height="<%= sz %>" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M16.5 9.4 7.55 4.24M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>
|
||||||
|
<% } %>
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
</main>
|
</main>
|
||||||
<footer class="footer">
|
<footer class="footer">
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<p>© <%= new Date().getFullYear() %> Shop · <a href="/cookies/policy">Cookies</a></p>
|
<p>© <%= new Date().getFullYear() %> Shop ·
|
||||||
|
<a href="/orders">Заказы</a> ·
|
||||||
|
<a href="/sitemap.xml">Карта сайта</a> ·
|
||||||
|
<a href="/cookies/policy">Cookies</a>
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
<%- include('cookie-banner') %>
|
<%- include('cookie-banner') %>
|
||||||
|
|||||||
@@ -4,6 +4,9 @@
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title><%= title %> — Shop</title>
|
<title><%= title %> — Shop</title>
|
||||||
|
<% if (typeof metaDescription !== 'undefined' && metaDescription) { %>
|
||||||
|
<meta name="description" content="<%= metaDescription %>">
|
||||||
|
<% } %>
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700;1,9..40,400&display=swap" rel="stylesheet">
|
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700;1,9..40,400&display=swap" rel="stylesheet">
|
||||||
@@ -12,26 +15,40 @@
|
|||||||
<body>
|
<body>
|
||||||
<header class="header">
|
<header class="header">
|
||||||
<div class="container header__inner">
|
<div class="container header__inner">
|
||||||
<a href="/" class="logo">Shop</a>
|
<a href="/" class="logo">
|
||||||
|
<%- include('icon', { name: 'package', iconSize: 22, iconClass: 'logo__icon' }) %>
|
||||||
|
Shop
|
||||||
|
</a>
|
||||||
<form class="search" action="/" method="get">
|
<form class="search" action="/" method="get">
|
||||||
|
<span class="search__icon" aria-hidden="true"><%- include('icon', { name: 'search', iconSize: 18 }) %></span>
|
||||||
<input type="search" name="q" placeholder="Поиск товаров…" value="<%= typeof searchQuery !== 'undefined' ? searchQuery : '' %>" aria-label="Поиск">
|
<input type="search" name="q" placeholder="Поиск товаров…" value="<%= typeof searchQuery !== 'undefined' ? searchQuery : '' %>" aria-label="Поиск">
|
||||||
<button type="submit" class="btn btn--ghost">Найти</button>
|
<button type="submit" class="btn btn--ghost btn--icon-text">Найти</button>
|
||||||
</form>
|
</form>
|
||||||
<nav class="nav">
|
<nav class="nav">
|
||||||
<a href="/cart" class="nav__link nav__cart">
|
<a href="/cart" class="nav__link nav__cart nav__link--icon">
|
||||||
Корзина
|
<%- include('icon', { name: 'cart', iconSize: 18 }) %>
|
||||||
|
<span>Корзина</span>
|
||||||
<% if (cartCount > 0) { %><span class="badge"><%= cartCount %></span><% } %>
|
<% if (cartCount > 0) { %><span class="badge"><%= cartCount %></span><% } %>
|
||||||
</a>
|
</a>
|
||||||
<% if (user) { %>
|
<% if (user) { %>
|
||||||
<% if (typeof isAdmin !== 'undefined' && isAdmin) { %>
|
<% if (typeof isAdmin !== 'undefined' && isAdmin) { %>
|
||||||
<a href="/admin" class="nav__link nav__admin">Админ</a>
|
<a href="/admin" class="nav__link nav__link--icon nav__admin">
|
||||||
|
<%- include('icon', { name: 'shield', iconSize: 18 }) %>
|
||||||
|
<span>Админ</span>
|
||||||
|
</a>
|
||||||
<% } %>
|
<% } %>
|
||||||
<a href="/account" class="nav__link"><%= user.name %></a>
|
<a href="/account" class="nav__link nav__link--icon">
|
||||||
|
<%- include('icon', { name: 'user', iconSize: 18 }) %>
|
||||||
|
<span><%= user.name %></span>
|
||||||
|
</a>
|
||||||
<form action="/logout" method="post" class="inline-form">
|
<form action="/logout" method="post" class="inline-form">
|
||||||
<button type="submit" class="btn btn--ghost btn--sm">Выйти</button>
|
<button type="submit" class="btn btn--ghost btn--sm">Выйти</button>
|
||||||
</form>
|
</form>
|
||||||
<% } else if (cookieConsent) { %>
|
<% } else if (cookieConsent) { %>
|
||||||
<a href="/login" class="nav__link">Вход</a>
|
<a href="/login" class="nav__link nav__link--icon">
|
||||||
|
<%- include('icon', { name: 'user', iconSize: 18 }) %>
|
||||||
|
<span>Вход</span>
|
||||||
|
</a>
|
||||||
<a href="/register" class="btn btn--primary btn--sm">Регистрация</a>
|
<a href="/register" class="btn btn--primary btn--sm">Регистрация</a>
|
||||||
<% } else { %>
|
<% } else { %>
|
||||||
<span class="nav__link nav__link--disabled" title="Примите cookies">Вход</span>
|
<span class="nav__link nav__link--disabled" title="Примите cookies">Вход</span>
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<%
|
||||||
|
const onSale = typeof forceOnSale !== 'undefined'
|
||||||
|
? forceOnSale
|
||||||
|
: (typeof isSaleActive === 'function' && isSaleActive(product));
|
||||||
|
const eff = typeof forceEffective !== 'undefined'
|
||||||
|
? forceEffective
|
||||||
|
: (typeof effectivePrice === 'function' ? effectivePrice(product) : product.price_cents);
|
||||||
|
const oldCents = product.price_cents;
|
||||||
|
const pct = onSale && typeof salePercent === 'function'
|
||||||
|
? salePercent(product)
|
||||||
|
: (onSale && oldCents ? Math.round(((oldCents - eff) / oldCents) * 100) : 0);
|
||||||
|
const sizeMod = typeof priceSize !== 'undefined' ? ' price-block--' + priceSize : '';
|
||||||
|
%>
|
||||||
|
<div class="price-block<%= sizeMod %><%= onSale ? ' price-block--sale' : '' %>" role="group" aria-label="<%= onSale ? 'Цена со скидкой' : 'Цена' %>">
|
||||||
|
<% if (onSale) { %>
|
||||||
|
<div class="price-block__meta">
|
||||||
|
<span class="price-block__tag">
|
||||||
|
<%- include('icon', { name: 'tag', iconSize: 12 }) %>
|
||||||
|
Акция
|
||||||
|
</span>
|
||||||
|
<span class="price-block__badge">−<%= pct %>%</span>
|
||||||
|
</div>
|
||||||
|
<div class="price-block__prices">
|
||||||
|
<span class="price-block__old" aria-label="Старая цена"><%= formatPrice(oldCents) %></span>
|
||||||
|
<span class="price-block__current" aria-label="Цена со скидкой"><%= formatPrice(eff) %></span>
|
||||||
|
</div>
|
||||||
|
<% if (typeof showSavings !== 'undefined' && showSavings) { %>
|
||||||
|
<span class="price-block__savings">Экономия <%= formatPrice(oldCents - eff) %></span>
|
||||||
|
<% } %>
|
||||||
|
<% } else { %>
|
||||||
|
<span class="price-block__current price-block__current--solo"><%= formatPrice(oldCents) %></span>
|
||||||
|
<% } %>
|
||||||
|
</div>
|
||||||
+21
-3
@@ -13,7 +13,15 @@
|
|||||||
<a href="/?category=<%= product.category_slug %>" class="card__category"><%= product.category_name %></a>
|
<a href="/?category=<%= product.category_slug %>" class="card__category"><%= product.category_name %></a>
|
||||||
<% } %>
|
<% } %>
|
||||||
<h1><%= product.name %></h1>
|
<h1><%= product.name %></h1>
|
||||||
<p class="product-detail__price"><%= formatPrice(product.price_cents) %></p>
|
<div class="product-detail__price">
|
||||||
|
<%- include('partials/product-price', { product, priceSize: 'lg', showSavings: true }) %>
|
||||||
|
<% if (isSaleActive(product) && product.sale_ends_at) { %>
|
||||||
|
<p class="promo-countdown promo-countdown--product" data-expires="<%= product.sale_ends_at %>">
|
||||||
|
<%- include('partials/icon', { name: 'clock', iconSize: 16 }) %>
|
||||||
|
<span>Акция заканчивается: <strong class="promo-countdown__timer">—</strong></span>
|
||||||
|
</p>
|
||||||
|
<% } %>
|
||||||
|
</div>
|
||||||
<p class="product-detail__desc"><%= product.description %></p>
|
<p class="product-detail__desc"><%= product.description %></p>
|
||||||
<p class="product-detail__stock">В наличии: <strong><%= product.stock %></strong> шт.</p>
|
<p class="product-detail__stock">В наличии: <strong><%= product.stock %></strong> шт.</p>
|
||||||
|
|
||||||
@@ -36,7 +44,10 @@
|
|||||||
<input type="number" name="quantity" value="1" min="1" max="<%= product.stock %>" class="input input--qty">
|
<input type="number" name="quantity" value="1" min="1" max="<%= product.stock %>" class="input input--qty">
|
||||||
</label>
|
</label>
|
||||||
<input type="hidden" name="redirect" value="/cart">
|
<input type="hidden" name="redirect" value="/cart">
|
||||||
<button type="submit" class="btn btn--primary btn--lg">Добавить в корзину</button>
|
<button type="submit" class="btn btn--primary btn--lg">
|
||||||
|
<%- include('partials/icon', { name: 'cart', iconSize: 20 }) %>
|
||||||
|
Добавить в корзину
|
||||||
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<% if (user && !userReservation) { %>
|
<% if (user && !userReservation) { %>
|
||||||
@@ -80,8 +91,15 @@
|
|||||||
</section>
|
</section>
|
||||||
<% } %>
|
<% } %>
|
||||||
<% } %>
|
<% } %>
|
||||||
<a href="/" class="link-back">← Назад в каталог</a>
|
<a href="/" class="link-back">
|
||||||
|
<%- include('partials/icon', { name: 'arrow-left', iconSize: 16 }) %>
|
||||||
|
Назад в каталог
|
||||||
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
|
|
||||||
|
<% if (isSaleActive(product) && product.sale_ends_at) { %>
|
||||||
|
<script src="/js/promo-countdown.js"></script>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
<%- include('partials/layout-end') %>
|
<%- include('partials/layout-end') %>
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
Повторите пароль
|
Повторите пароль
|
||||||
<input type="password" name="password2" class="input" required>
|
<input type="password" name="password2" class="input" required>
|
||||||
</label>
|
</label>
|
||||||
|
<%- include('partials/captcha-widget') %>
|
||||||
<button type="submit" class="btn btn--primary btn--block">Создать аккаунт</button>
|
<button type="submit" class="btn btn--primary btn--block">Создать аккаунт</button>
|
||||||
<p class="form-footer">Уже есть аккаунт? <a href="/login">Войти</a></p>
|
<p class="form-footer">Уже есть аккаунт? <a href="/login">Войти</a></p>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
+9
-1
@@ -1,6 +1,6 @@
|
|||||||
# Shop — документация
|
# Shop — документация
|
||||||
|
|
||||||
Интернет-магазин на **Node.js** и **PostgreSQL 17**.
|
Интернет-магазин на **Node.js** и **PostgreSQL 17**. Текущий релиз: **v1.0.1** (см. [CHANGELOG](../CHANGELOG.md), [RELEASE-1.0.1](../docs/RELEASE-1.0.1.md)).
|
||||||
|
|
||||||
## Способы установки
|
## Способы установки
|
||||||
|
|
||||||
@@ -25,6 +25,14 @@
|
|||||||
|
|
||||||
Админ-панель доступна только этому аккаунту.
|
Админ-панель доступна только этому аккаунту.
|
||||||
|
|
||||||
|
## Установщик
|
||||||
|
|
||||||
|
Интерактивно: админ, PostgreSQL, Docker или Ubuntu:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash scripts/install.sh
|
||||||
|
```
|
||||||
|
|
||||||
## Быстрый старт
|
## Быстрый старт
|
||||||
|
|
||||||
### Docker
|
### Docker
|
||||||
|
|||||||
@@ -17,6 +17,26 @@ test -f "$SHOP_ROOT/package.json" && echo OK || echo "Неверный SHOP_ROOT
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Интерактивный установщик (рекомендуется)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd "$SHOP_ROOT"
|
||||||
|
bash scripts/install.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Скрипт спросит:
|
||||||
|
|
||||||
|
1. **Docker** или **Ubuntu без Docker**
|
||||||
|
2. Email, имя и пароль **администратора**
|
||||||
|
3. Пользователь, пароль и имя базы **PostgreSQL**
|
||||||
|
4. **URL сайта**, секрет сессий (можно сгенерировать)
|
||||||
|
5. Опционально **SMTP**
|
||||||
|
6. Для Docker — порт и включить ли **Caddy**
|
||||||
|
|
||||||
|
Создаётся файл `.env`, затем запускается `docker compose` или `systemd`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Первая установка (Ubuntu, без Docker)
|
## Первая установка (Ubuntu, без Docker)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -73,7 +93,8 @@ bash scripts/server-update.sh
|
|||||||
|
|
||||||
| Скрипт | Назначение |
|
| Скрипт | Назначение |
|
||||||
|--------|------------|
|
|--------|------------|
|
||||||
| `quick-deploy-ubuntu.sh` | Первая установка / полный цикл |
|
| `install.sh` | **Интерактивная установка** (Docker или Ubuntu) |
|
||||||
|
| `quick-deploy-ubuntu.sh` | Первая установка / полный цикл (без вопросов) |
|
||||||
| `server-update.sh` | `git pull`, `npm install`, перезапуск shop |
|
| `server-update.sh` | `git pull`, `npm install`, перезапуск shop |
|
||||||
| `git-sync.sh` | Исправить detached HEAD, синхронизация с `main` |
|
| `git-sync.sh` | Исправить detached HEAD, синхронизация с `main` |
|
||||||
| `install-postgresql-ubuntu.sh` | PostgreSQL 17 через PGDG |
|
| `install-postgresql-ubuntu.sh` | PostgreSQL 17 через PGDG |
|
||||||
|
|||||||
@@ -38,6 +38,9 @@ journalctl -u shop -n 50 --no-pager
|
|||||||
| Placeholder / `URL_РЕПОЗИТОРИЯ` | `git clone <ваш-url> "$SHOP_ROOT"` — не копировать шаблоны как команды |
|
| Placeholder / `URL_РЕПОЗИТОРИЯ` | `git clone <ваш-url> "$SHOP_ROOT"` — не копировать шаблоны как команды |
|
||||||
| Нет `package.json` | `find /opt -name package.json`; `cd` в найденный каталог |
|
| Нет `package.json` | `find /opt -name package.json`; `cd` в найденный каталог |
|
||||||
| detached HEAD | `bash scripts/git-sync.sh` |
|
| detached HEAD | `bash scripts/git-sync.sh` |
|
||||||
|
| `EACCES` на `package-lock.json`, npm от www-data | `sudo bash scripts/fix-shop-permissions.sh` затем `sudo npm install --omit=dev` и снова `fix-shop-permissions` |
|
||||||
|
| `shop.service` failed после обновления | `sudo bash scripts/fix-shop-permissions.sh` && `sudo systemctl restart shop` |
|
||||||
|
| `status=203/EXEC` на `wait-postgres.sh` | `chmod +x scripts/*.sh`; `sed -i 's/\r$//' scripts/*.sh`; в unit: `ExecStartPre=+/bin/bash .../wait-postgres.sh`; `sudo bash scripts/install-shop-service.sh` |
|
||||||
| Нет `scripts/...` | `bash "$SHOP_ROOT/scripts/server-update.sh"` |
|
| Нет `scripts/...` | `bash "$SHOP_ROOT/scripts/server-update.sh"` |
|
||||||
| Unit shop not found | `sudo bash scripts/install-shop-service.sh` |
|
| Unit shop not found | `sudo bash scripts/install-shop-service.sh` |
|
||||||
| shop exit-code / auto-restart | `sudo bash scripts/free-port-3000.sh`; `systemctl restart shop` |
|
| shop exit-code / auto-restart | `sudo bash scripts/free-port-3000.sh`; `systemctl restart shop` |
|
||||||
|
|||||||
Reference in New Issue
Block a user