Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9b688b2af4 | |||
| db4bc9bfe1 | |||
| dedef454c8 | |||
| 42a1ca312f | |||
| ed9850c96f | |||
| e2a7c79245 | |||
| 561fbd22e0 | |||
| d31a63829c | |||
| f13ec7f29a | |||
| b44419aebd | |||
| da77b1f8da | |||
| b7c8d2ed80 | |||
| 42177555ac | |||
| e71bfa35dc | |||
| 711110c03b |
+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
|
||||||
|
|||||||
+8
-2
@@ -4,14 +4,20 @@ NODE_ENV=production
|
|||||||
TRUST_PROXY=1
|
TRUST_PROXY=1
|
||||||
SESSION_SECRET=change-me-to-a-long-random-string
|
SESSION_SECRET=change-me-to-a-long-random-string
|
||||||
|
|
||||||
# Первый администратор (создаётся при старте, если email не занят)
|
# Единственный администратор (зарегистрированный пользователь с этим email)
|
||||||
|
# При регистрации через сайт все получают роль customer; admin — только этот аккаунт
|
||||||
ADMIN_EMAIL=admin@site.com
|
ADMIN_EMAIL=admin@site.com
|
||||||
ADMIN_PASSWORD=admin
|
ADMIN_PASSWORD=admin
|
||||||
ADMIN_NAME=Администратор
|
ADMIN_NAME=Администратор
|
||||||
|
|
||||||
# URL сайта (ссылки в письмах)
|
# URL сайта (ссылки в письмах, WebAuthn origin)
|
||||||
SITE_URL=http://localhost:3000
|
SITE_URL=http://localhost:3000
|
||||||
|
|
||||||
|
# Passkey (WebAuthn) — по умолчанию hostname из SITE_URL
|
||||||
|
# WEBAUTHN_RP_ID=shop.example.com
|
||||||
|
# WEBAUTHN_RP_NAME=Shop
|
||||||
|
# WEBAUTHN_ORIGIN=https://shop.example.com,http://localhost:3000
|
||||||
|
|
||||||
# SMTP — сброс пароля и уведомления о брони
|
# SMTP — сброс пароля и уведомления о брони
|
||||||
SMTP_HOST=smtp.example.com
|
SMTP_HOST=smtp.example.com
|
||||||
SMTP_PORT=587
|
SMTP_PORT=587
|
||||||
|
|||||||
@@ -6,16 +6,18 @@
|
|||||||
|
|
||||||
Подробности релиза: [CHANGELOG.md](CHANGELOG.md) · [docs/RELEASE-0.20.md](docs/RELEASE-0.20.md)
|
Подробности релиза: [CHANGELOG.md](CHANGELOG.md) · [docs/RELEASE-0.20.md](docs/RELEASE-0.20.md)
|
||||||
|
|
||||||
**Wiki (установка):** https://git.evilfox.cc/test/shop10/wiki
|
**Сервер (установка, обновление, ошибки):** [wiki/Server-Operations.md](wiki/Server-Operations.md) · [wiki/Troubleshooting.md](wiki/Troubleshooting.md)
|
||||||
|
|
||||||
## Возможности
|
## Возможности
|
||||||
|
|
||||||
- Каталог товаров с категориями и поиском
|
- Каталог товаров с категориями и поиском
|
||||||
- Корзина и оформление заказа
|
- Корзина и оформление заказа
|
||||||
- Регистрация, вход, сброс пароля по email
|
- Регистрация, вход (пароль или passkey), сброс пароля по email
|
||||||
- Личный кабинет: профиль, бронирования
|
- Личный кабинет: профиль, бронирования
|
||||||
- Роли клиент / администратор, админ-панель
|
- Роли: клиент (`customer`) и **один** администратор (`admin`) — аккаунт из `ADMIN_EMAIL` в `.env`
|
||||||
- Согласие на cookies
|
- Согласие на cookies
|
||||||
|
- Подписка «сообщить о поступлении», если товара нет в наличии
|
||||||
|
- Лояльность (баллы), промокоды со скидкой и таймером до конца акции
|
||||||
|
|
||||||
## Требования
|
## Требования
|
||||||
|
|
||||||
@@ -100,7 +102,7 @@ apt install -y postgresql-17 postgresql-client-17
|
|||||||
Пользователь и база `shop`:
|
Пользователь и база `shop`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /opt/shop
|
cd "$SHOP_ROOT"
|
||||||
bash scripts/setup-postgres-ubuntu.sh
|
bash scripts/setup-postgres-ubuntu.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -110,36 +112,46 @@ bash scripts/setup-postgres-ubuntu.sh
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Быстрый развёртывание на Ubuntu
|
## Интерактивный установщик
|
||||||
|
|
||||||
|
Задаёт вопросы: **Docker или Ubuntu**, данные **администратора**, **PostgreSQL**, URL сайта, опционально SMTP.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 1. Система + Node.js 20
|
cd /path/to/shop
|
||||||
apt update
|
bash scripts/install.sh
|
||||||
apt install -y git curl
|
|
||||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
|
||||||
apt install -y nodejs
|
|
||||||
|
|
||||||
# 2. PostgreSQL 17
|
|
||||||
apt install -y postgresql-17 postgresql-client-17
|
|
||||||
|
|
||||||
# 3. Код
|
|
||||||
cd /opt
|
|
||||||
git clone <URL_РЕПОЗИТОРИЯ> shop
|
|
||||||
cd shop
|
|
||||||
|
|
||||||
# 4. БД
|
|
||||||
bash scripts/setup-postgres-ubuntu.sh
|
|
||||||
|
|
||||||
# 5. Окружение
|
|
||||||
cp .env.example .env
|
|
||||||
sed -i "s/change-me-to-a-long-random-string/$(openssl rand -hex 32)/" .env
|
|
||||||
# Проверьте DATABASE_URL в .env
|
|
||||||
|
|
||||||
# 6. Приложение
|
|
||||||
npm install --omit=dev
|
|
||||||
npm start
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Нативная установка на сервере — от root: `sudo bash scripts/install.sh`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Быстрый развёртывание на Ubuntu
|
||||||
|
|
||||||
|
Подставьте **URL своего репозитория** и каталог клона `SHOP_ROOT` (часто `/opt/shop`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export SHOP_ROOT=/opt/shop
|
||||||
|
export SHOP_GIT_URL='https://ваш-forge/пользователь/shop.git'
|
||||||
|
|
||||||
|
apt update && apt install -y git curl
|
||||||
|
git clone "$SHOP_GIT_URL" "$SHOP_ROOT"
|
||||||
|
cd "$SHOP_ROOT"
|
||||||
|
sudo SHOP_INSTALL_DIR="$SHOP_ROOT" SHOP_GIT_URL="$SHOP_GIT_URL" bash scripts/quick-deploy-ubuntu.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
**Обновление** (сайт уже работает) — **лучше так** (из любого каталога):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export SHOP_ROOT=/opt/shop/shop10
|
||||||
|
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||||
|
```
|
||||||
|
|
||||||
|
`SHOP_ROOT` — путь к клону с `package.json` (у вас может быть `/opt/shop` вместо `/opt/shop/shop10`).
|
||||||
|
|
||||||
|
Не копируйте в shell шаблоны вроде `<URL_РЕПОЗИТОРИЯ>` — это подсказки в тексте, не команды.
|
||||||
|
|
||||||
|
Подробно: **[wiki/Server-Operations.md](wiki/Server-Operations.md)** (PostgreSQL PGDG, git, systemd, порт 3000).
|
||||||
|
|
||||||
Проверка:
|
Проверка:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -163,28 +175,31 @@ DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop
|
|||||||
| `DATABASE_URL` | Строка подключения PostgreSQL |
|
| `DATABASE_URL` | Строка подключения PostgreSQL |
|
||||||
| `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE` | Альтернатива `DATABASE_URL` |
|
| `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE` | Альтернатива `DATABASE_URL` |
|
||||||
| `HOST` | `127.0.0.1` в production (доступ через Caddy) |
|
| `HOST` | `127.0.0.1` в production (доступ через Caddy) |
|
||||||
|
| `ADMIN_EMAIL` | Email **единственного** администратора (создаётся/обновляется при старте) |
|
||||||
|
| `ADMIN_PASSWORD` | Пароль администратора (только при первом создании аккаунта) |
|
||||||
|
| `ADMIN_NAME` | Имя администратора |
|
||||||
|
|
||||||
|
### Роли и администратор
|
||||||
|
|
||||||
|
- Через **регистрацию** на сайте все пользователи получают роль **клиент** (`customer`).
|
||||||
|
- **Один** зарегистрированный пользователь — **администратор**: аккаунт с email из `ADMIN_EMAIL` (по умолчанию `admin@site.com`). При старте приложения он создаётся, если ещё нет, или ему назначается роль `admin`.
|
||||||
|
- Админ-панель: `/admin` (кнопка в шапке и в личном кабинете — только у администратора).
|
||||||
|
- Сменить администратора: укажите другой email в `ADMIN_EMAIL` и перезапустите shop (прежние admin-аккаунты станут клиентами).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Запуск как служба (systemd)
|
## Запуск как служба (systemd)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cp /opt/shop/deploy/shop.service /etc/systemd/system/shop.service
|
cd "$SHOP_ROOT"
|
||||||
|
cp .env.example .env # при первой установке — SESSION_SECRET, DATABASE_URL
|
||||||
cd /opt/shop
|
sudo bash scripts/install-shop-service.sh
|
||||||
cp .env.example .env # при первой установке
|
|
||||||
# Заполните SESSION_SECRET и DATABASE_URL
|
|
||||||
|
|
||||||
npm install --omit=dev
|
|
||||||
|
|
||||||
# Не делайте chown -R www-data на весь /opt/shop (ломает git pull)
|
|
||||||
systemctl daemon-reload
|
|
||||||
systemctl enable shop
|
|
||||||
systemctl start shop
|
|
||||||
journalctl -u shop -f
|
journalctl -u shop -f
|
||||||
```
|
```
|
||||||
|
|
||||||
`EnvironmentFile=/opt/shop/.env` должен содержать `DATABASE_URL`.
|
Не делайте `chown -R www-data` на весь каталог репозитория (ломает `git pull`).
|
||||||
|
|
||||||
|
`EnvironmentFile` в unit должен указывать на `$SHOP_ROOT/.env` с `DATABASE_URL`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -203,18 +218,23 @@ journalctl -u shop -n 5 --no-pager
|
|||||||
|
|
||||||
## Обновление на сервере (git pull)
|
## Обновление на сервере (git pull)
|
||||||
|
|
||||||
|
См. **[wiki/Server-Operations.md](wiki/Server-Operations.md)**.
|
||||||
|
|
||||||
|
**Рекомендуемый способ** (надёжнее, чем вручную `cd` и `git pull`):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /opt/shop
|
export SHOP_ROOT=/opt/shop/shop10
|
||||||
git config --global --add safe.directory /opt/shop
|
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||||
bash scripts/server-update.sh
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`WorkingDirectory` в `deploy/shop.service` должен совпадать с `$SHOP_ROOT`.
|
||||||
|
|
||||||
Скрипт: `git pull` → `npm install` → проверка PostgreSQL → `restart shop` → `curl /health` → `reload caddy`.
|
Скрипт: `git pull` → `npm install` → проверка PostgreSQL → `restart shop` → `curl /health` → `reload caddy`.
|
||||||
|
|
||||||
Вручную:
|
Вручную:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /opt/shop
|
cd "$SHOP_ROOT"
|
||||||
git pull
|
git pull
|
||||||
npm install --omit=dev
|
npm install --omit=dev
|
||||||
systemctl restart shop
|
systemctl restart shop
|
||||||
@@ -224,50 +244,6 @@ systemctl reload caddy
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Переход с SQLite на PostgreSQL 17
|
|
||||||
|
|
||||||
Если сервер уже работал на старой версии (файлы `data/*.db`):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 1. PostgreSQL
|
|
||||||
apt install -y postgresql-17 postgresql-client-17
|
|
||||||
systemctl start postgresql
|
|
||||||
|
|
||||||
# 2. Код
|
|
||||||
cd /opt/shop
|
|
||||||
git config --global --add safe.directory /opt/shop
|
|
||||||
git pull
|
|
||||||
|
|
||||||
# 3. База shop
|
|
||||||
bash scripts/setup-postgres-ubuntu.sh
|
|
||||||
|
|
||||||
# 4. .env — обязательно DATABASE_URL
|
|
||||||
cp -n .env.example .env
|
|
||||||
nano .env
|
|
||||||
# DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop
|
|
||||||
# HOST=127.0.0.1
|
|
||||||
# NODE_ENV=production
|
|
||||||
# TRUST_PROXY=1
|
|
||||||
|
|
||||||
# 5. Зависимости и перезапуск
|
|
||||||
npm install --omit=dev
|
|
||||||
systemctl restart shop
|
|
||||||
|
|
||||||
# 6. Проверка
|
|
||||||
curl -s http://127.0.0.1:3000/health
|
|
||||||
systemctl reload caddy
|
|
||||||
```
|
|
||||||
|
|
||||||
Каталог `data/` больше не используется. Демо-товары появятся при пустой таблице `products`. Аккаунты и заказы из SQLite не переносятся — нужна повторная регистрация или ручной импорт.
|
|
||||||
|
|
||||||
Проверка PostgreSQL:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
psql "postgresql://shop:shop@127.0.0.1:5432/shop" -c '\dt'
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Caddy — SSL и reverse proxy
|
## Caddy — SSL и reverse proxy
|
||||||
|
|
||||||
**Перед Caddy:** `curl http://127.0.0.1:3000/health` → OK.
|
**Перед Caddy:** `curl http://127.0.0.1:3000/health` → OK.
|
||||||
@@ -310,19 +286,17 @@ shop.example.com {
|
|||||||
**Быстрое исправление (одной командой):**
|
**Быстрое исправление (одной командой):**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /opt/shop
|
bash "$SHOP_ROOT/scripts/fix-db-connection.sh"
|
||||||
git pull
|
|
||||||
bash scripts/fix-db-connection.sh
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Вручную:**
|
**Вручную:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
apt install -y postgresql-17 postgresql-client-17
|
cd "$SHOP_ROOT"
|
||||||
|
sudo bash scripts/install-postgresql-ubuntu.sh
|
||||||
systemctl enable --now postgresql
|
systemctl enable --now postgresql
|
||||||
pg_isready -h 127.0.0.1 -p 5432
|
pg_isready -h 127.0.0.1 -p 5432
|
||||||
|
|
||||||
cd /opt/shop
|
|
||||||
bash scripts/setup-postgres-ubuntu.sh
|
bash scripts/setup-postgres-ubuntu.sh
|
||||||
nano .env # DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop
|
nano .env # DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop
|
||||||
|
|
||||||
@@ -335,7 +309,7 @@ curl -s http://127.0.0.1:3000/health
|
|||||||
### HTTP 502
|
### HTTP 502
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bash /opt/shop/scripts/diagnose-502.sh
|
bash "$SHOP_ROOT/scripts/diagnose-502.sh"
|
||||||
journalctl -u shop -n 50 --no-pager
|
journalctl -u shop -n 50 --no-pager
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -378,6 +352,9 @@ 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
|
||||||
|
quick-deploy-ubuntu.sh
|
||||||
fix-db-connection.sh
|
fix-db-connection.sh
|
||||||
diagnose-502.sh
|
diagnose-502.sh
|
||||||
server-update.sh
|
server-update.sh
|
||||||
@@ -387,8 +364,8 @@ src/
|
|||||||
## Релиз 0.20.0
|
## Релиз 0.20.0
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone <URL_РЕПОЗИТОРИЯ> shop
|
git clone <URL-вашего-репозитория> /opt/shop
|
||||||
cd shop
|
cd /opt/shop
|
||||||
git checkout v0.20.0
|
git checkout v0.20.0
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -400,6 +377,6 @@ git checkout v0.20.0
|
|||||||
## Репозиторий
|
## Репозиторий
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone <URL_РЕПОЗИТОРИЯ> shop
|
git clone <URL-вашего-репозитория> /opt/shop
|
||||||
cd shop
|
cd /opt/shop
|
||||||
```
|
```
|
||||||
|
|||||||
+7
-4
@@ -1,7 +1,7 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=Shop Node.js
|
Description=Shop Node.js
|
||||||
After=network.target postgresql.service
|
After=network.target
|
||||||
Wants=postgresql.service
|
Wants=network-online.target
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
@@ -9,12 +9,15 @@ User=www-data
|
|||||||
Group=www-data
|
Group=www-data
|
||||||
WorkingDirectory=/opt/shop
|
WorkingDirectory=/opt/shop
|
||||||
EnvironmentFile=/opt/shop/.env
|
EnvironmentFile=/opt/shop/.env
|
||||||
# Дождаться PostgreSQL (запуск от root, +)
|
ExecStartPre=+/opt/shop/scripts/wait-postgres.sh
|
||||||
ExecStartPre=+/bin/bash -c 'for i in $(seq 1 60); do pg_isready -h 127.0.0.1 -p 5432 -q && exit 0; sleep 1; done; echo "PostgreSQL не отвечает на 127.0.0.1:5432"; exit 1'
|
|
||||||
ExecStart=/usr/bin/node src/server.js
|
ExecStart=/usr/bin/node src/server.js
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
RestartSec=5
|
RestartSec=5
|
||||||
|
|
||||||
|
# Логи в journal
|
||||||
|
StandardOutput=journal
|
||||||
|
StandardError=journal
|
||||||
|
|
||||||
UMask=0022
|
UMask=0022
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
|
|||||||
+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'
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
## Вариант A — Docker Compose
|
## Вариант A — Docker Compose
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone <URL_РЕПОЗИТОРИЯ> shop && cd shop
|
git clone https://git.evilfox.cc/test/shop10.git /opt/shop/shop10 && cd /opt/shop/shop10
|
||||||
git checkout v0.10.0
|
git checkout v0.10.0
|
||||||
|
|
||||||
cp .env.docker.example .env
|
cp .env.docker.example .env
|
||||||
@@ -27,7 +27,7 @@ docker compose --profile proxy up -d --build
|
|||||||
## Вариант B — без Docker (Ubuntu)
|
## Вариант B — без Docker (Ubuntu)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone <URL_РЕПОЗИТОРИЯ> shop && cd shop
|
git clone https://git.evilfox.cc/test/shop10.git /opt/shop/shop10 && cd /opt/shop/shop10
|
||||||
git checkout v0.10.0
|
git checkout v0.10.0
|
||||||
|
|
||||||
apt install -y git curl
|
apt install -y git curl
|
||||||
@@ -50,7 +50,6 @@ Caddy на хосте — см. `README.md`, раздел «Caddy».
|
|||||||
|
|
||||||
## Обновление с более ранних версий
|
## Обновление с более ранних версий
|
||||||
|
|
||||||
- С **SQLite**: раздел «Переход с SQLite на PostgreSQL 17» в README
|
|
||||||
- С **0.10-beta**: `git pull`, `npm install`, `systemctl restart shop`
|
- С **0.10-beta**: `git pull`, `npm install`, `systemctl restart shop`
|
||||||
|
|
||||||
## Тег и Release в Gitea
|
## Тег и Release в Gitea
|
||||||
|
|||||||
+2
-1
@@ -19,6 +19,7 @@
|
|||||||
"express": "^4.21.2",
|
"express": "^4.21.2",
|
||||||
"express-session": "^1.18.1",
|
"express-session": "^1.18.1",
|
||||||
"nodemailer": "^6.9.16",
|
"nodemailer": "^6.9.16",
|
||||||
"pg": "^8.13.1"
|
"pg": "^8.13.1",
|
||||||
|
"@simplewebauthn/server": "^13.1.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- Passkey (WebAuthn) — опциональный вход вместо пароля
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS passkey_enabled BOOLEAN NOT NULL DEFAULT false;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS webauthn_credentials (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
credential_id TEXT NOT NULL UNIQUE,
|
||||||
|
public_key BYTEA NOT NULL,
|
||||||
|
counter BIGINT NOT NULL DEFAULT 0,
|
||||||
|
device_type VARCHAR(32),
|
||||||
|
backed_up BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
transports TEXT,
|
||||||
|
label TEXT NOT NULL DEFAULT 'Passkey',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_webauthn_credentials_user_id ON webauthn_credentials(user_id);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- Подписка «сообщить о поступлении»
|
||||||
|
CREATE TABLE IF NOT EXISTS product_stock_alerts (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
product_id INTEGER NOT NULL REFERENCES products(id) ON DELETE CASCADE,
|
||||||
|
email TEXT NOT NULL,
|
||||||
|
user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
notified_at TIMESTAMPTZ,
|
||||||
|
UNIQUE (product_id, email)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_stock_alerts_product_pending
|
||||||
|
ON product_stock_alerts (product_id)
|
||||||
|
WHERE notified_at IS NULL;
|
||||||
@@ -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;
|
||||||
@@ -2,7 +2,9 @@
|
|||||||
# Диагностика HTTP 502 (Caddy не достучался до Node / БД)
|
# Диагностика HTTP 502 (Caddy не достучался до Node / БД)
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
echo "=== Shop / Caddy 502 diagnostic ==="
|
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/shop-root.sh" 2>/dev/null || SHOP_ROOT=/opt/shop
|
||||||
|
|
||||||
|
echo "=== Shop / Caddy 502 diagnostic ($SHOP_ROOT) ==="
|
||||||
echo
|
echo
|
||||||
|
|
||||||
echo "1. PostgreSQL"
|
echo "1. PostgreSQL"
|
||||||
@@ -40,11 +42,11 @@ fi
|
|||||||
echo
|
echo
|
||||||
|
|
||||||
echo "6. .env"
|
echo "6. .env"
|
||||||
if [ -f /opt/shop/.env ]; then
|
if [ -f "$SHOP_ROOT/.env" ]; then
|
||||||
grep -E '^(DATABASE_URL|HOST|PORT)=' /opt/shop/.env 2>/dev/null | sed 's/=.*/=***/' || true
|
grep -E '^(DATABASE_URL|HOST|PORT)=' "$SHOP_ROOT/.env" 2>/dev/null | sed 's/=.*/=***/' || true
|
||||||
grep -E '^DATABASE_URL=' /opt/shop/.env || echo " DATABASE_URL не задан"
|
grep -E '^DATABASE_URL=' "$SHOP_ROOT/.env" || echo " DATABASE_URL не задан"
|
||||||
else
|
else
|
||||||
echo " /opt/shop/.env не найден"
|
echo " $SHOP_ROOT/.env не найден"
|
||||||
fi
|
fi
|
||||||
echo
|
echo
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Диагностика службы shop
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
source "$SCRIPT_DIR/shop-root.sh"
|
||||||
|
|
||||||
|
echo "=== Диагностика shop.service ==="
|
||||||
|
echo "SHOP_ROOT=$SHOP_ROOT"
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "1. Unit"
|
||||||
|
systemctl cat shop.service 2>/dev/null | head -25 || echo " shop.service не найден"
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "2. PostgreSQL"
|
||||||
|
systemctl is-active postgresql 2>/dev/null || systemctl is-active 'postgresql@*' 2>/dev/null || echo " postgresql: не active"
|
||||||
|
pg_isready -q 2>/dev/null && echo " pg_isready (socket): OK" || echo " pg_isready (socket): FAIL"
|
||||||
|
pg_isready -h 127.0.0.1 -p 5432 -q 2>/dev/null && echo " pg_isready 127.0.0.1: OK" || echo " pg_isready 127.0.0.1: FAIL"
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "3. .env"
|
||||||
|
if [ -f "$SHOP_ROOT/.env" ]; then
|
||||||
|
ls -la "$SHOP_ROOT/.env"
|
||||||
|
grep -E '^(DATABASE_URL|HOST|PORT|NODE_ENV)=' "$SHOP_ROOT/.env" | sed 's/=.*/=***/' || true
|
||||||
|
else
|
||||||
|
echo " .env не найден"
|
||||||
|
fi
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "4. Порт 3000"
|
||||||
|
ss -tlnp | grep ':3000' || echo " порт 3000 свободен"
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "5. www-data доступ"
|
||||||
|
sudo -u www-data test -r "$SHOP_ROOT/package.json" && echo " package.json: OK" || echo " package.json: FAIL"
|
||||||
|
sudo -u www-data test -x "$SHOP_ROOT" && echo " каталог: OK" || echo " каталог: FAIL"
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "6. Тест Node (5 сек)"
|
||||||
|
set +e
|
||||||
|
timeout 8 sudo -u www-data bash -c "cd '$SHOP_ROOT' && set -a && source .env 2>/dev/null && set +a && node src/server.js" 2>&1 | head -20
|
||||||
|
set -e
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "7. journalctl shop"
|
||||||
|
journalctl -u shop -n 30 --no-pager 2>/dev/null || true
|
||||||
@@ -2,29 +2,30 @@
|
|||||||
# Быстрое исправление ECONNREFUSED 127.0.0.1:5432
|
# Быстрое исправление ECONNREFUSED 127.0.0.1:5432
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
cd /opt/shop 2>/dev/null || cd "$(dirname "$0")/.."
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
source "$SCRIPT_DIR/shop-root.sh"
|
||||||
|
|
||||||
echo "=== Исправление подключения к PostgreSQL ==="
|
echo "=== Исправление подключения к PostgreSQL ($SHOP_ROOT) ==="
|
||||||
|
|
||||||
if ! dpkg -l | grep -q postgresql; then
|
if ! command -v psql >/dev/null; then
|
||||||
echo "Установка PostgreSQL 17..."
|
bash "$SCRIPT_DIR/install-postgresql-ubuntu.sh"
|
||||||
apt update
|
|
||||||
apt install -y postgresql-17 postgresql-client-17 || {
|
|
||||||
echo "Если пакет не найден — см. README (репозиторий PGDG)"
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
bash scripts/setup-postgres-ubuntu.sh
|
bash "$SCRIPT_DIR/setup-postgres-ubuntu.sh"
|
||||||
|
|
||||||
if [ -f .env ] && ! grep -q '^DATABASE_URL=' .env; then
|
if [ -f .env ] && ! grep -q '^DATABASE_URL=' .env; then
|
||||||
echo "DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop" >> .env
|
echo 'DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop' >> .env
|
||||||
echo "Добавлен DATABASE_URL в .env"
|
echo "Добавлен DATABASE_URL в .env"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
cp -f deploy/shop.service /etc/systemd/system/shop.service
|
if [ -f deploy/shop.service ]; then
|
||||||
systemctl daemon-reload
|
cp -f deploy/shop.service /etc/systemd/system/shop.service
|
||||||
systemctl restart shop
|
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
|
||||||
|
systemctl daemon-reload
|
||||||
|
fi
|
||||||
|
|
||||||
|
systemctl restart shop 2>/dev/null || true
|
||||||
sleep 2
|
sleep 2
|
||||||
|
|
||||||
if curl -sf http://127.0.0.1:3000/health; then
|
if curl -sf http://127.0.0.1:3000/health; then
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Освободить порт 3000 (ручной npm start / старый процесс)
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PORT="${1:-3000}"
|
||||||
|
|
||||||
|
if ! command -v ss >/dev/null; then
|
||||||
|
echo "ss не найден"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! ss -tlnp | grep -q ":${PORT} "; then
|
||||||
|
echo "Порт ${PORT} свободен"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Порт ${PORT} занят:"
|
||||||
|
ss -tlnp | grep ":${PORT} " || true
|
||||||
|
|
||||||
|
if command -v fuser >/dev/null; then
|
||||||
|
echo "Останавливаем процессы на ${PORT}/tcp..."
|
||||||
|
fuser -k "${PORT}/tcp" 2>/dev/null || true
|
||||||
|
sleep 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ss -tlnp | grep -q ":${PORT} "; then
|
||||||
|
echo "Порт ${PORT} всё ещё занят — остановите процесс вручную"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Порт ${PORT} свободен"
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Синхронизация с origin/main (исправляет detached HEAD)
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/shop-root.sh"
|
||||||
|
|
||||||
|
if [ ! -d .git ]; then
|
||||||
|
echo "Ошибка: в $SHOP_ROOT нет .git — нужен полный clone:"
|
||||||
|
echo " git clone <URL-репозитория> /opt/shop"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
git config --global --add safe.directory "$SHOP_ROOT" 2>/dev/null || true
|
||||||
|
|
||||||
|
echo "=== git sync: $SHOP_ROOT ==="
|
||||||
|
git fetch origin
|
||||||
|
|
||||||
|
if git symbolic-ref -q HEAD >/dev/null 2>&1; then
|
||||||
|
BRANCH=$(git branch --show-current)
|
||||||
|
echo "Текущая ветка: ${BRANCH:-?}"
|
||||||
|
else
|
||||||
|
echo "Состояние: detached HEAD ($(git rev-parse --short HEAD))"
|
||||||
|
BRANCH=""
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$BRANCH" != "main" ]; then
|
||||||
|
if git show-ref --verify --quiet refs/remotes/origin/main; then
|
||||||
|
git checkout -B main origin/main
|
||||||
|
elif git show-ref --verify --quiet refs/heads/main; then
|
||||||
|
git checkout main
|
||||||
|
else
|
||||||
|
echo "Ветка main не найдена на origin"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
git pull origin main
|
||||||
|
echo "OK: $(git log -1 --oneline)"
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Установка PostgreSQL 17 (PGDG) или postgresql из Ubuntu
|
||||||
|
# sudo bash scripts/install-postgresql-ubuntu.sh
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
if command -v psql >/dev/null; then
|
||||||
|
echo "PostgreSQL уже установлен: $(psql --version | head -1)"
|
||||||
|
systemctl enable postgresql 2>/dev/null || true
|
||||||
|
systemctl start postgresql 2>/dev/null || true
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== Установка PostgreSQL ==="
|
||||||
|
apt update
|
||||||
|
apt install -y curl ca-certificates gnupg lsb-release
|
||||||
|
|
||||||
|
if [ ! -f /etc/os-release ]; then
|
||||||
|
echo "Ошибка: не найден /etc/os-release"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
# shellcheck source=/dev/null
|
||||||
|
. /etc/os-release
|
||||||
|
CODENAME="${VERSION_CODENAME:-}"
|
||||||
|
if [ -z "$CODENAME" ]; then
|
||||||
|
echo "Ошибка: не удалось определить VERSION_CODENAME (Ubuntu/Debian?)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
install -d /usr/share/postgresql-common/pgdg
|
||||||
|
curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
|
||||||
|
-o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc
|
||||||
|
|
||||||
|
echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt ${CODENAME}-pgdg main" \
|
||||||
|
> /etc/apt/sources.list.d/pgdg.list
|
||||||
|
|
||||||
|
apt update
|
||||||
|
|
||||||
|
if apt install -y postgresql-17 postgresql-client-17; then
|
||||||
|
echo "Установлен PostgreSQL 17 (PGDG)"
|
||||||
|
else
|
||||||
|
echo "Пакет postgresql-17 недоступен — устанавливаем postgresql из репозитория Ubuntu..."
|
||||||
|
apt install -y postgresql postgresql-contrib
|
||||||
|
fi
|
||||||
|
|
||||||
|
systemctl enable postgresql
|
||||||
|
systemctl start postgresql
|
||||||
|
|
||||||
|
for i in $(seq 1 30); do
|
||||||
|
if pg_isready -h 127.0.0.1 -p 5432 -q 2>/dev/null; then
|
||||||
|
echo "pg_isready: OK"
|
||||||
|
psql --version | head -1
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "PostgreSQL установлен, но не отвечает на 127.0.0.1:5432"
|
||||||
|
echo " journalctl -u postgresql -n 30 --no-pager"
|
||||||
|
exit 1
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Установка systemd-службы shop (после git clone и .env)
|
||||||
|
# sudo bash scripts/install-shop-service.sh
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
if [ "$(id -u)" -ne 0 ]; then
|
||||||
|
echo "Запустите от root: sudo bash scripts/install-shop-service.sh"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
source "$SCRIPT_DIR/shop-root.sh"
|
||||||
|
|
||||||
|
echo "=== Установка службы shop ==="
|
||||||
|
echo "Каталог: $SHOP_ROOT"
|
||||||
|
|
||||||
|
if [ ! -f "$SHOP_ROOT/package.json" ]; then
|
||||||
|
echo "Ошибка: нет package.json в $SHOP_ROOT"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# .env в родительском каталоге (если переносили клон)
|
||||||
|
PARENT_ENV="$(dirname "$SHOP_ROOT")/.env"
|
||||||
|
if [ ! -f "$SHOP_ROOT/.env" ] && [ -f "$PARENT_ENV" ]; then
|
||||||
|
cp "$PARENT_ENV" "$SHOP_ROOT/.env"
|
||||||
|
echo "Скопирован .env из $(dirname "$SHOP_ROOT")"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -f "$SHOP_ROOT/.env" ]; then
|
||||||
|
if [ -f "$SHOP_ROOT/.env.example" ]; then
|
||||||
|
cp "$SHOP_ROOT/.env.example" "$SHOP_ROOT/.env"
|
||||||
|
if command -v openssl >/dev/null; then
|
||||||
|
sed -i "s/change-me-to-a-long-random-string/$(openssl rand -hex 32)/" "$SHOP_ROOT/.env"
|
||||||
|
fi
|
||||||
|
echo "Создан .env — проверьте DATABASE_URL"
|
||||||
|
else
|
||||||
|
echo "Ошибка: нет .env"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! grep -q '^DATABASE_URL=' "$SHOP_ROOT/.env"; then
|
||||||
|
echo "Добавляю DATABASE_URL по умолчанию..."
|
||||||
|
echo 'DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop' >> "$SHOP_ROOT/.env"
|
||||||
|
fi
|
||||||
|
|
||||||
|
NODE_BIN=$(command -v node)
|
||||||
|
echo "Node: $NODE_BIN ($($NODE_BIN -v))"
|
||||||
|
|
||||||
|
chmod +x "$SHOP_ROOT/scripts/wait-postgres.sh" 2>/dev/null || true
|
||||||
|
|
||||||
|
if command -v pg_isready >/dev/null; then
|
||||||
|
bash "$SCRIPT_DIR/install-postgresql-ubuntu.sh" 2>/dev/null || true
|
||||||
|
systemctl enable postgresql 2>/dev/null || true
|
||||||
|
systemctl start postgresql 2>/dev/null || true
|
||||||
|
bash "$SCRIPT_DIR/setup-postgres-ubuntu.sh" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
npm install --omit=dev --prefix "$SHOP_ROOT"
|
||||||
|
|
||||||
|
# Доступ www-data: чтение кода и .env (systemd читает .env от root, но на всякий случай)
|
||||||
|
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
|
||||||
|
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|ExecStartPre=.*|ExecStartPre=+${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
|
||||||
|
|
||||||
|
if ! sudo -u www-data test -r "$SHOP_ROOT/package.json"; then
|
||||||
|
echo "Ошибка: www-data не читает $SHOP_ROOT"
|
||||||
|
ls -la "$SHOP_ROOT" | head -5
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable shop
|
||||||
|
|
||||||
|
systemctl stop shop 2>/dev/null || true
|
||||||
|
bash "$SCRIPT_DIR/free-port-3000.sh" 3000
|
||||||
|
|
||||||
|
echo "Запуск shop..."
|
||||||
|
if ! systemctl restart shop; then
|
||||||
|
echo ""
|
||||||
|
echo "=== Ошибка запуска — лог ==="
|
||||||
|
journalctl -u shop -n 40 --no-pager
|
||||||
|
echo ""
|
||||||
|
bash "$SCRIPT_DIR/diagnose-shop-service.sh" || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
sleep 3
|
||||||
|
|
||||||
|
if ! systemctl is-active --quiet shop; then
|
||||||
|
echo "shop.service не в состоянии active"
|
||||||
|
journalctl -u shop -n 40 --no-pager
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if curl -sf http://127.0.0.1:3000/health; then
|
||||||
|
echo ""
|
||||||
|
echo "OK — служба shop запущена (systemd active)"
|
||||||
|
systemctl status shop --no-pager | head -15
|
||||||
|
systemctl reload caddy 2>/dev/null || true
|
||||||
|
else
|
||||||
|
echo "health не отвечает"
|
||||||
|
journalctl -u shop -n 40 --no-pager
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
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 "============================================"
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Быстрое развёртывание / обновление на Ubuntu (без Docker)
|
||||||
|
# sudo bash scripts/quick-deploy-ubuntu.sh
|
||||||
|
#
|
||||||
|
# Каталог: SHOP_INSTALL_DIR (по умолчанию /opt/shop)
|
||||||
|
# URL репозитория: SHOP_GIT_URL (обязателен при первом clone)
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
INSTALL_DIR="${SHOP_INSTALL_DIR:-/opt/shop}"
|
||||||
|
GIT_URL="${SHOP_GIT_URL:-}"
|
||||||
|
|
||||||
|
if [ "$(id -u)" -ne 0 ]; then
|
||||||
|
echo "Запустите от root: sudo bash scripts/quick-deploy-ubuntu.sh"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== Shop: быстрое развёртывание ==="
|
||||||
|
echo "Каталог: $INSTALL_DIR"
|
||||||
|
|
||||||
|
if ! command -v node >/dev/null; then
|
||||||
|
echo "Установка Node.js 20..."
|
||||||
|
apt update
|
||||||
|
apt install -y git curl ca-certificates
|
||||||
|
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||||
|
apt install -y nodejs
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -f "$INSTALL_DIR/package.json" ]; then
|
||||||
|
if [ -z "$GIT_URL" ]; then
|
||||||
|
echo "Задайте URL репозитория:"
|
||||||
|
echo " export SHOP_GIT_URL='https://ваш-forge/user/shop.git'"
|
||||||
|
echo " sudo SHOP_GIT_URL=\"\$SHOP_GIT_URL\" bash scripts/quick-deploy-ubuntu.sh"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Клонирование: $GIT_URL -> $INSTALL_DIR"
|
||||||
|
mkdir -p "$(dirname "$INSTALL_DIR")"
|
||||||
|
git clone "$GIT_URL" "$INSTALL_DIR"
|
||||||
|
fi
|
||||||
|
|
||||||
|
export SHOP_ROOT="$INSTALL_DIR"
|
||||||
|
cd "$INSTALL_DIR"
|
||||||
|
git config --global --add safe.directory "$INSTALL_DIR" 2>/dev/null || true
|
||||||
|
git pull
|
||||||
|
|
||||||
|
bash scripts/install-postgresql-ubuntu.sh
|
||||||
|
bash scripts/setup-postgres-ubuntu.sh
|
||||||
|
|
||||||
|
if [ ! -f .env ]; then
|
||||||
|
cp .env.example .env
|
||||||
|
if command -v openssl >/dev/null; then
|
||||||
|
SECRET=$(openssl rand -hex 32)
|
||||||
|
sed -i "s/change-me-to-a-long-random-string/${SECRET}/" .env
|
||||||
|
fi
|
||||||
|
if ! grep -q '^DATABASE_URL=' .env; then
|
||||||
|
echo 'DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop' >> .env
|
||||||
|
fi
|
||||||
|
echo "Создан .env — проверьте SITE_URL и SMTP"
|
||||||
|
fi
|
||||||
|
|
||||||
|
npm install --omit=dev
|
||||||
|
|
||||||
|
if [ -f deploy/shop.service ]; then
|
||||||
|
cp -f deploy/shop.service /etc/systemd/system/shop.service
|
||||||
|
# Подставить фактический путь в unit
|
||||||
|
sed -i "s|WorkingDirectory=.*|WorkingDirectory=${INSTALL_DIR}|" /etc/systemd/system/shop.service
|
||||||
|
sed -i "s|EnvironmentFile=.*|EnvironmentFile=${INSTALL_DIR}/.env|" /etc/systemd/system/shop.service
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable shop 2>/dev/null || true
|
||||||
|
systemctl restart shop
|
||||||
|
sleep 2
|
||||||
|
curl -sf http://127.0.0.1:3000/health && echo && echo "OK — shop запущен (systemd)"
|
||||||
|
systemctl reload caddy 2>/dev/null || true
|
||||||
|
else
|
||||||
|
echo "deploy/shop.service не найден — запустите: npm start"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "Обновления в будущем:"
|
||||||
|
echo " bash ${INSTALL_DIR}/scripts/server-update.sh"
|
||||||
+35
-12
@@ -1,11 +1,24 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# Обновление на сервере (запускать от root в /opt/shop)
|
# Обновление на сервере: git pull, npm, restart shop
|
||||||
|
# bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
cd /opt/shop
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
# shellcheck source=shop-root.sh
|
||||||
|
source "$SCRIPT_DIR/shop-root.sh"
|
||||||
|
|
||||||
git config --global --add safe.directory /opt/shop 2>/dev/null || true
|
echo "=== Shop update: $SHOP_ROOT ==="
|
||||||
git pull
|
|
||||||
|
if [ ! -d .git ]; then
|
||||||
|
echo "Ошибка: $SHOP_ROOT не git-репозиторий (нет .git)."
|
||||||
|
echo "Если нет .git — клонируйте заново:"
|
||||||
|
echo " export SHOP_GIT_URL='<URL-репозитория>'"
|
||||||
|
echo " mv \"$SHOP_ROOT\" \"\${SHOP_ROOT}.bak\""
|
||||||
|
echo " git clone \"\$SHOP_GIT_URL\" \"$SHOP_ROOT\""
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
bash "$SCRIPT_DIR/git-sync.sh"
|
||||||
|
|
||||||
npm install --omit=dev
|
npm install --omit=dev
|
||||||
|
|
||||||
@@ -21,15 +34,25 @@ if command -v pg_isready >/dev/null; then
|
|||||||
}
|
}
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if systemctl is-active --quiet shop 2>/dev/null; then
|
if [ -f /etc/systemd/system/shop.service ]; then
|
||||||
|
systemctl daemon-reload
|
||||||
|
bash "$SCRIPT_DIR/free-port-3000.sh" 3000 2>/dev/null || true
|
||||||
systemctl restart shop
|
systemctl restart shop
|
||||||
sleep 1
|
sleep 2
|
||||||
curl -sf http://127.0.0.1:3000/health && echo || {
|
if curl -sf http://127.0.0.1:3000/health; then
|
||||||
echo "shop не отвечает — смотрите: journalctl -u shop -n 30"
|
echo ""
|
||||||
|
echo "OK"
|
||||||
|
systemctl reload caddy 2>/dev/null || true
|
||||||
|
else
|
||||||
|
echo "shop не отвечает — journalctl -u shop -n 30"
|
||||||
exit 1
|
exit 1
|
||||||
}
|
fi
|
||||||
systemctl reload caddy 2>/dev/null || true
|
elif [ "$(id -u)" -eq 0 ]; then
|
||||||
echo "OK"
|
echo "Служба shop не установлена — устанавливаем..."
|
||||||
|
bash "$SCRIPT_DIR/install-shop-service.sh"
|
||||||
else
|
else
|
||||||
echo "Служба shop не установлена. См. deploy/shop.service в README."
|
echo "Служба shop не установлена. Выполните от root:"
|
||||||
|
echo " sudo bash $SHOP_ROOT/scripts/install-shop-service.sh"
|
||||||
|
echo "WorkingDirectory: $SHOP_ROOT"
|
||||||
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# PostgreSQL 17 на Ubuntu — установка службы, пользователь и БД shop
|
# PostgreSQL — пользователь и БД shop (после install-postgresql-ubuntu.sh)
|
||||||
# Запуск: sudo bash scripts/setup-postgres-ubuntu.sh
|
# sudo bash scripts/setup-postgres-ubuntu.sh
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
SHOP_ROOT="${SHOP_ROOT:-$(cd "$SCRIPT_DIR/.." && pwd)}"
|
||||||
|
|
||||||
DB_USER="${DB_USER:-shop}"
|
DB_USER="${DB_USER:-shop}"
|
||||||
DB_PASS="${DB_PASS:-shop}"
|
DB_PASS="${DB_PASS:-shop}"
|
||||||
DB_NAME="${DB_NAME:-shop}"
|
DB_NAME="${DB_NAME:-shop}"
|
||||||
|
|
||||||
if ! command -v psql >/dev/null; then
|
if ! command -v psql >/dev/null; then
|
||||||
echo "PostgreSQL не установлен."
|
echo "PostgreSQL не установлен. Запустите:"
|
||||||
echo " apt install -y postgresql-17 postgresql-client-17"
|
echo " sudo bash $SCRIPT_DIR/install-postgresql-ubuntu.sh"
|
||||||
echo " systemctl enable --now postgresql"
|
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -52,7 +54,7 @@ EOF
|
|||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "PostgreSQL готов."
|
echo "PostgreSQL готов."
|
||||||
echo "Добавьте в /opt/shop/.env:"
|
echo "Добавьте в ${SHOP_ROOT}/.env:"
|
||||||
echo "DATABASE_URL=postgresql://${DB_USER}:${DB_PASS}@127.0.0.1:5432/${DB_NAME}"
|
echo "DATABASE_URL=postgresql://${DB_USER}:${DB_PASS}@127.0.0.1:5432/${DB_NAME}"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Проверка: psql \"postgresql://${DB_USER}:${DB_PASS}@127.0.0.1:5432/${DB_NAME}\" -c 'SELECT 1'"
|
echo "Проверка: psql \"postgresql://${DB_USER}:${DB_PASS}@127.0.0.1:5432/${DB_NAME}\" -c 'SELECT 1'"
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Каталог репозитория (package.json + по возможности .git)
|
||||||
|
# Переопределение: SHOP_ROOT=/opt/shop/shop10
|
||||||
|
_resolve_shop_root() {
|
||||||
|
local d
|
||||||
|
for d in \
|
||||||
|
"${SHOP_ROOT:-}" \
|
||||||
|
"$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" \
|
||||||
|
"/opt/shop" \
|
||||||
|
"/opt/shop/app"; do
|
||||||
|
[ -z "$d" ] && continue
|
||||||
|
[ -f "${d}/package.json" ] && [ -d "${d}/.git" ] && SHOP_ROOT="$d" && return 0
|
||||||
|
done
|
||||||
|
for d in \
|
||||||
|
"${SHOP_ROOT:-}" \
|
||||||
|
"$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" \
|
||||||
|
"/opt/shop" \
|
||||||
|
"/opt/shop/app"; do
|
||||||
|
[ -z "$d" ] && continue
|
||||||
|
[ -f "${d}/package.json" ] && SHOP_ROOT="$d" && return 0
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if ! _resolve_shop_root; then
|
||||||
|
echo "Ошибка: не найден каталог Shop (нет package.json)."
|
||||||
|
echo " export SHOP_ROOT=/opt/shop # каталог с package.json"
|
||||||
|
echo " git clone <URL-репозитория> \"\$SHOP_ROOT\""
|
||||||
|
echo " SHOP_ROOT=\$SHOP_ROOT bash scripts/server-update.sh"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
export SHOP_ROOT
|
||||||
|
cd "$SHOP_ROOT"
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Ожидание PostgreSQL (сокет или TCP 127.0.0.1:5432)
|
||||||
|
for i in $(seq 1 45); do
|
||||||
|
if pg_isready -q 2>/dev/null; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
if pg_isready -h 127.0.0.1 -p 5432 -q 2>/dev/null; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
echo "PostgreSQL недоступен (проверьте: systemctl status postgresql)"
|
||||||
|
exit 1
|
||||||
+12
-5
@@ -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) => {
|
||||||
...p,
|
const effective = getEffectivePriceCents(p);
|
||||||
quantity: cart[p.id] || 0,
|
const qty = cart[p.id] || 0;
|
||||||
line_total: (cart[p.id] || 0) * p.price_cents,
|
return {
|
||||||
}))
|
...p,
|
||||||
|
quantity: qty,
|
||||||
|
effective_price_cents: effective,
|
||||||
|
on_sale: isSaleActive(p),
|
||||||
|
line_total: qty * effective,
|
||||||
|
};
|
||||||
|
})
|
||||||
.filter((p) => p.quantity > 0);
|
.filter((p) => p.quantity > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+277
-1
@@ -281,6 +281,39 @@ a:hover {
|
|||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.stock-notify {
|
||||||
|
margin-top: 1.25rem;
|
||||||
|
padding: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stock-notify__title {
|
||||||
|
margin: 0 0 0.35rem;
|
||||||
|
font-size: 1.05rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stock-notify__hint {
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stock-notify__form {
|
||||||
|
max-width: 320px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stock-notify--done {
|
||||||
|
margin-top: 1rem;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
background: rgba(0, 184, 148, 0.12);
|
||||||
|
border-radius: 8px;
|
||||||
|
color: var(--success);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-stock-form {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
.product-detail__form {
|
.product-detail__form {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
@@ -392,7 +425,9 @@ a:hover {
|
|||||||
|
|
||||||
.auth {
|
.auth {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1.25rem;
|
||||||
padding: 2rem 0;
|
padding: 2rem 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -402,6 +437,52 @@ a:hover {
|
|||||||
padding: 1.75rem;
|
padding: 1.75rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.passkey-login {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 400px;
|
||||||
|
padding: 1.25rem 1.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.passkey-login__title {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.passkey-login__hint {
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.passkey-list {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0 0 1.25rem;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.passkey-list__item {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 0.65rem 0;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.passkey-list__item:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.passkey-actions {
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.divider {
|
||||||
|
border: none;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
margin: 1.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
.alert {
|
.alert {
|
||||||
padding: 0.75rem 1rem;
|
padding: 0.75rem 1rem;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
@@ -466,6 +547,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;
|
||||||
@@ -585,6 +766,34 @@ a:hover {
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.btn--admin {
|
||||||
|
background: rgba(253, 203, 110, 0.15);
|
||||||
|
border: 1px solid var(--warn);
|
||||||
|
color: var(--warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn--admin:hover {
|
||||||
|
background: rgba(253, 203, 110, 0.28);
|
||||||
|
color: #fff;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.account-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.75rem;
|
||||||
|
margin-top: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-hint {
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-hint code {
|
||||||
|
font-size: 0.85em;
|
||||||
|
}
|
||||||
|
|
||||||
.admin-header {
|
.admin-header {
|
||||||
margin-bottom: 1.5rem;
|
margin-bottom: 1.5rem;
|
||||||
}
|
}
|
||||||
@@ -797,3 +1006,70 @@ a:hover {
|
|||||||
body:has(.cookie-banner) .main {
|
body:has(.cookie-banner) .main {
|
||||||
padding-bottom: 7rem;
|
padding-bottom: 7rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.price-block {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 0.35rem 0.6rem;
|
||||||
|
margin: 0.35rem 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block__old {
|
||||||
|
text-decoration: line-through;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-block--sale .price-block__current {
|
||||||
|
color: var(--accent);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge--sale {
|
||||||
|
background: rgba(239, 68, 68, 0.15);
|
||||||
|
color: #f87171;
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
/**
|
||||||
|
* WebAuthn (passkey) — требуется современный браузер с parseCreationOptionsFromJSON / toJSON.
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
function supportsPasskey() {
|
||||||
|
return (
|
||||||
|
window.PublicKeyCredential &&
|
||||||
|
typeof PublicKeyCredential.parseCreationOptionsFromJSON === 'function' &&
|
||||||
|
typeof PublicKeyCredential.parseRequestOptionsFromJSON === 'function'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function showError(el, message) {
|
||||||
|
if (!el) return;
|
||||||
|
el.textContent = message;
|
||||||
|
el.hidden = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideError(el) {
|
||||||
|
if (el) el.hidden = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postJson(url, body) {
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
credentials: 'same-origin',
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(data.error || 'Ошибка запроса');
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function registerPasskey(passwordInput, errorEl, btn) {
|
||||||
|
if (!supportsPasskey()) {
|
||||||
|
showError(errorEl, 'Браузер не поддерживает passkey. Обновите браузер или используйте Chrome, Edge, Safari.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const password = passwordInput?.value;
|
||||||
|
if (!password) {
|
||||||
|
showError(errorEl, 'Введите текущий пароль для подтверждения');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
hideError(errorEl);
|
||||||
|
if (btn) btn.disabled = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const options = await postJson('/webauthn/register/options', {
|
||||||
|
current_password: password,
|
||||||
|
});
|
||||||
|
|
||||||
|
const credential = await navigator.credentials.create({
|
||||||
|
publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(options),
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await postJson('/webauthn/register/verify', credential.toJSON());
|
||||||
|
if (result.redirect) {
|
||||||
|
window.location.href = result.redirect;
|
||||||
|
} else {
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
showError(errorEl, err.message || 'Не удалось привязать passkey');
|
||||||
|
} finally {
|
||||||
|
if (btn) btn.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loginWithPasskey(emailInput, nextInput, errorEl, btn) {
|
||||||
|
if (!supportsPasskey()) {
|
||||||
|
showError(errorEl, 'Браузер не поддерживает passkey');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const email = (emailInput?.value || '').trim();
|
||||||
|
if (!email) {
|
||||||
|
showError(errorEl, 'Сначала укажите email');
|
||||||
|
emailInput?.focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
hideError(errorEl);
|
||||||
|
if (btn) btn.disabled = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const options = await postJson('/webauthn/login/options', { email });
|
||||||
|
const credential = await navigator.credentials.get({
|
||||||
|
publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(options),
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await postJson('/webauthn/login/verify', {
|
||||||
|
...credential.toJSON(),
|
||||||
|
next: nextInput?.value || '/',
|
||||||
|
});
|
||||||
|
|
||||||
|
window.location.href = result.redirect || '/';
|
||||||
|
} catch (err) {
|
||||||
|
showError(errorEl, err.message || 'Не удалось войти по passkey');
|
||||||
|
} finally {
|
||||||
|
if (btn) btn.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.ShopPasskey = {
|
||||||
|
supportsPasskey,
|
||||||
|
registerPasskey,
|
||||||
|
loginWithPasskey,
|
||||||
|
};
|
||||||
|
})();
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})();
|
||||||
+50
-2
@@ -4,9 +4,10 @@ const { query, formatPrice } = require('../db');
|
|||||||
const { getCart, cartCount } = require('../cart');
|
const { getCart, cartCount } = require('../cart');
|
||||||
const { requireAuth } = require('../middleware/auth');
|
const { requireAuth } = require('../middleware/auth');
|
||||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||||
const { ROLE_LABELS } = require('../constants/roles');
|
const { ROLES, ROLE_LABELS } = require('../constants/roles');
|
||||||
const { asyncHandler } = require('../utils/asyncHandler');
|
const { asyncHandler } = require('../utils/asyncHandler');
|
||||||
const { expireOldReservations } = require('../services/reservations');
|
const { expireOldReservations } = require('../services/reservations');
|
||||||
|
const webauthn = require('../services/webauthn');
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -21,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 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];
|
||||||
@@ -44,12 +45,16 @@ function accountRender(res, options) {
|
|||||||
success,
|
success,
|
||||||
activeTab,
|
activeTab,
|
||||||
formatPrice,
|
formatPrice,
|
||||||
|
passkeys,
|
||||||
|
isAdmin,
|
||||||
} = options;
|
} = options;
|
||||||
res.render('account/index', {
|
res.render('account/index', {
|
||||||
title: 'Личный кабинет',
|
title: 'Личный кабинет',
|
||||||
user,
|
user,
|
||||||
orderCount,
|
orderCount,
|
||||||
reservations: reservations || [],
|
reservations: reservations || [],
|
||||||
|
passkeys: passkeys || [],
|
||||||
|
isAdmin: Boolean(isAdmin),
|
||||||
roleLabels: ROLE_LABELS,
|
roleLabels: ROLE_LABELS,
|
||||||
formatPrice: formatPrice || res.locals.formatPrice,
|
formatPrice: formatPrice || res.locals.formatPrice,
|
||||||
error: error || null,
|
error: error || null,
|
||||||
@@ -78,10 +83,14 @@ router.get(
|
|||||||
[user.id]
|
[user.id]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const passkeys = await webauthn.getCredentialsForUser(user.id);
|
||||||
|
|
||||||
accountRender(res, {
|
accountRender(res, {
|
||||||
user,
|
user,
|
||||||
orderCount: countResult.rows[0].n,
|
orderCount: countResult.rows[0].n,
|
||||||
reservations,
|
reservations,
|
||||||
|
passkeys,
|
||||||
|
isAdmin: user.role === ROLES.ADMIN,
|
||||||
formatPrice,
|
formatPrice,
|
||||||
success: req.query.success ? decodeURIComponent(String(req.query.success)) : null,
|
success: req.query.success ? decodeURIComponent(String(req.query.success)) : null,
|
||||||
error: req.query.error ? decodeURIComponent(String(req.query.error)) : null,
|
error: req.query.error ? decodeURIComponent(String(req.query.error)) : null,
|
||||||
@@ -187,4 +196,43 @@ router.post(
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/passkey/disable',
|
||||||
|
requireAuth,
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const { current_password } = req.body;
|
||||||
|
if (!(await verifyPassword(req.session.userId, current_password))) {
|
||||||
|
return res.redirect(
|
||||||
|
'/account?tab=passkey&error=' + encodeURIComponent('Неверный пароль')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await webauthn.disablePasskeys(req.session.userId);
|
||||||
|
res.redirect(
|
||||||
|
'/account?tab=passkey&success=' + encodeURIComponent('Вход по passkey отключён')
|
||||||
|
);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/passkey/credentials/:id/delete',
|
||||||
|
requireAuth,
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const { current_password } = req.body;
|
||||||
|
if (!(await verifyPassword(req.session.userId, current_password))) {
|
||||||
|
return res.redirect(
|
||||||
|
'/account?tab=passkey&error=' + encodeURIComponent('Неверный пароль')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const credId = parseInt(req.params.id, 10);
|
||||||
|
if (!Number.isFinite(credId)) {
|
||||||
|
return res.redirect('/account?tab=passkey&error=' + encodeURIComponent('Некорректный ключ'));
|
||||||
|
}
|
||||||
|
const ok = await webauthn.deleteCredential(req.session.userId, credId);
|
||||||
|
if (!ok) {
|
||||||
|
return res.redirect('/account?tab=passkey&error=' + encodeURIComponent('Ключ не найден'));
|
||||||
|
}
|
||||||
|
res.redirect('/account?tab=passkey&success=' + encodeURIComponent('Passkey удалён'));
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
+208
-1
@@ -3,6 +3,7 @@ const { query, formatPrice } = require('../db');
|
|||||||
const { requireAdmin } = require('../middleware/auth');
|
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 router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -91,19 +92,165 @@ router.get(
|
|||||||
'/products',
|
'/products',
|
||||||
asyncHandler(async (req, res) => {
|
asyncHandler(async (req, res) => {
|
||||||
const { rows: products } = await query(
|
const { rows: products } = await query(
|
||||||
`SELECT p.*, c.name AS category_name
|
`SELECT p.*, c.name AS category_name,
|
||||||
|
(SELECT COUNT(*)::int FROM product_stock_alerts a
|
||||||
|
WHERE a.product_id = p.id AND a.notified_at IS NULL) AS alert_count
|
||||||
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
|
||||||
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',
|
||||||
|
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,
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/products/:id/stock',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const productId = parseInt(req.params.id, 10);
|
||||||
|
const stock = parseInt(req.body.stock, 10);
|
||||||
|
if (!Number.isFinite(productId) || !Number.isFinite(stock) || stock < 0) {
|
||||||
|
return res.redirect('/admin/products');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { rows } = await query('SELECT stock FROM products WHERE id = $1', [productId]);
|
||||||
|
const oldStock = rows[0]?.stock ?? 0;
|
||||||
|
|
||||||
|
await query('UPDATE products SET stock = $1 WHERE id = $2', [stock, productId]);
|
||||||
|
|
||||||
|
let notified = 0;
|
||||||
|
if (oldStock <= 0 && stock > 0) {
|
||||||
|
const result = await notifyIfBackInStock(productId);
|
||||||
|
notified = result.sent;
|
||||||
|
}
|
||||||
|
|
||||||
|
const qs = new URLSearchParams({ stock_updated: '1' });
|
||||||
|
if (notified > 0) qs.set('notified', String(notified));
|
||||||
|
res.redirect(`/admin/products?${qs}`);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
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) => {
|
||||||
@@ -142,4 +289,64 @@ 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');
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const bcrypt = require('bcryptjs');
|
||||||
|
const { query, formatPrice } = require('../db');
|
||||||
|
const { getCart, cartCount } = require('../cart');
|
||||||
|
const { requireAuth } = require('../middleware/auth');
|
||||||
|
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||||
|
const { ROLES } = require('../constants/roles');
|
||||||
|
const { asyncHandler } = require('../utils/asyncHandler');
|
||||||
|
const webauthn = require('../services/webauthn');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.use((req, res, next) => {
|
||||||
|
const cart = getCart(req);
|
||||||
|
res.locals.cartCount = cartCount(cart);
|
||||||
|
res.locals.formatPrice = formatPrice;
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function verifyPasswordById(userId, password) {
|
||||||
|
const { rows } = await query('SELECT password_hash FROM users WHERE id = $1', [
|
||||||
|
userId,
|
||||||
|
]);
|
||||||
|
if (!rows[0]) return false;
|
||||||
|
return bcrypt.compareSync(password || '', rows[0].password_hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadUserById(userId) {
|
||||||
|
const { rows } = await query(
|
||||||
|
'SELECT id, email, name, role, passkey_enabled FROM users WHERE id = $1',
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
return rows[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveChallenge(req, challenge, extra = {}) {
|
||||||
|
req.session.webauthnChallenge = challenge;
|
||||||
|
Object.assign(req.session, extra);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearChallenge(req) {
|
||||||
|
delete req.session.webauthnChallenge;
|
||||||
|
delete req.session.webauthnLoginUserId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function adminRedirect(user, next) {
|
||||||
|
if (user.role === ROLES.ADMIN && (next === '/' || next === '/account')) {
|
||||||
|
return '/admin';
|
||||||
|
}
|
||||||
|
return next.startsWith('/') ? next : '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Регистрация passkey (в профиле, нужен вход) ---
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/register/options',
|
||||||
|
requireCookieConsent,
|
||||||
|
requireAuth,
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const { current_password } = req.body || {};
|
||||||
|
if (!(await verifyPasswordById(req.session.userId, current_password))) {
|
||||||
|
return res.status(401).json({ error: 'Неверный пароль' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await loadUserById(req.session.userId);
|
||||||
|
if (!user) return res.status(404).json({ error: 'Пользователь не найден' });
|
||||||
|
|
||||||
|
webauthn.assertOrigin(req);
|
||||||
|
const options = await webauthn.generateRegisterOptions(user);
|
||||||
|
saveChallenge(req, options.challenge);
|
||||||
|
res.json(options);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/register/verify',
|
||||||
|
requireCookieConsent,
|
||||||
|
requireAuth,
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const expectedChallenge = req.session.webauthnChallenge;
|
||||||
|
if (!expectedChallenge) {
|
||||||
|
return res.status(400).json({ error: 'Сессия истекла, повторите привязку' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await loadUserById(req.session.userId);
|
||||||
|
if (!user) return res.status(404).json({ error: 'Пользователь не найден' });
|
||||||
|
|
||||||
|
const origin = webauthn.assertOrigin(req);
|
||||||
|
const result = await webauthn.verifyRegister(
|
||||||
|
user,
|
||||||
|
req.body,
|
||||||
|
expectedChallenge,
|
||||||
|
origin
|
||||||
|
);
|
||||||
|
clearChallenge(req);
|
||||||
|
|
||||||
|
if (!result.verified) {
|
||||||
|
return res.status(400).json({ error: 'Не удалось подтвердить passkey' });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ ok: true, redirect: '/account?tab=passkey&success=' + encodeURIComponent('Passkey привязан') });
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- Вход по passkey ---
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/login/options',
|
||||||
|
requireCookieConsent,
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const email = (req.body?.email || '').trim().toLowerCase();
|
||||||
|
if (!email) {
|
||||||
|
return res.status(400).json({ error: 'Укажите email' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { user, options } = await webauthn.generateLoginOptions(email);
|
||||||
|
if (!user || !options) {
|
||||||
|
return res.status(404).json({
|
||||||
|
error: 'Passkey не настроен для этого аккаунта',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
webauthn.assertOrigin(req);
|
||||||
|
saveChallenge(req, options.challenge, { webauthnLoginUserId: user.id });
|
||||||
|
res.json(options);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/login/verify',
|
||||||
|
requireCookieConsent,
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const expectedChallenge = req.session.webauthnChallenge;
|
||||||
|
const userId = req.session.webauthnLoginUserId;
|
||||||
|
if (!expectedChallenge || !userId) {
|
||||||
|
return res.status(400).json({ error: 'Сессия истекла, начните вход заново' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await loadUserById(userId);
|
||||||
|
if (!user || !user.passkey_enabled) {
|
||||||
|
clearChallenge(req);
|
||||||
|
return res.status(400).json({ error: 'Вход по passkey недоступен' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const origin = webauthn.assertOrigin(req);
|
||||||
|
const result = await webauthn.verifyLogin(
|
||||||
|
user,
|
||||||
|
req.body,
|
||||||
|
expectedChallenge,
|
||||||
|
origin
|
||||||
|
);
|
||||||
|
clearChallenge(req);
|
||||||
|
|
||||||
|
if (!result.verified) {
|
||||||
|
return res.status(401).json({ error: 'Не удалось войти по passkey' });
|
||||||
|
}
|
||||||
|
|
||||||
|
req.session.userId = user.id;
|
||||||
|
const next = req.body?.next || '/';
|
||||||
|
res.json({ ok: true, redirect: adminRedirect(user, next) });
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -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;
|
||||||
+93
-9
@@ -4,6 +4,10 @@ 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 router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -15,6 +19,9 @@ 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();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -89,6 +96,25 @@ router.get(
|
|||||||
|
|
||||||
const errorMsg = req.query.error ? decodeURIComponent(String(req.query.error)) : null;
|
const errorMsg = req.query.error ? decodeURIComponent(String(req.query.error)) : null;
|
||||||
const reserved = req.query.reserved === '1';
|
const reserved = req.query.reserved === '1';
|
||||||
|
const notifySuccess = req.query.notify_success
|
||||||
|
? decodeURIComponent(String(req.query.notify_success))
|
||||||
|
: null;
|
||||||
|
const notifyError = req.query.notify_error
|
||||||
|
? decodeURIComponent(String(req.query.notify_error))
|
||||||
|
: null;
|
||||||
|
|
||||||
|
let stockAlertSubscribed = false;
|
||||||
|
let notifyEmail = res.locals.user?.email || '';
|
||||||
|
if (product.stock <= 0) {
|
||||||
|
const stockAlerts = require('../services/stock-alerts');
|
||||||
|
if (notifyEmail) {
|
||||||
|
stockAlertSubscribed = await stockAlerts.isSubscribed(
|
||||||
|
product.id,
|
||||||
|
notifyEmail,
|
||||||
|
req.session.userId
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
res.render('product', {
|
res.render('product', {
|
||||||
title: product.name,
|
title: product.name,
|
||||||
@@ -96,6 +122,10 @@ router.get(
|
|||||||
userReservation,
|
userReservation,
|
||||||
error: errorMsg,
|
error: errorMsg,
|
||||||
reserved,
|
reserved,
|
||||||
|
notifySuccess,
|
||||||
|
notifyError,
|
||||||
|
stockAlertSubscribed,
|
||||||
|
notifyEmail,
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
@@ -105,14 +135,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,
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
@@ -184,10 +221,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,
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
@@ -204,17 +244,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 {
|
||||||
@@ -230,13 +272,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(),
|
||||||
@@ -245,11 +314,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,
|
||||||
@@ -259,6 +341,8 @@ router.post(
|
|||||||
|
|
||||||
await client.query('COMMIT');
|
await client.query('COMMIT');
|
||||||
req.session.cart = {};
|
req.session.cart = {};
|
||||||
|
delete req.session.appliedPromoCode;
|
||||||
|
delete req.session.loyaltyPointsToUse;
|
||||||
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,75 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { query, formatPrice } = require('../db');
|
||||||
|
const { getCart, cartCount } = require('../cart');
|
||||||
|
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||||
|
const { asyncHandler } = require('../utils/asyncHandler');
|
||||||
|
const stockAlerts = require('../services/stock-alerts');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.use((req, res, next) => {
|
||||||
|
const cart = getCart(req);
|
||||||
|
res.locals.cartCount = cartCount(cart);
|
||||||
|
res.locals.formatPrice = formatPrice;
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
|
const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/product/:slug/notify-stock',
|
||||||
|
requireCookieConsent,
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const slug = req.params.slug;
|
||||||
|
const { rows } = await query('SELECT id, name, stock FROM products WHERE slug = $1', [
|
||||||
|
slug,
|
||||||
|
]);
|
||||||
|
const product = rows[0];
|
||||||
|
|
||||||
|
if (!product) {
|
||||||
|
return res.status(404).render('error', {
|
||||||
|
title: 'Не найдено',
|
||||||
|
message: 'Товар не найден',
|
||||||
|
code: 404,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (product.stock > 0) {
|
||||||
|
return res.redirect(
|
||||||
|
`/product/${slug}?notify_error=${encodeURIComponent('Товар уже в наличии')}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let email = (req.body.email || '').trim().toLowerCase();
|
||||||
|
if (req.session.userId) {
|
||||||
|
const { rows: users } = await query('SELECT email FROM users WHERE id = $1', [
|
||||||
|
req.session.userId,
|
||||||
|
]);
|
||||||
|
if (users[0]) email = users[0].email;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!email || !emailRe.test(email)) {
|
||||||
|
return res.redirect(
|
||||||
|
`/product/${slug}?notify_error=${encodeURIComponent('Укажите корректный email')}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await stockAlerts.isSubscribed(product.id, email, req.session.userId)) {
|
||||||
|
return res.redirect(
|
||||||
|
`/product/${slug}?notify_success=${encodeURIComponent('Вы уже подписаны — сообщим на почту')}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await stockAlerts.subscribe({
|
||||||
|
productId: product.id,
|
||||||
|
email,
|
||||||
|
userId: req.session.userId || null,
|
||||||
|
});
|
||||||
|
|
||||||
|
res.redirect(
|
||||||
|
`/product/${slug}?notify_success=${encodeURIComponent('Когда товар появится, отправим письмо на ' + email)}`
|
||||||
|
);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
+11
-2
@@ -7,6 +7,15 @@ async function seedAdmin() {
|
|||||||
const password = process.env.ADMIN_PASSWORD || 'admin';
|
const password = process.env.ADMIN_PASSWORD || 'admin';
|
||||||
const name = process.env.ADMIN_NAME || 'Администратор';
|
const name = process.env.ADMIN_NAME || 'Администратор';
|
||||||
|
|
||||||
|
// Только один администратор — пользователь с ADMIN_EMAIL (остальные customer)
|
||||||
|
const { rowCount: demoted } = await query(
|
||||||
|
`UPDATE users SET role = $1 WHERE role = $2 AND email != $3`,
|
||||||
|
[ROLES.CUSTOMER, ROLES.ADMIN, email]
|
||||||
|
);
|
||||||
|
if (demoted > 0) {
|
||||||
|
console.log('Снята роль admin у', demoted, 'пользоват(елей) — админ только:', email);
|
||||||
|
}
|
||||||
|
|
||||||
const { rows } = await query('SELECT id, role FROM users WHERE email = $1', [email]);
|
const { rows } = await query('SELECT id, role FROM users WHERE email = $1', [email]);
|
||||||
|
|
||||||
if (!rows[0]) {
|
if (!rows[0]) {
|
||||||
@@ -16,13 +25,13 @@ async function seedAdmin() {
|
|||||||
VALUES ($1, $2, $3, $4)`,
|
VALUES ($1, $2, $3, $4)`,
|
||||||
[email, hash, name, ROLES.ADMIN]
|
[email, hash, name, ROLES.ADMIN]
|
||||||
);
|
);
|
||||||
console.log('Создан администратор:', email);
|
console.log('Создан администратор (единственный):', email);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (rows[0].role !== ROLES.ADMIN) {
|
if (rows[0].role !== ROLES.ADMIN) {
|
||||||
await query('UPDATE users SET role = $1 WHERE id = $2', [ROLES.ADMIN, rows[0].id]);
|
await query('UPDATE users SET role = $1 WHERE id = $2', [ROLES.ADMIN, rows[0].id]);
|
||||||
console.log('Пользователю назначена роль admin:', email);
|
console.log('Назначен единственный администратор:', email);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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 };
|
||||||
+20
-1
@@ -7,6 +7,7 @@ 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 healthRoutes = require('./routes/health');
|
const healthRoutes = require('./routes/health');
|
||||||
@@ -17,6 +18,9 @@ const adminRoutes = require('./routes/admin');
|
|||||||
const cookiesRoutes = require('./routes/cookies');
|
const cookiesRoutes = require('./routes/cookies');
|
||||||
const passwordResetRoutes = require('./routes/password-reset');
|
const passwordResetRoutes = require('./routes/password-reset');
|
||||||
const reservationsRoutes = require('./routes/reservations');
|
const reservationsRoutes = require('./routes/reservations');
|
||||||
|
const passkeyRoutes = require('./routes/passkey');
|
||||||
|
const stockAlertsRoutes = require('./routes/stock-alerts');
|
||||||
|
const promoRoutes = require('./routes/promo');
|
||||||
|
|
||||||
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';
|
||||||
@@ -27,6 +31,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 +45,7 @@ async function start() {
|
|||||||
app.use(healthRoutes);
|
app.use(healthRoutes);
|
||||||
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(cookieParser());
|
app.use(cookieParser());
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
@@ -66,8 +72,11 @@ async function start() {
|
|||||||
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('/', promoRoutes);
|
||||||
app.use('/', shopRoutes);
|
app.use('/', shopRoutes);
|
||||||
app.use('/', authRoutes);
|
app.use('/', authRoutes);
|
||||||
|
app.use('/webauthn', passkeyRoutes);
|
||||||
app.use('/account', accountRoutes);
|
app.use('/account', accountRoutes);
|
||||||
app.use('/admin', adminRoutes);
|
app.use('/admin', adminRoutes);
|
||||||
|
|
||||||
@@ -93,7 +102,13 @@ async function start() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
server.on('error', (err) => {
|
server.on('error', (err) => {
|
||||||
console.error('Не удалось запустить сервер:', err.message);
|
if (err.code === 'EADDRINUSE') {
|
||||||
|
console.error(
|
||||||
|
`Порт ${PORT} уже занят (часто старый «npm start»). Выполните: bash scripts/free-port-3000.sh`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
console.error('Не удалось запустить сервер:', err.message);
|
||||||
|
}
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -104,8 +119,12 @@ start().catch((err) => {
|
|||||||
console.error(' systemctl start postgresql');
|
console.error(' systemctl start postgresql');
|
||||||
console.error(' bash scripts/setup-postgres-ubuntu.sh');
|
console.error(' bash scripts/setup-postgres-ubuntu.sh');
|
||||||
console.error(' Проверьте DATABASE_URL в .env');
|
console.error(' Проверьте DATABASE_URL в .env');
|
||||||
|
} else if (err.code === 'MODULE_NOT_FOUND') {
|
||||||
|
console.error('Не найден модуль:', err.message);
|
||||||
|
console.error(' cd', path.join(__dirname, '..'), '&& npm install --omit=dev');
|
||||||
} else {
|
} else {
|
||||||
console.error('Ошибка запуска:', err.message);
|
console.error('Ошибка запуска:', err.message);
|
||||||
|
if (err.stack) console.error(err.stack);
|
||||||
}
|
}
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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,10 +68,22 @@ async function sendReservationEmail(to, productName, quantity, expiresAt) {
|
|||||||
return sendMail({ to, subject, text, html });
|
return sendMail({ to, subject, text, html });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function sendStockAvailableEmail(to, productName, productUrl) {
|
||||||
|
const subject = `Снова в наличии: ${productName}`;
|
||||||
|
const text = `Товар «${productName}» снова в наличии.\n\nПерейти: ${productUrl}`;
|
||||||
|
const html = `
|
||||||
|
<p>Товар <strong>${productName}</strong> снова в наличии.</p>
|
||||||
|
<p><a href="${productUrl}">Открыть товар в магазине</a></p>
|
||||||
|
<p style="color:#666">Вы получили это письмо, потому что подписались на уведомление о поступлении.</p>
|
||||||
|
`;
|
||||||
|
return sendMail({ to, subject, text, html });
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
isConfigured,
|
isConfigured,
|
||||||
sendMail,
|
sendMail,
|
||||||
sendPasswordResetEmail,
|
sendPasswordResetEmail,
|
||||||
sendReservationEmail,
|
sendReservationEmail,
|
||||||
|
sendStockAvailableEmail,
|
||||||
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,74 @@
|
|||||||
|
const { query } = require('../db');
|
||||||
|
const { sendStockAvailableEmail, siteUrl } = require('./mail');
|
||||||
|
|
||||||
|
async function isSubscribed(productId, email, userId) {
|
||||||
|
const normalized = email.trim().toLowerCase();
|
||||||
|
const params = [productId, normalized];
|
||||||
|
let sql = `SELECT 1 FROM product_stock_alerts
|
||||||
|
WHERE product_id = $1 AND notified_at IS NULL
|
||||||
|
AND (email = $2`;
|
||||||
|
if (userId) {
|
||||||
|
sql += ' OR user_id = $3';
|
||||||
|
params.push(userId);
|
||||||
|
}
|
||||||
|
sql += ')';
|
||||||
|
const { rows } = await query(sql, params);
|
||||||
|
return rows.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function subscribe({ productId, email, userId }) {
|
||||||
|
const normalized = email.trim().toLowerCase();
|
||||||
|
await query(
|
||||||
|
`INSERT INTO product_stock_alerts (product_id, email, user_id)
|
||||||
|
VALUES ($1, $2, $3)
|
||||||
|
ON CONFLICT (product_id, email) DO UPDATE SET
|
||||||
|
user_id = COALESCE(EXCLUDED.user_id, product_stock_alerts.user_id),
|
||||||
|
notified_at = NULL,
|
||||||
|
created_at = CASE
|
||||||
|
WHEN product_stock_alerts.notified_at IS NOT NULL THEN NOW()
|
||||||
|
ELSE product_stock_alerts.created_at
|
||||||
|
END`,
|
||||||
|
[productId, normalized, userId || null]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function notifyIfBackInStock(productId) {
|
||||||
|
const { rows: products } = await query(
|
||||||
|
'SELECT id, slug, name, stock FROM products WHERE id = $1',
|
||||||
|
[productId]
|
||||||
|
);
|
||||||
|
const product = products[0];
|
||||||
|
if (!product || product.stock <= 0) return { sent: 0 };
|
||||||
|
|
||||||
|
const { rows: alerts } = await query(
|
||||||
|
`SELECT id, email FROM product_stock_alerts
|
||||||
|
WHERE product_id = $1 AND notified_at IS NULL`,
|
||||||
|
[productId]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!alerts.length) return { sent: 0 };
|
||||||
|
|
||||||
|
const productUrl = `${siteUrl()}/product/${product.slug}`;
|
||||||
|
let sent = 0;
|
||||||
|
|
||||||
|
for (const alert of alerts) {
|
||||||
|
try {
|
||||||
|
await sendStockAvailableEmail(alert.email, product.name, productUrl);
|
||||||
|
await query(
|
||||||
|
'UPDATE product_stock_alerts SET notified_at = NOW() WHERE id = $1',
|
||||||
|
[alert.id]
|
||||||
|
);
|
||||||
|
sent++;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('stock alert email failed:', alert.email, err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { sent };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
isSubscribed,
|
||||||
|
subscribe,
|
||||||
|
notifyIfBackInStock,
|
||||||
|
};
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
const crypto = require('crypto');
|
||||||
|
const {
|
||||||
|
generateRegistrationOptions,
|
||||||
|
verifyRegistrationResponse,
|
||||||
|
generateAuthenticationOptions,
|
||||||
|
verifyAuthenticationResponse,
|
||||||
|
} = require('@simplewebauthn/server');
|
||||||
|
const { isoBase64URL } = require('@simplewebauthn/server/helpers');
|
||||||
|
const { query } = require('../db');
|
||||||
|
|
||||||
|
function getRpId() {
|
||||||
|
if (process.env.WEBAUTHN_RP_ID) {
|
||||||
|
return process.env.WEBAUTHN_RP_ID.trim();
|
||||||
|
}
|
||||||
|
const site = process.env.SITE_URL || 'http://localhost:3000';
|
||||||
|
try {
|
||||||
|
return new URL(site).hostname;
|
||||||
|
} catch {
|
||||||
|
return 'localhost';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getRpName() {
|
||||||
|
return process.env.WEBAUTHN_RP_NAME || 'Shop';
|
||||||
|
}
|
||||||
|
|
||||||
|
function getOrigins() {
|
||||||
|
const list = [];
|
||||||
|
if (process.env.SITE_URL) list.push(process.env.SITE_URL.replace(/\/$/, ''));
|
||||||
|
if (process.env.WEBAUTHN_ORIGIN) {
|
||||||
|
process.env.WEBAUTHN_ORIGIN.split(',').forEach((o) => {
|
||||||
|
const t = o.trim().replace(/\/$/, '');
|
||||||
|
if (t) list.push(t);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!list.length) list.push('http://localhost:3000');
|
||||||
|
const expanded = [...list];
|
||||||
|
for (const o of list) {
|
||||||
|
if (o.includes('localhost')) {
|
||||||
|
expanded.push(o.replace('localhost', '127.0.0.1'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...new Set(expanded)];
|
||||||
|
}
|
||||||
|
|
||||||
|
function getOriginFromRequest(req) {
|
||||||
|
const proto = req.get('x-forwarded-proto') || req.protocol;
|
||||||
|
const host = req.get('x-forwarded-host') || req.get('host');
|
||||||
|
return `${proto}://${host}`.replace(/\/$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertOrigin(req) {
|
||||||
|
const origin = getOriginFromRequest(req);
|
||||||
|
const allowed = getOrigins();
|
||||||
|
if (!allowed.includes(origin)) {
|
||||||
|
const err = new Error('Недопустимый origin для WebAuthn');
|
||||||
|
err.status = 400;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
return origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
function userIdToBuffer(userId) {
|
||||||
|
const buf = Buffer.alloc(8);
|
||||||
|
buf.writeBigUInt64BE(BigInt(userId), 0);
|
||||||
|
return new Uint8Array(buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getCredentialsForUser(userId) {
|
||||||
|
const { rows } = await query(
|
||||||
|
`SELECT id, credential_id, public_key, counter, device_type, backed_up, transports, label, created_at
|
||||||
|
FROM webauthn_credentials WHERE user_id = $1 ORDER BY created_at`,
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rowToAuthenticator(row) {
|
||||||
|
return {
|
||||||
|
id: row.credential_id,
|
||||||
|
publicKey: row.public_key,
|
||||||
|
counter: Number(row.counter),
|
||||||
|
transports: row.transports ? row.transports.split(',') : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function generateRegisterOptions(user, excludeIds = []) {
|
||||||
|
const credentials = await getCredentialsForUser(user.id);
|
||||||
|
return generateRegistrationOptions({
|
||||||
|
rpName: getRpName(),
|
||||||
|
rpID: getRpId(),
|
||||||
|
userName: user.email,
|
||||||
|
userDisplayName: user.name,
|
||||||
|
userID: userIdToBuffer(user.id),
|
||||||
|
attestationType: 'none',
|
||||||
|
excludeCredentials: credentials.map((c) => ({
|
||||||
|
id: c.credential_id,
|
||||||
|
transports: c.transports ? c.transports.split(',') : undefined,
|
||||||
|
})),
|
||||||
|
authenticatorSelection: {
|
||||||
|
residentKey: 'preferred',
|
||||||
|
userVerification: 'preferred',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verifyRegister(user, response, expectedChallenge, expectedOrigin) {
|
||||||
|
const verification = await verifyRegistrationResponse({
|
||||||
|
response,
|
||||||
|
expectedChallenge,
|
||||||
|
expectedOrigin,
|
||||||
|
expectedRPID: getRpId(),
|
||||||
|
requireUserVerification: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!verification.verified || !verification.registrationInfo) {
|
||||||
|
return { verified: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
const { credential, credentialDeviceType, credentialBackedUp } =
|
||||||
|
verification.registrationInfo;
|
||||||
|
|
||||||
|
const credentialId =
|
||||||
|
typeof credential.id === 'string'
|
||||||
|
? credential.id
|
||||||
|
: isoBase64URL.fromBuffer(credential.id);
|
||||||
|
const label =
|
||||||
|
credentialDeviceType === 'singleDevice' ? 'Это устройство' : 'Passkey';
|
||||||
|
|
||||||
|
await query(
|
||||||
|
`INSERT INTO webauthn_credentials
|
||||||
|
(user_id, credential_id, public_key, counter, device_type, backed_up, transports, label)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
||||||
|
[
|
||||||
|
user.id,
|
||||||
|
credentialId,
|
||||||
|
Buffer.from(credential.publicKey),
|
||||||
|
credential.counter,
|
||||||
|
credentialDeviceType,
|
||||||
|
credentialBackedUp,
|
||||||
|
credential.transports?.join(',') || null,
|
||||||
|
label,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
await query('UPDATE users SET passkey_enabled = true WHERE id = $1', [user.id]);
|
||||||
|
|
||||||
|
return { verified: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function generateLoginOptions(email) {
|
||||||
|
const { rows } = await query(
|
||||||
|
`SELECT id, email, name, passkey_enabled FROM users WHERE email = $1`,
|
||||||
|
[email.trim().toLowerCase()]
|
||||||
|
);
|
||||||
|
const user = rows[0];
|
||||||
|
if (!user || !user.passkey_enabled) {
|
||||||
|
return { user: null, options: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const credentials = await getCredentialsForUser(user.id);
|
||||||
|
if (!credentials.length) {
|
||||||
|
return { user: null, options: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const options = await generateAuthenticationOptions({
|
||||||
|
rpID: getRpId(),
|
||||||
|
allowCredentials: credentials.map((c) => ({
|
||||||
|
id: c.credential_id,
|
||||||
|
transports: c.transports ? c.transports.split(',') : undefined,
|
||||||
|
})),
|
||||||
|
userVerification: 'preferred',
|
||||||
|
});
|
||||||
|
|
||||||
|
return { user, options };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verifyLogin(user, response, expectedChallenge, expectedOrigin) {
|
||||||
|
const credentialId = response.id;
|
||||||
|
const { rows } = await query(
|
||||||
|
`SELECT * FROM webauthn_credentials WHERE user_id = $1 AND credential_id = $2`,
|
||||||
|
[user.id, credentialId]
|
||||||
|
);
|
||||||
|
const row = rows[0];
|
||||||
|
if (!row) {
|
||||||
|
return { verified: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
const verification = await verifyAuthenticationResponse({
|
||||||
|
response,
|
||||||
|
expectedChallenge,
|
||||||
|
expectedOrigin,
|
||||||
|
expectedRPID: getRpId(),
|
||||||
|
credential: rowToAuthenticator(row),
|
||||||
|
requireUserVerification: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!verification.verified) {
|
||||||
|
return { verified: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
const { newCounter } = verification.authenticationInfo;
|
||||||
|
await query('UPDATE webauthn_credentials SET counter = $1 WHERE id = $2', [
|
||||||
|
newCounter,
|
||||||
|
row.id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return { verified: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function disablePasskeys(userId) {
|
||||||
|
await query('DELETE FROM webauthn_credentials WHERE user_id = $1', [userId]);
|
||||||
|
await query('UPDATE users SET passkey_enabled = false WHERE id = $1', [userId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteCredential(userId, credentialDbId) {
|
||||||
|
const { rowCount } = await query(
|
||||||
|
'DELETE FROM webauthn_credentials WHERE id = $1 AND user_id = $2',
|
||||||
|
[credentialDbId, userId]
|
||||||
|
);
|
||||||
|
const remaining = await query(
|
||||||
|
'SELECT COUNT(*)::int AS n FROM webauthn_credentials WHERE user_id = $1',
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
if (remaining.rows[0].n === 0) {
|
||||||
|
await query('UPDATE users SET passkey_enabled = false WHERE id = $1', [userId]);
|
||||||
|
}
|
||||||
|
return rowCount > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getRpId,
|
||||||
|
getOrigins,
|
||||||
|
assertOrigin,
|
||||||
|
getCredentialsForUser,
|
||||||
|
generateRegisterOptions,
|
||||||
|
verifyRegister,
|
||||||
|
generateLoginOptions,
|
||||||
|
verifyLogin,
|
||||||
|
disablePasskeys,
|
||||||
|
deleteCredential,
|
||||||
|
};
|
||||||
@@ -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 };
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
<a href="/account?tab=profile" class="account-tabs__link <%= activeTab === 'profile' ? 'account-tabs__link--active' : '' %>">Профиль</a>
|
<a href="/account?tab=profile" class="account-tabs__link <%= activeTab === 'profile' ? 'account-tabs__link--active' : '' %>">Профиль</a>
|
||||||
<a href="/account?tab=email" class="account-tabs__link <%= activeTab === 'email' ? 'account-tabs__link--active' : '' %>">Смена email</a>
|
<a href="/account?tab=email" class="account-tabs__link <%= activeTab === 'email' ? 'account-tabs__link--active' : '' %>">Смена email</a>
|
||||||
<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=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>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
@@ -28,8 +29,15 @@
|
|||||||
<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>
|
||||||
<a href="/orders" class="btn btn--primary">Мои заказы</a>
|
<div class="account-actions">
|
||||||
|
<a href="/orders" class="btn btn--primary">Мои заказы</a>
|
||||||
|
<% if (isAdmin) { %>
|
||||||
|
<a href="/admin" class="btn btn--admin">Админ-панель</a>
|
||||||
|
<% } %>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="card account-section">
|
<section class="card account-section">
|
||||||
@@ -102,6 +110,68 @@
|
|||||||
</section>
|
</section>
|
||||||
<% } %>
|
<% } %>
|
||||||
|
|
||||||
|
<% if (activeTab === 'passkey') { %>
|
||||||
|
<section class="card account-section account-section--narrow">
|
||||||
|
<h2>Вход по passkey</h2>
|
||||||
|
<p class="muted">
|
||||||
|
Passkey — вход по отпечатку, Face ID или PIN устройства. Пароль остаётся доступен.
|
||||||
|
Включение необязательно: привяжите ключ, когда будете готовы.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<% if (user.passkey_enabled) { %>
|
||||||
|
<p class="alert alert--success" style="margin-bottom:1rem">Passkey включён</p>
|
||||||
|
<% } else { %>
|
||||||
|
<p class="muted" style="margin-bottom:1rem">Passkey не настроен</p>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
|
<% if (passkeys.length) { %>
|
||||||
|
<ul class="passkey-list">
|
||||||
|
<% passkeys.forEach(pk => { %>
|
||||||
|
<li class="passkey-list__item">
|
||||||
|
<span><strong><%= pk.label %></strong> · с <%= new Date(pk.created_at).toLocaleDateString('ru-RU') %></span>
|
||||||
|
<form action="/account/passkey/credentials/<%= pk.id %>/delete" method="post" class="inline-form">
|
||||||
|
<input type="password" name="current_password" class="input input--sm" placeholder="Пароль" required autocomplete="current-password" aria-label="Пароль для удаления">
|
||||||
|
<button type="submit" class="btn btn--ghost btn--sm">Удалить</button>
|
||||||
|
</form>
|
||||||
|
</li>
|
||||||
|
<% }) %>
|
||||||
|
</ul>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
|
<div class="passkey-actions">
|
||||||
|
<p id="passkey-register-error" class="alert alert--error" hidden></p>
|
||||||
|
<label class="label">
|
||||||
|
Текущий пароль (для привязки нового ключа)
|
||||||
|
<input type="password" id="passkey-register-password" class="input" autocomplete="current-password">
|
||||||
|
</label>
|
||||||
|
<button type="button" id="passkey-register-btn" class="btn btn--primary">Привязать passkey</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<% if (user.passkey_enabled) { %>
|
||||||
|
<hr class="divider">
|
||||||
|
<h3>Отключить passkey</h3>
|
||||||
|
<p class="muted">Все привязанные ключи будут удалены. Вход только по паролю.</p>
|
||||||
|
<form action="/account/passkey/disable" method="post" class="form">
|
||||||
|
<label class="label">
|
||||||
|
Текущий пароль
|
||||||
|
<input type="password" name="current_password" class="input" required autocomplete="current-password">
|
||||||
|
</label>
|
||||||
|
<button type="submit" class="btn btn--ghost">Отключить passkey</button>
|
||||||
|
</form>
|
||||||
|
<% } %>
|
||||||
|
</section>
|
||||||
|
<script src="/js/passkey.js"></script>
|
||||||
|
<script>
|
||||||
|
document.getElementById('passkey-register-btn')?.addEventListener('click', function () {
|
||||||
|
ShopPasskey.registerPasskey(
|
||||||
|
document.getElementById('passkey-register-password'),
|
||||||
|
document.getElementById('passkey-register-error'),
|
||||||
|
this
|
||||||
|
);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
<% if (activeTab === 'password') { %>
|
<% if (activeTab === 'password') { %>
|
||||||
<section class="card account-section account-section--narrow">
|
<section class="card account-section account-section--narrow">
|
||||||
<h2>Смена пароля</h2>
|
<h2>Смена пароля</h2>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
<a href="/admin/orders" 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/users" class="admin-nav__link">Пользователи</a>
|
||||||
<a href="/admin/products" 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="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
||||||
<a href="/" class="admin-nav__link">В магазин</a>
|
<a href="/" class="admin-nav__link">В магазин</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
<a href="/admin/orders" class="admin-nav__link admin-nav__link--active">Заказы</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/users" class="admin-nav__link">Пользователи</a>
|
||||||
<a href="/admin/products" 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="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
||||||
<a href="/" class="admin-nav__link">В магазин</a>
|
<a href="/" class="admin-nav__link">В магазин</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|||||||
@@ -1,40 +1,97 @@
|
|||||||
<%- include('../partials/layout-start') %>
|
<%- include('../partials/layout-start') %>
|
||||||
|
|
||||||
<div class="admin-header">
|
<div class="admin-header">
|
||||||
<h1>Товары</h1>
|
<h1>Товары — цены и скидки</h1>
|
||||||
<nav class="admin-nav">
|
<nav class="admin-nav">
|
||||||
<a href="/admin" class="admin-nav__link">Обзор</a>
|
<a href="/admin" class="admin-nav__link">Обзор</a>
|
||||||
<a href="/admin/orders" 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/users" class="admin-nav__link">Пользователи</a>
|
||||||
<a href="/admin/products" class="admin-nav__link admin-nav__link--active">Товары</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="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
||||||
<a href="/" class="admin-nav__link">В магазин</a>
|
<a href="/" class="admin-nav__link">В магазин</a>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<table class="cart-table">
|
<% if (stockUpdated) { %>
|
||||||
|
<p class="alert alert--success">
|
||||||
|
Остаток обновлён.<% if (notified > 0) { %> Уведомления о поступлении: <%= notified %>.<% } %>
|
||||||
|
</p>
|
||||||
|
<% } %>
|
||||||
|
<% if (pricingUpdated) { %><p class="alert alert--success">Цены обновлены</p><% } %>
|
||||||
|
<% if (pricingError) { %><p class="alert alert--error"><%= pricingError %></p><% } %>
|
||||||
|
|
||||||
|
<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>
|
||||||
</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>
|
||||||
<td><%= p.name %></td>
|
<strong><%= p.name %></strong><br>
|
||||||
<td><%= p.category_name || '—' %></td>
|
<span class="muted"><%= p.category_name || '—' %></span>
|
||||||
<td><%= formatPrice(p.price_cents) %></td>
|
<% if (onSale) { %>
|
||||||
<td><%= p.stock %></td>
|
<br><span class="badge badge--sale">−<%= salePercent(p) %>% на сайте</span>
|
||||||
|
<% } %>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<form action="/admin/products/<%= p.id %>/pricing" method="post" class="admin-pricing-form">
|
||||||
|
<label class="label label--inline">
|
||||||
|
Цена
|
||||||
|
<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>
|
||||||
|
<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,115 @@
|
|||||||
|
<%- include('../partials/layout-start') %>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
</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') %>
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
<a href="/admin/orders" 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/users" class="admin-nav__link">Пользователи</a>
|
||||||
<a href="/admin/products" 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="/admin/reservations" class="admin-nav__link admin-nav__link--active">Бронирования</a>
|
||||||
<a href="/" class="admin-nav__link">В магазин</a>
|
<a href="/" class="admin-nav__link">В магазин</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|||||||
@@ -7,11 +7,17 @@
|
|||||||
<a href="/admin/orders" 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/users" class="admin-nav__link admin-nav__link--active">Пользователи</a>
|
||||||
<a href="/admin/products" 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="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
||||||
<a href="/" class="admin-nav__link">В магазин</a>
|
<a href="/" class="admin-nav__link">В магазин</a>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<p class="muted admin-hint">
|
||||||
|
Один администратор — зарегистрированный пользователь с email из <code>ADMIN_EMAIL</code> в <code>.env</code>.
|
||||||
|
Остальные при регистрации получают роль «Клиент».
|
||||||
|
</p>
|
||||||
|
|
||||||
<table class="cart-table">
|
<table class="cart-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
|
|||||||
+76
-7
@@ -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,7 +29,14 @@
|
|||||||
<% } %>
|
<% } %>
|
||||||
<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>
|
||||||
|
<% 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>
|
||||||
<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>
|
||||||
@@ -39,16 +48,76 @@
|
|||||||
<% }) %>
|
<% }) %>
|
||||||
</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">
|
||||||
<% } else { %>
|
<h2 class="promo-box__title">Баллы лояльности</h2>
|
||||||
<p class="hint"><a href="/login?next=/checkout">Войдите</a>, чтобы оформить заказ.</p>
|
<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 { %>
|
||||||
|
<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') %>
|
||||||
|
|||||||
+1
-1
@@ -32,7 +32,7 @@
|
|||||||
<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 }) %>
|
||||||
<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">
|
||||||
|
|||||||
+23
-4
@@ -4,21 +4,40 @@
|
|||||||
<form action="/login" method="post" class="form card">
|
<form action="/login" method="post" class="form card">
|
||||||
<h1>Вход</h1>
|
<h1>Вход</h1>
|
||||||
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %>
|
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %>
|
||||||
<input type="hidden" name="next" value="<%= next %>">
|
<input type="hidden" name="next" id="login-next" value="<%= next %>">
|
||||||
<label class="label">
|
<label class="label">
|
||||||
Email
|
Email
|
||||||
<input type="email" name="email" class="input" required value="<%= values.email || '' %>">
|
<input type="email" name="email" id="login-email" class="input" required value="<%= values.email || '' %>">
|
||||||
</label>
|
</label>
|
||||||
<label class="label">
|
<label class="label">
|
||||||
Пароль
|
Пароль
|
||||||
<input type="password" name="password" class="input" required>
|
<input type="password" name="password" class="input" required autocomplete="current-password">
|
||||||
</label>
|
</label>
|
||||||
<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>
|
||||||
Нет аккаунта? <a href="/register">Регистрация</a>
|
Нет аккаунта? <a href="/register">Регистрация</a>
|
||||||
</p>
|
</p>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
<div class="card passkey-login">
|
||||||
|
<h2 class="passkey-login__title">Или passkey</h2>
|
||||||
|
<p class="muted passkey-login__hint">Если в профиле включён passkey — войдите без пароля (нужен тот же email).</p>
|
||||||
|
<p id="passkey-login-error" class="alert alert--error" hidden></p>
|
||||||
|
<button type="button" id="passkey-login-btn" class="btn btn--ghost btn--block">Войти с passkey</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<script src="/js/passkey.js"></script>
|
||||||
|
<script>
|
||||||
|
document.getElementById('passkey-login-btn')?.addEventListener('click', function () {
|
||||||
|
ShopPasskey.loginWithPasskey(
|
||||||
|
document.getElementById('login-email'),
|
||||||
|
document.getElementById('login-next'),
|
||||||
|
document.getElementById('passkey-login-error'),
|
||||||
|
this
|
||||||
|
);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
<%- include('partials/layout-end') %>
|
<%- include('partials/layout-end') %>
|
||||||
|
|||||||
+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,11 @@
|
|||||||
|
<% 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' : '' %>">
|
||||||
|
<% 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>
|
||||||
|
<% } %>
|
||||||
|
</p>
|
||||||
+39
-1
@@ -13,11 +13,20 @@
|
|||||||
<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 }) %>
|
||||||
|
<% if (isSaleActive(product) && product.sale_ends_at) { %>
|
||||||
|
<div class="promo-countdown" data-expires="<%= product.sale_ends_at %>">
|
||||||
|
Акция заканчивается: <span class="promo-countdown__timer">—</span>
|
||||||
|
</div>
|
||||||
|
<% } %>
|
||||||
|
</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>
|
||||||
|
|
||||||
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %>
|
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %>
|
||||||
|
<% if (notifySuccess) { %><p class="alert alert--success"><%= notifySuccess %></p><% } %>
|
||||||
|
<% if (notifyError) { %><p class="alert alert--error"><%= notifyError %></p><% } %>
|
||||||
<% if (reserved) { %><p class="alert alert--success">Товар успешно забронирован. Подробности на почте и в личном кабинете.</p><% } %>
|
<% if (reserved) { %><p class="alert alert--success">Товар успешно забронирован. Подробности на почте и в личном кабинете.</p><% } %>
|
||||||
<% if (userReservation) { %>
|
<% if (userReservation) { %>
|
||||||
<p class="alert alert--success">
|
<p class="alert alert--success">
|
||||||
@@ -52,9 +61,38 @@
|
|||||||
<% } %>
|
<% } %>
|
||||||
<% } else { %>
|
<% } else { %>
|
||||||
<p class="alert alert--warn">Нет в наличии</p>
|
<p class="alert alert--warn">Нет в наличии</p>
|
||||||
|
|
||||||
|
<% if (typeof cookieConsent !== 'undefined' && !cookieConsent) { %>
|
||||||
|
<p class="muted">Примите cookies, чтобы подписаться на уведомление о поступлении.</p>
|
||||||
|
<% } else if (stockAlertSubscribed) { %>
|
||||||
|
<p class="stock-notify stock-notify--done">
|
||||||
|
Вы подписаны на уведомление<% if (notifyEmail) { %> — письмо придёт на <strong><%= notifyEmail %></strong><% } %>.
|
||||||
|
</p>
|
||||||
|
<% } else { %>
|
||||||
|
<section class="stock-notify card">
|
||||||
|
<h2 class="stock-notify__title">Сообщить о поступлении</h2>
|
||||||
|
<p class="muted stock-notify__hint">Будьте среди первых, кто узнает, когда товар снова появится в наличии.</p>
|
||||||
|
<form action="/product/<%= product.slug %>/notify-stock" method="post" class="form stock-notify__form">
|
||||||
|
<% if (user && notifyEmail) { %>
|
||||||
|
<p class="muted">Уведомление отправим на <strong><%= notifyEmail %></strong></p>
|
||||||
|
<input type="hidden" name="email" value="<%= notifyEmail %>">
|
||||||
|
<% } else { %>
|
||||||
|
<label class="label">
|
||||||
|
Email
|
||||||
|
<input type="email" name="email" class="input" required autocomplete="email" placeholder="you@example.com" value="<%= notifyEmail || '' %>">
|
||||||
|
</label>
|
||||||
|
<% } %>
|
||||||
|
<button type="submit" class="btn btn--primary">Подписаться</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
<% } %>
|
||||||
<% } %>
|
<% } %>
|
||||||
<a href="/" class="link-back">← Назад в каталог</a>
|
<a href="/" class="link-back">← Назад в каталог</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') %>
|
||||||
|
|||||||
+44
-14
@@ -1,4 +1,4 @@
|
|||||||
# Shop — документация v0.10.0
|
# Shop — документация
|
||||||
|
|
||||||
Интернет-магазин на **Node.js** и **PostgreSQL 17**.
|
Интернет-магазин на **Node.js** и **PostgreSQL 17**.
|
||||||
|
|
||||||
@@ -7,7 +7,8 @@
|
|||||||
| Способ | Когда использовать |
|
| Способ | Когда использовать |
|
||||||
|--------|-------------------|
|
|--------|-------------------|
|
||||||
| **[Установка через Docker](Install-Docker)** | Быстрый старт, тест, изолированное окружение |
|
| **[Установка через Docker](Install-Docker)** | Быстрый старт, тест, изолированное окружение |
|
||||||
| **[Установка без Docker](Install-Native)** | Production на Ubuntu, systemd, свой Caddy |
|
| **[Установка без Docker](Install-Native)** | Production на Ubuntu, systemd, Caddy |
|
||||||
|
| **[Сервер: установка и обновление](Server-Operations)** | Обновления, systemd, типичные ошибки |
|
||||||
|
|
||||||
## Требования
|
## Требования
|
||||||
|
|
||||||
@@ -15,27 +16,57 @@
|
|||||||
|
|
||||||
**Без Docker:** Ubuntu 22.04 / 24.04, Node.js 20, PostgreSQL 17.
|
**Без Docker:** Ubuntu 22.04 / 24.04, Node.js 20, PostgreSQL 17.
|
||||||
|
|
||||||
## Быстрый старт
|
## Роли
|
||||||
|
|
||||||
### Docker (3 команды)
|
| Роль | Кто |
|
||||||
|
|------|-----|
|
||||||
|
| **customer** | Все, кто регистрируется через сайт |
|
||||||
|
| **admin** | **Один** пользователь — email из `ADMIN_EMAIL` в `.env` (по умолчанию `admin@site.com` / пароль `admin`) |
|
||||||
|
|
||||||
|
Админ-панель доступна только этому аккаунту.
|
||||||
|
|
||||||
|
## Установщик
|
||||||
|
|
||||||
|
Интерактивно: админ, PostgreSQL, Docker или Ubuntu:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://git.evilfox.cc/test/shop10.git && cd shop10
|
bash scripts/install.sh
|
||||||
git checkout v0.10.0
|
```
|
||||||
cp .env.docker.example .env && docker compose up -d --build
|
|
||||||
|
## Быстрый старт
|
||||||
|
|
||||||
|
### Docker
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone <URL-вашего-репозитория> shop
|
||||||
|
cd shop
|
||||||
|
cp .env.docker.example .env
|
||||||
|
docker compose up -d --build
|
||||||
```
|
```
|
||||||
|
|
||||||
Сайт: http://localhost:3000
|
Сайт: http://localhost:3000
|
||||||
|
|
||||||
### Без Docker
|
### Без Docker (сервер)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://git.evilfox.cc/test/shop10.git && cd shop10
|
export SHOP_ROOT=/opt/shop
|
||||||
git checkout v0.10.0
|
export GIT_REPO_URL='<URL-вашего-репозитория>'
|
||||||
# см. Install-Native
|
|
||||||
|
git clone "$GIT_REPO_URL" "$SHOP_ROOT"
|
||||||
|
cd "$SHOP_ROOT"
|
||||||
|
sudo bash scripts/quick-deploy-ubuntu.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
## Проверка работы
|
Обновление (рекомендуется):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export SHOP_ROOT=/opt/shop/shop10
|
||||||
|
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||||
|
```
|
||||||
|
|
||||||
|
Путь `SHOP_ROOT` — ваш каталог клона (см. [Server-Operations](Server-Operations)).
|
||||||
|
|
||||||
|
## Проверка
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -s http://127.0.0.1:3000/health
|
curl -s http://127.0.0.1:3000/health
|
||||||
@@ -45,6 +76,5 @@ curl -s http://127.0.0.1:3000/health
|
|||||||
|
|
||||||
## Ссылки
|
## Ссылки
|
||||||
|
|
||||||
- [Репозиторий](https://git.evilfox.cc/test/shop10)
|
|
||||||
- [Releases](https://git.evilfox.cc/test/shop10/releases)
|
|
||||||
- [Решение проблем](Troubleshooting)
|
- [Решение проблем](Troubleshooting)
|
||||||
|
- [Сервер: установка и обновление](Server-Operations)
|
||||||
|
|||||||
+43
-181
@@ -1,244 +1,106 @@
|
|||||||
# Установка без Docker (Ubuntu)
|
# Установка без Docker (Ubuntu)
|
||||||
|
|
||||||
Production-развёртывание на **Ubuntu 22.04 / 24.04**: Node.js 20, PostgreSQL 17, systemd, опционально Caddy.
|
Production: Node.js 20, PostgreSQL 17, systemd, опционально Caddy.
|
||||||
|
|
||||||
|
**Полное руководство по ошибкам и обновлениям:** [Server-Operations](Server-Operations).
|
||||||
|
|
||||||
|
Задайте каталог клона:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export SHOP_ROOT=/opt/shop
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 1. Требования
|
## 1. Требования
|
||||||
|
|
||||||
- Сервер Ubuntu 22.04 или 24.04 (root или sudo)
|
- Ubuntu 22.04 или 24.04
|
||||||
- Минимум 1 GB RAM, 10 GB диск
|
- Порты 22, 80, 443 (для Caddy)
|
||||||
- Открыты порты **22**, **80**, **443** (если используете Caddy)
|
- Порт 3000 только localhost
|
||||||
- Порт **3000** наружу не открывать — только localhost
|
|
||||||
|
|
||||||
## 2. Установка системных пакетов
|
## 2. Системные пакеты
|
||||||
|
|
||||||
```bash
|
### Node.js 20
|
||||||
apt update
|
|
||||||
apt install -y git curl ca-certificates
|
|
||||||
```
|
|
||||||
|
|
||||||
### Node.js 20 LTS
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||||
apt install -y nodejs
|
apt install -y nodejs git curl
|
||||||
node -v # v20.x
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### PostgreSQL 17
|
### PostgreSQL 17
|
||||||
|
|
||||||
|
Не используйте `apt install postgresql-17` без PGDG:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
apt install -y postgresql-17 postgresql-client-17
|
sudo bash "$SHOP_ROOT/scripts/install-postgresql-ubuntu.sh"
|
||||||
systemctl enable postgresql
|
|
||||||
systemctl start postgresql
|
|
||||||
pg_isready -h 127.0.0.1 -p 5432
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Если пакет `postgresql-17` не найден — [репозиторий PGDG](https://www.postgresql.org/download/linux/ubuntu/):
|
## 3. Клонирование
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
apt install -y curl ca-certificates
|
export GIT_REPO_URL='<URL-вашего-репозитория>'
|
||||||
install -d /usr/share/postgresql-common/pgdg
|
git clone "$GIT_REPO_URL" "$SHOP_ROOT"
|
||||||
curl -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc --fail \
|
cd "$SHOP_ROOT"
|
||||||
https://www.postgresql.org/media/keys/ACCC4CF8.asc
|
|
||||||
sh -c 'echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $(. /etc/os-release && echo ${VERSION_CODENAME}-pgdg) main" > /etc/apt/sources.list.d/pgdg.list'
|
|
||||||
apt update
|
|
||||||
apt install -y postgresql-17 postgresql-client-17
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 3. Клонирование проекта
|
Или: `sudo SHOP_GIT_URL="$GIT_REPO_URL" bash scripts/quick-deploy-ubuntu.sh`
|
||||||
|
|
||||||
|
## 4. База данных
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /opt
|
cd "$SHOP_ROOT"
|
||||||
git clone https://git.evilfox.cc/test/shop10.git shop
|
|
||||||
cd shop
|
|
||||||
git checkout v0.10.0
|
|
||||||
```
|
|
||||||
|
|
||||||
## 4. База данных PostgreSQL
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd /opt/shop
|
|
||||||
bash scripts/setup-postgres-ubuntu.sh
|
bash scripts/setup-postgres-ubuntu.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
Скрипт:
|
## 5. `.env`
|
||||||
- запускает PostgreSQL;
|
|
||||||
- создаёт пользователя и БД `shop` (по умолчанию пароль `shop` — **смените в production**);
|
|
||||||
- выводит строку `DATABASE_URL`.
|
|
||||||
|
|
||||||
Проверка:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
psql "postgresql://shop:shop@127.0.0.1:5432/shop" -c "SELECT 1"
|
|
||||||
```
|
|
||||||
|
|
||||||
## 5. Файл окружения `.env`
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
nano .env
|
nano .env
|
||||||
```
|
```
|
||||||
|
|
||||||
Обязательные параметры:
|
`SESSION_SECRET`, `DATABASE_URL`, `SITE_URL` (ваш публичный URL без привязки к конкретному домену в коде).
|
||||||
|
|
||||||
```env
|
## 6. Зависимости
|
||||||
PORT=3000
|
|
||||||
HOST=127.0.0.1
|
|
||||||
NODE_ENV=production
|
|
||||||
TRUST_PROXY=1
|
|
||||||
SESSION_SECRET=сгенерируйте_длинную_строку
|
|
||||||
DATABASE_URL=postgresql://shop:ВАШ_ПАРОЛЬ@127.0.0.1:5432/shop
|
|
||||||
```
|
|
||||||
|
|
||||||
Секрет сессии:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
openssl rand -hex 32
|
|
||||||
```
|
|
||||||
|
|
||||||
`HOST=127.0.0.1` — приложение доступно только локально; снаружи — через Caddy.
|
|
||||||
|
|
||||||
## 6. Установка зависимостей Node.js
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd /opt/shop
|
|
||||||
npm install --omit=dev
|
npm install --omit=dev
|
||||||
```
|
```
|
||||||
|
|
||||||
При первом запуске приложение создаст таблицы и демо-товары (если каталог пуст).
|
## 7. systemd
|
||||||
|
|
||||||
## 7. Служба systemd
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cp /opt/shop/deploy/shop.service /etc/systemd/system/shop.service
|
sudo bash scripts/install-shop-service.sh
|
||||||
systemctl daemon-reload
|
|
||||||
systemctl enable shop
|
|
||||||
systemctl start shop
|
|
||||||
systemctl status shop
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Unit ждёт PostgreSQL (`ExecStartPre` + `pg_isready`) и запускает Node от пользователя `www-data`.
|
`WorkingDirectory` в unit = `$SHOP_ROOT`. Не делайте `chown -R www-data` на весь репозиторий.
|
||||||
|
|
||||||
**Важно:** не выполняйте `chown -R www-data /opt/shop` — это ломает `git pull`. Права на запись нужны только для каталога `data/` (если используется); с PostgreSQL каталог `data/` не обязателен.
|
## 8. Caddy
|
||||||
|
|
||||||
Логи:
|
После `curl http://127.0.0.1:3000/health` → OK:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
journalctl -u shop -f
|
cp "$SHOP_ROOT/caddy/Caddyfile.example" /etc/caddy/Caddyfile
|
||||||
```
|
# укажите ваш домен в Caddyfile
|
||||||
|
|
||||||
## 8. Проверка backend
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -s http://127.0.0.1:3000/health
|
|
||||||
ss -tlnp | grep 3000
|
|
||||||
```
|
|
||||||
|
|
||||||
В логах должно быть: `Магазин: http://127.0.0.1:3000 (PostgreSQL)`
|
|
||||||
|
|
||||||
## 9. Caddy — HTTPS и reverse proxy
|
|
||||||
|
|
||||||
Установка Caddy:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
apt install -y debian-keyring debian-archive-keyring apt-transport-https
|
|
||||||
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
|
|
||||||
| gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
|
|
||||||
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
|
|
||||||
| tee /etc/apt/sources.list.d/caddy-stable.list
|
|
||||||
apt update && apt install -y caddy
|
|
||||||
```
|
|
||||||
|
|
||||||
Конфигурация:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cp /opt/shop/caddy/Caddyfile.example /etc/caddy/Caddyfile
|
|
||||||
nano /etc/caddy/Caddyfile
|
|
||||||
```
|
|
||||||
|
|
||||||
Пример (замените домен и email):
|
|
||||||
|
|
||||||
```caddyfile
|
|
||||||
{
|
|
||||||
email admin@example.com
|
|
||||||
}
|
|
||||||
|
|
||||||
shop.example.com {
|
|
||||||
encode gzip zstd
|
|
||||||
reverse_proxy 127.0.0.1:3000
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```bash
|
|
||||||
caddy validate --config /etc/caddy/Caddyfile
|
|
||||||
systemctl enable caddy
|
|
||||||
systemctl reload caddy
|
systemctl reload caddy
|
||||||
```
|
```
|
||||||
|
|
||||||
Файрвол:
|
## 9. Обновление
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
ufw allow 22/tcp
|
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||||
ufw allow 80/tcp
|
|
||||||
ufw allow 443/tcp
|
|
||||||
ufw enable
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Зависимость Caddy от shop (опционально):
|
## 10. Архитектура
|
||||||
|
|
||||||
```bash
|
|
||||||
mkdir -p /etc/systemd/system/caddy.service.d
|
|
||||||
cp /opt/shop/deploy/caddy-after-shop.conf /etc/systemd/system/caddy.service.d/shop.conf
|
|
||||||
systemctl daemon-reload
|
|
||||||
```
|
|
||||||
|
|
||||||
## 10. Обновление
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd /opt/shop
|
|
||||||
git config --global --add safe.directory /opt/shop
|
|
||||||
bash scripts/server-update.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
Или вручную:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git pull
|
|
||||||
npm install --omit=dev
|
|
||||||
systemctl restart shop
|
|
||||||
curl -s http://127.0.0.1:3000/health
|
|
||||||
systemctl reload caddy
|
|
||||||
```
|
|
||||||
|
|
||||||
## 11. Переход с SQLite (старая версия)
|
|
||||||
|
|
||||||
1. Установите PostgreSQL (шаги 2–4)
|
|
||||||
2. Добавьте `DATABASE_URL` в `.env`
|
|
||||||
3. `git pull` → `npm install` → `systemctl restart shop`
|
|
||||||
4. Демо-товары появятся автоматически; пользователей нужно зарегистрировать заново
|
|
||||||
|
|
||||||
Быстрое исправление подключения к БД:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
bash /opt/shop/scripts/fix-db-connection.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
## 12. Архитектура
|
|
||||||
|
|
||||||
```
|
```
|
||||||
Интернет → Caddy :443 → 127.0.0.1:3000 (Node.js shop)
|
Интернет → Caddy :443 → 127.0.0.1:3000 (Node.js)
|
||||||
↓
|
↓
|
||||||
PostgreSQL 127.0.0.1:5432
|
PostgreSQL 127.0.0.1:5432
|
||||||
```
|
```
|
||||||
|
|
||||||
## 13. Резервное копирование БД
|
## 11. Резервное копирование
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo -u postgres pg_dump shop > shop_backup_$(date +%F).sql
|
sudo -u postgres pg_dump shop > shop_backup_$(date +%F).sql
|
||||||
```
|
```
|
||||||
|
|
||||||
Восстановление:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo -u postgres psql shop < shop_backup_2026-05-17.sql
|
|
||||||
```
|
|
||||||
|
|||||||
@@ -0,0 +1,218 @@
|
|||||||
|
# Сервер: установка и обновление
|
||||||
|
|
||||||
|
Инструкция **без привязки к конкретному домену или хостингу**. Подставьте свои значения:
|
||||||
|
|
||||||
|
| Переменная | Что это | Пример |
|
||||||
|
|------------|---------|--------|
|
||||||
|
| `SHOP_ROOT` | Каталог клона, где лежат `package.json` и `scripts/` | `/opt/shop` |
|
||||||
|
| `GIT_REPO_URL` | URL вашего git-репозитория | `https://forge.example.com/user/shop.git` |
|
||||||
|
| `SITE_URL` | Публичный URL магазина (для писем и passkey) | `https://shop.example.com` |
|
||||||
|
|
||||||
|
Проверка каталога:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export SHOP_ROOT=/opt/shop
|
||||||
|
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)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export SHOP_ROOT=/opt/shop
|
||||||
|
export GIT_REPO_URL='https://ВАШ-FORGE/путь/к/shop.git'
|
||||||
|
|
||||||
|
apt update && apt install -y git curl
|
||||||
|
git clone "$GIT_REPO_URL" "$SHOP_ROOT"
|
||||||
|
cd "$SHOP_ROOT"
|
||||||
|
|
||||||
|
sudo SHOP_INSTALL_DIR="$SHOP_ROOT" SHOP_GIT_URL="$GIT_REPO_URL" \
|
||||||
|
bash scripts/quick-deploy-ubuntu.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Скрипт: Node.js (если нет), PostgreSQL (PGDG), `.env`, `npm install`, служба **shop** (systemd).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Обновление кода (сайт уже работает)
|
||||||
|
|
||||||
|
**Рекомендуется** — две команды (можно из любого каталога, не нужен `cd`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export SHOP_ROOT=/opt/shop/shop10
|
||||||
|
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||||
|
```
|
||||||
|
|
||||||
|
Подставьте свой путь к клону (где лежит `package.json`). Часто это `/opt/shop` или `/opt/shop/shop10`.
|
||||||
|
|
||||||
|
Почему так надёжнее, чем `cd /opt/shop && git pull`:
|
||||||
|
|
||||||
|
- явно задан каталог репозитория (`SHOP_ROOT`);
|
||||||
|
- внутри выполняются `git-sync` (ветка `main`), `npm install`, перезапуск `shop`, проверка `/health`;
|
||||||
|
- не перепутаете родительскую папку без `package.json` и скриптов.
|
||||||
|
|
||||||
|
Проверка после обновления:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
systemctl status shop
|
||||||
|
curl -s http://127.0.0.1:3000/health
|
||||||
|
```
|
||||||
|
|
||||||
|
Если git в detached HEAD отдельно:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd "$SHOP_ROOT"
|
||||||
|
bash scripts/git-sync.sh
|
||||||
|
bash scripts/server-update.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Скрипты в `scripts/`
|
||||||
|
|
||||||
|
| Скрипт | Назначение |
|
||||||
|
|--------|------------|
|
||||||
|
| `install.sh` | **Интерактивная установка** (Docker или Ubuntu) |
|
||||||
|
| `quick-deploy-ubuntu.sh` | Первая установка / полный цикл (без вопросов) |
|
||||||
|
| `server-update.sh` | `git pull`, `npm install`, перезапуск shop |
|
||||||
|
| `git-sync.sh` | Исправить detached HEAD, синхронизация с `main` |
|
||||||
|
| `install-postgresql-ubuntu.sh` | PostgreSQL 17 через PGDG |
|
||||||
|
| `setup-postgres-ubuntu.sh` | Пользователь и БД `shop` |
|
||||||
|
| `install-shop-service.sh` | Установка systemd unit |
|
||||||
|
| `free-port-3000.sh` | Освободить порт (старый `npm start`) |
|
||||||
|
| `fix-db-connection.sh` | ECONNREFUSED :5432 |
|
||||||
|
| `diagnose-502.sh` | HTTP 502, Caddy |
|
||||||
|
| `diagnose-shop-service.sh` | Падение shop.service |
|
||||||
|
|
||||||
|
Все скрипты сами ищут `SHOP_ROOT` (каталог, откуда вызван `scripts/`, или переменная окружения).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Частые ошибки
|
||||||
|
|
||||||
|
### `Unable to locate package postgresql-17`
|
||||||
|
|
||||||
|
В стандартном Ubuntu нет пакета 17. Не копируйте `apt install postgresql-17` из старых заметок.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo bash "$SHOP_ROOT/scripts/install-postgresql-ubuntu.sh"
|
||||||
|
bash "$SHOP_ROOT/scripts/setup-postgres-ubuntu.sh"
|
||||||
|
```
|
||||||
|
|
||||||
|
### `URL_РЕПОЗИТОРИЯ: No such file` или placeholder в команде
|
||||||
|
|
||||||
|
В документации иногда указан **шаблон**, а не команда. Клонируйте так:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone 'https://ВАШ-FORGE/shop.git' "$SHOP_ROOT"
|
||||||
|
```
|
||||||
|
|
||||||
|
### `package.json` ENOENT в `/opt/shop`
|
||||||
|
|
||||||
|
Вы в **родительской** папке, а клон в подкаталоге (или наоборот).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
find /opt -name package.json 2>/dev/null
|
||||||
|
export SHOP_ROOT=/путь/где/найден
|
||||||
|
cd "$SHOP_ROOT"
|
||||||
|
```
|
||||||
|
|
||||||
|
### `You are not currently on a branch`
|
||||||
|
|
||||||
|
После `git checkout v0.x.x` репозиторий в detached HEAD.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd "$SHOP_ROOT"
|
||||||
|
bash scripts/git-sync.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
### `scripts/...: No such file or directory`
|
||||||
|
|
||||||
|
Запуск не из клона. Используйте полный путь:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||||
|
```
|
||||||
|
|
||||||
|
### `Служба shop не установлена` / `Unit shop.service could not be found`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd "$SHOP_ROOT"
|
||||||
|
sudo bash scripts/install-shop-service.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
В `/etc/systemd/system/shop.service` поля `WorkingDirectory` и `EnvironmentFile` должны указывать на **`$SHOP_ROOT`**.
|
||||||
|
|
||||||
|
### `shop.service: status=1/FAILURE`, `activating (auto-restart)`
|
||||||
|
|
||||||
|
1. **Порт 3000 занят** (старый ручной Node) — health отвечает, systemd падает:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo bash "$SHOP_ROOT/scripts/free-port-3000.sh"
|
||||||
|
sudo systemctl restart shop
|
||||||
|
systemctl status shop
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **PostgreSQL** — смотрите лог:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
journalctl -u shop -n 40 --no-pager
|
||||||
|
bash "$SHOP_ROOT/scripts/diagnose-shop-service.sh"
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **`.env` не в `SHOP_ROOT`** — скопируйте с прежнего места:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp /старый/путь/.env "$SHOP_ROOT/.env"
|
||||||
|
sudo bash "$SHOP_ROOT/scripts/install-shop-service.sh"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Изменения в git не видны на сайте
|
||||||
|
|
||||||
|
Обновление делали не в том каталоге или служба смотрит на другой путь:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd "$SHOP_ROOT" && git log -1 --oneline
|
||||||
|
grep WorkingDirectory /etc/systemd/system/shop.service
|
||||||
|
bash scripts/server-update.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Проверка
|
||||||
|
|
||||||
|
```bash
|
||||||
|
systemctl status shop
|
||||||
|
curl -s http://127.0.0.1:3000/health
|
||||||
|
```
|
||||||
|
|
||||||
|
Ожидается: `{"ok":true,"service":"shop","database":"postgresql"}` и **`Active: active (running)`**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Caddy / HTTPS
|
||||||
|
|
||||||
|
Пока `curl http://127.0.0.1:3000/health` не OK, reverse proxy будет отдавать **502**. Сначала backend, потом Caddy.
|
||||||
|
|
||||||
|
См. также: [Решение проблем](Troubleshooting), [Установка без Docker](Install-Native).
|
||||||
+57
-56
@@ -1,71 +1,65 @@
|
|||||||
# Решение проблем
|
# Решение проблем
|
||||||
|
|
||||||
## Диагностика одной командой
|
Полное руководство по развёртыванию: **[Сервер: установка и обновление](Server-Operations)**.
|
||||||
|
|
||||||
|
**Обновление на сервере (рекомендуется):**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bash /opt/shop/scripts/diagnose-502.sh
|
export SHOP_ROOT=/opt/shop/shop10
|
||||||
|
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`SHOP_ROOT` — каталог с `package.json` (у вас может быть `/opt/shop`).
|
||||||
|
|
||||||
|
Перед диагностикой:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export SHOP_ROOT=/opt/shop/shop10
|
||||||
|
cd "$SHOP_ROOT"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Диагностика
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash "$SHOP_ROOT/scripts/diagnose-502.sh"
|
||||||
|
bash "$SHOP_ROOT/scripts/diagnose-shop-service.sh"
|
||||||
|
journalctl -u shop -n 50 --no-pager
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Краткая таблица ошибок
|
||||||
|
|
||||||
|
| Симптом | Что делать |
|
||||||
|
|---------|------------|
|
||||||
|
| `postgresql-17` not found | `sudo bash scripts/install-postgresql-ubuntu.sh` |
|
||||||
|
| Placeholder / `URL_РЕПОЗИТОРИЯ` | `git clone <ваш-url> "$SHOP_ROOT"` — не копировать шаблоны как команды |
|
||||||
|
| Нет `package.json` | `find /opt -name package.json`; `cd` в найденный каталог |
|
||||||
|
| detached HEAD | `bash scripts/git-sync.sh` |
|
||||||
|
| Нет `scripts/...` | `bash "$SHOP_ROOT/scripts/server-update.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` |
|
||||||
|
| 502 в браузере | `curl http://127.0.0.1:3000/health` — сначала backend |
|
||||||
|
| ECONNREFUSED :5432 | `bash scripts/fix-db-connection.sh` |
|
||||||
|
|
||||||
|
Подробности — в [Server-Operations](Server-Operations).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## HTTP 502 (Caddy / браузер)
|
## HTTP 502 (Caddy / браузер)
|
||||||
|
|
||||||
**SSL работает, страница 502** — Caddy жив, backend (Node) не отвечает.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -s http://127.0.0.1:3000/health
|
curl -s http://127.0.0.1:3000/health
|
||||||
systemctl status shop
|
systemctl status shop
|
||||||
journalctl -u shop -n 30 --no-pager
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Пока `/health` не OK — Caddy будет отдавать 502.
|
Пока `/health` не OK — Caddy будет отдавать 502.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ECONNREFUSED 127.0.0.1:5432
|
## Docker
|
||||||
|
|
||||||
PostgreSQL не запущен или не установлен.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
bash /opt/shop/scripts/fix-db-connection.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
Или вручную:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
systemctl start postgresql
|
|
||||||
pg_isready -h 127.0.0.1 -p 5432
|
|
||||||
bash scripts/setup-postgres-ubuntu.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
Проверьте `DATABASE_URL` в `/opt/shop/.env`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Служба shop сразу останавливается
|
|
||||||
|
|
||||||
В логе только «База уже содержит товары» без строки `Магазин: http://...`:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd /opt/shop && git pull # нужен исправленный seed.js (v0.10.0+)
|
|
||||||
systemctl restart shop
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## dubious ownership (git pull)
|
|
||||||
|
|
||||||
Не делайте `chown -R www-data /opt/shop`.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
chown -R root:root /opt/shop
|
|
||||||
git config --global --add safe.directory /opt/shop
|
|
||||||
git pull
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Docker: контейнер app unhealthy
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose logs app
|
docker compose logs app
|
||||||
@@ -73,16 +67,23 @@ docker compose logs postgres
|
|||||||
docker compose up -d --build
|
docker compose up -d --build
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
`DATABASE_URL` в compose должен указывать на сервис `postgres`, не на `127.0.0.1` внутри контейнера app.
|
||||||
|
|
||||||
## Docker: нет связи с БД
|
|
||||||
|
|
||||||
Проверьте, что `DATABASE_URL` в compose указывает на хост `postgres`, а не `127.0.0.1` (внутри контейнера app).
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Полезные ссылки
|
## git pull / dubious ownership
|
||||||
|
|
||||||
|
Не делайте `chown -R www-data` на весь каталог репозитория.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git config --global --add safe.directory "$SHOP_ROOT"
|
||||||
|
cd "$SHOP_ROOT" && git pull
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ссылки
|
||||||
|
|
||||||
|
- [Сервер: установка и обновление](Server-Operations)
|
||||||
- [Установка Docker](Install-Docker)
|
- [Установка Docker](Install-Docker)
|
||||||
- [Установка без Docker](Install-Native)
|
- [Установка без Docker](Install-Native)
|
||||||
- [Репозиторий](https://git.evilfox.cc/test/shop10)
|
|
||||||
|
|||||||
Reference in New Issue
Block a user