Compare commits
9 Commits
9b688b2af4
...
v1.0.1
| Author | SHA1 | Date | |
|---|---|---|---|
| c5e8653b30 | |||
| 9025677fd8 | |||
| f9f0446c12 | |||
| 4c37f4ac1a | |||
| d4166ec62a | |||
| af2901152d | |||
| 69dfd2a93a | |||
| d4dd1fb587 | |||
| 0c2cee410f |
@@ -13,6 +13,14 @@ ADMIN_NAME=Администратор
|
||||
# URL сайта (ссылки в письмах, WebAuthn origin)
|
||||
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
|
||||
# WEBAUTHN_RP_ID=shop.example.com
|
||||
# WEBAUTHN_RP_NAME=Shop
|
||||
@@ -26,6 +34,12 @@ SMTP_USER=
|
||||
SMTP_PASS=
|
||||
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
|
||||
|
||||
# PostgreSQL 17 (одна строка или отдельные переменные)
|
||||
DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop
|
||||
# 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"
|
||||
```
|
||||
@@ -1,5 +1,59 @@
|
||||
# Changelog
|
||||
|
||||
## [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
|
||||
|
||||
### Роли и администрирование
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Shop
|
||||
|
||||
**v0.20.0** — интернет-магазин на **Node.js** и **PostgreSQL 17**.
|
||||
**v1.0.1** — интернет-магазин на **Node.js** и **PostgreSQL 17**.
|
||||
|
||||
Два способа установки: [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)
|
||||
|
||||
@@ -361,19 +361,22 @@ scripts/
|
||||
src/
|
||||
```
|
||||
|
||||
## Релиз 0.20.0
|
||||
## Релиз 1.0.1
|
||||
|
||||
```bash
|
||||
git clone <URL-вашего-репозитория> /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 | `bash scripts/setup-postgres-ubuntu.sh` → `systemctl start shop` |
|
||||
|
||||
Обновление с **0.20**: `bash "$SHOP_ROOT/scripts/server-update.sh"` или **Админ → Обновление**.
|
||||
|
||||
## Репозиторий
|
||||
|
||||
```bash
|
||||
|
||||
@@ -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",
|
||||
"version": "0.20.0",
|
||||
"version": "1.0.1",
|
||||
"description": "Интернет-магазин на Node.js с PostgreSQL 17",
|
||||
"main": "src/server.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/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)}"
|
||||
|
||||
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 ---"
|
||||
run_as_owner "npm install --omit=dev"
|
||||
|
||||
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 "Готово."
|
||||
@@ -32,3 +32,7 @@ fi
|
||||
|
||||
export SHOP_ROOT
|
||||
cd "$SHOP_ROOT"
|
||||
|
||||
if [ -d "$SHOP_ROOT/.git" ]; then
|
||||
git config --global --add safe.directory "$SHOP_ROOT" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
@@ -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 };
|
||||
+281
-18
@@ -10,6 +10,8 @@
|
||||
--success: #00b894;
|
||||
--warn: #fdcb6e;
|
||||
--error: #ff7675;
|
||||
--sale: #ff6b6b;
|
||||
--sale-bg: rgba(255, 107, 107, 0.12);
|
||||
--radius: 12px;
|
||||
--shadow: 0 8px 32px rgba(0, 0, 0, 0.35);
|
||||
font-family: 'DM Sans', system-ui, sans-serif;
|
||||
@@ -63,6 +65,9 @@ a:hover {
|
||||
}
|
||||
|
||||
.logo {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
font-size: 1.35rem;
|
||||
font-weight: 700;
|
||||
color: var(--text);
|
||||
@@ -70,6 +75,10 @@ a:hover {
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.logo__icon {
|
||||
color: var(--accent-hover);
|
||||
}
|
||||
|
||||
.logo:hover {
|
||||
color: var(--accent-hover);
|
||||
text-decoration: none;
|
||||
@@ -78,13 +87,24 @@ a:hover {
|
||||
.search {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
min-width: 200px;
|
||||
max-width: 420px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.search__icon {
|
||||
position: absolute;
|
||||
left: 0.75rem;
|
||||
color: var(--muted);
|
||||
pointer-events: none;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.search input {
|
||||
flex: 1;
|
||||
padding-left: 2.35rem;
|
||||
}
|
||||
|
||||
.nav {
|
||||
@@ -103,10 +123,25 @@ a:hover {
|
||||
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 {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.nav__admin {
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -144,7 +179,8 @@ a:hover {
|
||||
letter-spacing: -0.03em;
|
||||
}
|
||||
|
||||
.hero p {
|
||||
.hero p,
|
||||
.hero__lead {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
}
|
||||
@@ -185,7 +221,7 @@ a:hover {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
transition: transform 0.2s, box-shadow 0.2s, border-color 0.2s;
|
||||
}
|
||||
|
||||
.card:hover {
|
||||
@@ -193,13 +229,40 @@ a:hover {
|
||||
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 {
|
||||
display: block;
|
||||
position: relative;
|
||||
aspect-ratio: 1;
|
||||
overflow: hidden;
|
||||
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 {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
@@ -240,10 +303,8 @@ a:hover {
|
||||
color: var(--accent-hover);
|
||||
}
|
||||
|
||||
.card__price {
|
||||
margin: 0 0 0.75rem;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 700;
|
||||
.card .price-block {
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.card__form {
|
||||
@@ -272,9 +333,16 @@ a:hover {
|
||||
}
|
||||
|
||||
.product-detail__price {
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
margin: 0.5rem 0;
|
||||
margin: 0.75rem 0 1rem;
|
||||
padding: 1rem 1.15rem;
|
||||
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 {
|
||||
@@ -323,15 +391,29 @@ a:hover {
|
||||
}
|
||||
|
||||
.link-back {
|
||||
display: inline-block;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
margin-top: 1rem;
|
||||
color: var(--muted);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.link-back:hover {
|
||||
color: var(--text);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.icon {
|
||||
flex-shrink: 0;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.45rem;
|
||||
padding: 0.55rem 1.1rem;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
@@ -1008,27 +1090,129 @@ body:has(.cookie-banner) .main {
|
||||
}
|
||||
|
||||
.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.35rem 0.6rem;
|
||||
margin: 0.35rem 0 0;
|
||||
gap: 0.5rem 0.75rem;
|
||||
}
|
||||
|
||||
.price-block__old {
|
||||
text-decoration: line-through;
|
||||
position: relative;
|
||||
color: var(--muted);
|
||||
font-size: 0.9rem;
|
||||
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(--accent);
|
||||
font-weight: 600;
|
||||
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: rgba(239, 68, 68, 0.15);
|
||||
color: #f87171;
|
||||
background: var(--sale-bg);
|
||||
color: var(--sale);
|
||||
font-size: 0.75rem;
|
||||
padding: 0.15rem 0.45rem;
|
||||
border-radius: 4px;
|
||||
@@ -1073,3 +1257,82 @@ body:has(.cookie-banner) .main {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ const { requireAdmin } = require('../middleware/auth');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
const { ROLE_LABELS } = require('../constants/roles');
|
||||
const { notifyIfBackInStock } = require('../services/stock-alerts');
|
||||
const gitDeploy = require('../services/git-deploy');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -349,4 +350,69 @@ router.post(
|
||||
})
|
||||
);
|
||||
|
||||
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;
|
||||
|
||||
@@ -6,6 +6,7 @@ const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||
const { ROLES } = require('../constants/roles');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
const { verifyCaptcha } = require('../services/captcha');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -28,6 +29,15 @@ router.post(
|
||||
const { name, email, password, password2 } = req.body;
|
||||
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) {
|
||||
return res.status(400).render('register', {
|
||||
title: 'Регистрация',
|
||||
@@ -90,6 +100,16 @@ router.post(
|
||||
const next = req.body.next || '/';
|
||||
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', [
|
||||
(email || '').trim().toLowerCase(),
|
||||
]);
|
||||
|
||||
@@ -6,6 +6,7 @@ const { getCart, cartCount } = require('../cart');
|
||||
const { formatPrice } = require('../db');
|
||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
const { verifyCaptcha } = require('../services/captcha');
|
||||
const { sendPasswordResetEmail, siteUrl } = require('../services/mail');
|
||||
|
||||
const router = express.Router();
|
||||
@@ -39,6 +40,16 @@ router.post(
|
||||
const genericSuccess =
|
||||
'Если аккаунт с таким 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) {
|
||||
return res.status(400).render('auth/forgot-password', {
|
||||
title: 'Сброс пароля',
|
||||
|
||||
@@ -10,6 +10,7 @@ const { seedAdmin } = require('./seed-admin');
|
||||
const { seedPromoCodes } = require('./seed-promo');
|
||||
const { loadUser } = require('./middleware/auth');
|
||||
const { loadCookieConsent } = require('./middleware/cookieConsent');
|
||||
const { loadCaptchaLocals, rejectYandexCaptcha } = require('./middleware/captcha');
|
||||
const healthRoutes = require('./routes/health');
|
||||
const shopRoutes = require('./routes/shop');
|
||||
const authRoutes = require('./routes/auth');
|
||||
@@ -68,6 +69,8 @@ async function start() {
|
||||
);
|
||||
|
||||
app.use(loadCookieConsent);
|
||||
app.use(loadCaptchaLocals);
|
||||
app.use(rejectYandexCaptcha);
|
||||
app.use(loadUser);
|
||||
app.use('/cookies', cookiesRoutes);
|
||||
app.use('/', passwordResetRoutes);
|
||||
|
||||
@@ -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,253 @@
|
||||
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 без записи в .git (без fetch) */
|
||||
async function getCommitsBehind(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');
|
||||
}
|
||||
if (remoteSha === localHead) return 0;
|
||||
const count = await gitCmd(['rev-list', '--count', `${localHead}..${remoteSha}`], root);
|
||||
return parseInt(count, 10) || 0;
|
||||
}
|
||||
|
||||
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,
|
||||
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 {
|
||||
info.behind = await getCommitsBehind(root);
|
||||
} 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,
|
||||
};
|
||||
@@ -2,17 +2,15 @@
|
||||
|
||||
<div class="admin-header">
|
||||
<h1>Админ-панель</h1>
|
||||
<nav class="admin-nav">
|
||||
<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/promo-codes" class="admin-nav__link">Промокоды</a>
|
||||
<a href="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
||||
<a href="/" class="admin-nav__link">В магазин</a>
|
||||
</nav>
|
||||
<%- include('../partials/admin-nav', { adminNav: 'dashboard' }) %>
|
||||
</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="stat-card">
|
||||
<span class="stat-card__label">Пользователи</span>
|
||||
|
||||
@@ -2,15 +2,7 @@
|
||||
|
||||
<div class="admin-header">
|
||||
<h1>Заказы</h1>
|
||||
<nav class="admin-nav">
|
||||
<a href="/admin" class="admin-nav__link">Обзор</a>
|
||||
<a href="/admin/orders" class="admin-nav__link admin-nav__link--active">Заказы</a>
|
||||
<a href="/admin/users" class="admin-nav__link">Пользователи</a>
|
||||
<a href="/admin/products" class="admin-nav__link">Товары</a>
|
||||
<a href="/admin/promo-codes" class="admin-nav__link">Промокоды</a>
|
||||
<a href="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
||||
<a href="/" class="admin-nav__link">В магазин</a>
|
||||
</nav>
|
||||
<%- include('../partials/admin-nav', { adminNav: 'orders' }) %>
|
||||
</div>
|
||||
|
||||
<% const statusLabels = { pending: 'Ожидает', paid: 'Оплачен', shipped: 'Отправлен', cancelled: 'Отменён' }; %>
|
||||
|
||||
@@ -2,15 +2,7 @@
|
||||
|
||||
<div class="admin-header">
|
||||
<h1>Товары — цены и скидки</h1>
|
||||
<nav class="admin-nav">
|
||||
<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/promo-codes" class="admin-nav__link">Промокоды</a>
|
||||
<a href="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
||||
<a href="/" class="admin-nav__link">В магазин</a>
|
||||
</nav>
|
||||
<%- include('../partials/admin-nav', { adminNav: 'products' }) %>
|
||||
</div>
|
||||
|
||||
<% if (stockUpdated) { %>
|
||||
|
||||
@@ -2,15 +2,7 @@
|
||||
|
||||
<div class="admin-header">
|
||||
<h1>Промокоды и скидки</h1>
|
||||
<nav class="admin-nav">
|
||||
<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/promo-codes" 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>
|
||||
<%- include('../partials/admin-nav', { adminNav: 'promo' }) %>
|
||||
</div>
|
||||
|
||||
<% if (created) { %><p class="alert alert--success">Промокод создан</p><% } %>
|
||||
|
||||
@@ -2,15 +2,7 @@
|
||||
|
||||
<div class="admin-header">
|
||||
<h1>Бронирования</h1>
|
||||
<nav class="admin-nav">
|
||||
<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/promo-codes" 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>
|
||||
<%- include('../partials/admin-nav', { adminNav: 'reservations' }) %>
|
||||
</div>
|
||||
|
||||
<% const resStatus = { active: 'Активна', fulfilled: 'Выполнена', cancelled: 'Отменена', expired: 'Истекла' }; %>
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
<%- 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.behind > 0) { %>
|
||||
<span class="badge badge--sale">Доступно обновлений: <%= git.behind %></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,15 +2,7 @@
|
||||
|
||||
<div class="admin-header">
|
||||
<h1>Пользователи</h1>
|
||||
<nav class="admin-nav">
|
||||
<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/promo-codes" class="admin-nav__link">Промокоды</a>
|
||||
<a href="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
||||
<a href="/" class="admin-nav__link">В магазин</a>
|
||||
</nav>
|
||||
<%- include('../partials/admin-nav', { adminNav: 'users' }) %>
|
||||
</div>
|
||||
|
||||
<p class="muted admin-hint">
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
Email
|
||||
<input type="email" name="email" class="input" required value="<%= values.email || '' %>" autocomplete="email">
|
||||
</label>
|
||||
<%- include('../partials/captcha-widget') %>
|
||||
<button type="submit" class="btn btn--primary btn--block">Отправить ссылку</button>
|
||||
<p class="form-footer"><a href="/login">← Вход</a></p>
|
||||
</form>
|
||||
|
||||
+10
-8
@@ -29,20 +29,22 @@
|
||||
<% } %>
|
||||
<a href="/product/<%= item.slug %>"><%= item.name %></a>
|
||||
</td>
|
||||
<td>
|
||||
<% if (item.on_sale) { %>
|
||||
<span class="price-block__old"><%= formatPrice(item.price_cents) %></span>
|
||||
<%= formatPrice(item.effective_price_cents) %>
|
||||
<% } else { %>
|
||||
<%= formatPrice(item.effective_price_cents) %>
|
||||
<% } %>
|
||||
<td class="cart-table__price">
|
||||
<%- include('partials/product-price', {
|
||||
product: item,
|
||||
forceOnSale: item.on_sale,
|
||||
forceEffective: item.effective_price_cents,
|
||||
priceSize: 'sm'
|
||||
}) %>
|
||||
</td>
|
||||
<td>
|
||||
<input type="number" name="items[<%= item.id %>]" value="<%= item.quantity %>" min="0" max="<%= item.stock %>" class="input input--qty">
|
||||
</td>
|
||||
<td><%= formatPrice(item.line_total) %></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>
|
||||
</tr>
|
||||
<% }) %>
|
||||
|
||||
+14
-4
@@ -2,7 +2,7 @@
|
||||
|
||||
<section class="hero">
|
||||
<h1>Каталог товаров</h1>
|
||||
<p>Доставка по России. Оплата при получении.</p>
|
||||
<p class="hero__lead">Доставка по России · Оплата при получении · Акции со скидкой в каталоге</p>
|
||||
</section>
|
||||
|
||||
<% if (categories.length) { %>
|
||||
@@ -19,8 +19,15 @@
|
||||
<% } else { %>
|
||||
<div class="grid">
|
||||
<% products.forEach(p => { %>
|
||||
<article class="card">
|
||||
<% const onSale = isSaleActive(p); %>
|
||||
<article class="card<%= onSale ? ' card--sale' : '' %>">
|
||||
<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 (p.image_url) { %>
|
||||
<img src="<%= p.image_url %>" alt="<%= p.name %>" class="card__image" loading="lazy">
|
||||
<% } else { %>
|
||||
@@ -32,11 +39,14 @@
|
||||
<span class="card__category"><%= p.category_name %></span>
|
||||
<% } %>
|
||||
<h2 class="card__title"><a href="/product/<%= p.slug %>"><%= p.name %></a></h2>
|
||||
<%- include('partials/product-price', { product: p }) %>
|
||||
<%- include('partials/product-price', { product: p, priceSize: 'md' }) %>
|
||||
<form action="/cart/add" method="post" class="card__form">
|
||||
<input type="hidden" name="product_id" value="<%= p.id %>">
|
||||
<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>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
Пароль
|
||||
<input type="password" name="password" class="input" required autocomplete="current-password">
|
||||
</label>
|
||||
<%- include('partials/captcha-widget') %>
|
||||
<button type="submit" class="btn btn--primary btn--block">Войти по паролю</button>
|
||||
<p class="form-footer">
|
||||
<a href="/forgot-password">Забыли пароль?</a><br>
|
||||
|
||||
@@ -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>
|
||||
<% } %>
|
||||
@@ -12,26 +12,40 @@
|
||||
<body>
|
||||
<header class="header">
|
||||
<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">
|
||||
<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="Поиск">
|
||||
<button type="submit" class="btn btn--ghost">Найти</button>
|
||||
<button type="submit" class="btn btn--ghost btn--icon-text">Найти</button>
|
||||
</form>
|
||||
<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><% } %>
|
||||
</a>
|
||||
<% if (user) { %>
|
||||
<% 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">
|
||||
<button type="submit" class="btn btn--ghost btn--sm">Выйти</button>
|
||||
</form>
|
||||
<% } 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>
|
||||
<% } else { %>
|
||||
<span class="nav__link nav__link--disabled" title="Примите cookies">Вход</span>
|
||||
|
||||
@@ -1,11 +1,33 @@
|
||||
<% const onSale = typeof isSaleActive === 'function' && isSaleActive(product); %>
|
||||
<% const eff = typeof effectivePrice === 'function' ? effectivePrice(product) : product.price_cents; %>
|
||||
<p class="price-block<%= onSale ? ' price-block--sale' : '' %>">
|
||||
<%
|
||||
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) { %>
|
||||
<span class="price-block__old"><%= formatPrice(product.price_cents) %></span>
|
||||
<span class="price-block__current"><%= formatPrice(eff) %></span>
|
||||
<span class="badge badge--sale">−<%= salePercent(product) %>%</span>
|
||||
<% } else { %>
|
||||
<span class="price-block__current"><%= formatPrice(product.price_cents) %></span>
|
||||
<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>
|
||||
<% } %>
|
||||
</p>
|
||||
<% } else { %>
|
||||
<span class="price-block__current price-block__current--solo"><%= formatPrice(oldCents) %></span>
|
||||
<% } %>
|
||||
</div>
|
||||
|
||||
+13
-6
@@ -14,11 +14,12 @@
|
||||
<% } %>
|
||||
<h1><%= product.name %></h1>
|
||||
<div class="product-detail__price">
|
||||
<%- include('partials/product-price', { product }) %>
|
||||
<%- include('partials/product-price', { product, priceSize: 'lg', showSavings: true }) %>
|
||||
<% if (isSaleActive(product) && product.sale_ends_at) { %>
|
||||
<div class="promo-countdown" data-expires="<%= product.sale_ends_at %>">
|
||||
Акция заканчивается: <span class="promo-countdown__timer">—</span>
|
||||
</div>
|
||||
<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>
|
||||
@@ -43,7 +44,10 @@
|
||||
<input type="number" name="quantity" value="1" min="1" max="<%= product.stock %>" class="input input--qty">
|
||||
</label>
|
||||
<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>
|
||||
|
||||
<% if (user && !userReservation) { %>
|
||||
@@ -87,7 +91,10 @@
|
||||
</section>
|
||||
<% } %>
|
||||
<% } %>
|
||||
<a href="/" class="link-back">← Назад в каталог</a>
|
||||
<a href="/" class="link-back">
|
||||
<%- include('partials/icon', { name: 'arrow-left', iconSize: 16 }) %>
|
||||
Назад в каталог
|
||||
</a>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
Повторите пароль
|
||||
<input type="password" name="password2" class="input" required>
|
||||
</label>
|
||||
<%- include('partials/captcha-widget') %>
|
||||
<button type="submit" class="btn btn--primary btn--block">Создать аккаунт</button>
|
||||
<p class="form-footer">Уже есть аккаунт? <a href="/login">Войти</a></p>
|
||||
</form>
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# 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)).
|
||||
|
||||
## Способы установки
|
||||
|
||||
|
||||
Reference in New Issue
Block a user