Compare commits
33 Commits
v1.8.0
...
1bf82adbfc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1bf82adbfc | ||
|
|
9a68c083e3 | ||
|
|
aaeaa4f658 | ||
|
|
aea28ead9c | ||
|
|
cde2069d74 | ||
|
|
debb2efb3d | ||
|
|
4d4d5b0118 | ||
|
|
00b74b8aa9 | ||
|
|
577c5de200 | ||
|
|
0926757b7a | ||
|
|
13c32e9181 | ||
|
|
6b9eb562ba | ||
|
|
9558333c94 | ||
|
|
40e7abd012 | ||
|
|
3d7a456299 | ||
|
|
5acf597944 | ||
|
|
3f4bbcbb0d | ||
|
|
c8beeaf1b1 | ||
|
|
5ee8419c7c | ||
|
|
e376c86fbe | ||
|
|
69e21a18c9 | ||
|
|
90a2f7be1f | ||
|
|
d4633a0f46 | ||
|
|
b72b0e78b0 | ||
|
|
2a04099f95 | ||
|
|
58f9b74a1c | ||
|
|
8c9c328302 | ||
|
|
784bb27958 | ||
|
|
1add9fa299 | ||
|
|
b8696793f4 | ||
|
|
37e2df1fef | ||
|
|
48da26c270 | ||
|
|
bacfd8fe54 |
@@ -2,6 +2,9 @@ DATABASE_URL=mysql+pymysql://evosync:evosync@db:3306/evosync
|
||||
SECRET_KEY=your-random-secret-key-here
|
||||
BASE_URL=http://localhost:8000
|
||||
|
||||
EVOTOR_APP_ID=your-evotor-app-id
|
||||
EVOTOR_WEBHOOK_SECRET=your-webhook-secret
|
||||
|
||||
DB_ROOT_PASSWORD=rootpass
|
||||
DB_NAME=evosync
|
||||
DB_USER=evosync
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -16,3 +16,4 @@ passwords.txt
|
||||
.env
|
||||
__pycache__/
|
||||
*.pyc
|
||||
certbot
|
||||
|
||||
50
CHANGELOG.md
50
CHANGELOG.md
@@ -5,28 +5,46 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [1.8.2] - 2026-03-06
|
||||
|
||||
### Miscellaneous
|
||||
|
||||
- Replace EvoSync with ЭВОСИНК throughout UI
|
||||
|
||||
## [1.8.1] - 2026-03-06
|
||||
|
||||
### Documentation
|
||||
|
||||
- Update changelog for v1.7.3
|
||||
- Fix changelog order — 1.8.0 before 1.7.3
|
||||
|
||||
### Other
|
||||
|
||||
- V1.8.1
|
||||
|
||||
## [1.7.3] - 2026-03-06
|
||||
|
||||
### Added
|
||||
|
||||
- Add nginx reverse proxy and Let's Encrypt TLS setup
|
||||
|
||||
### Other
|
||||
|
||||
- V1.7.3
|
||||
|
||||
## [1.8.0] - 2026-03-06
|
||||
|
||||
### Added
|
||||
|
||||
- Connections dashboard (`/connections`) — unified page for all service integrations with online/offline status indicators
|
||||
- Add-connection page (`/connections/add`) — shows only unconnected services; "all connected" state when none remain
|
||||
- VK OAuth connection — connect VK account via OAuth, store access token and profile info
|
||||
- Background health checker — runs every 10 minutes, checks Evotor and VK tokens, updates `is_online` / `last_checked_at`
|
||||
- Sync configuration page (`/sync`) — master enable/disable toggle, confirm-and-start button, filter summary, warnings for missing connections
|
||||
- Catalog browser (`/catalog`) — browse Evotor stores, groups, and products in table views with cache auto-refresh on first visit
|
||||
- Catalog filter management — include/exclude rules per store/group/product via inline dropdown; rules stored in `sync_filters` table
|
||||
- Catalog CSV export — download stores, groups, or products as UTF-8 BOM CSV (Excel-compatible)
|
||||
- Alembic migrations for all new tables: `evotor_connections` (health fields), `vk_connections`, `sync_configs`, `sync_filters`, `cached_stores`, `cached_groups`, `cached_products`
|
||||
- `run/read_config.py` — CLI helper for shell sync scripts to read per-user sync config as JSON
|
||||
- Add Evotor OAuth connection feature with formatted phone input
|
||||
- Add Alembic database migrations
|
||||
- Add connections dashboard with background health checks
|
||||
- Add VK OAuth connection with health checks
|
||||
- Release v1.8.0 — connections dashboard, VK OAuth, sync config, catalog browser
|
||||
|
||||
### Changed
|
||||
### Miscellaneous
|
||||
|
||||
- Navbar: replaced "Эвотор" link with "Подключения", added "Каталог" and "Синхронизация" links
|
||||
- Evotor and VK connect/disconnect flows now redirect to `/connections`
|
||||
- Back links on `/evotor` and `/vk` pages updated to "Вернуться к подключениям"
|
||||
- VK connection card icon changed to `bi-bag` (shopping bag) to reflect VK Market use case
|
||||
- Password reset and email confirmation pages: replaced dev-mode console instructions with user-facing copy
|
||||
- Add semantic versioning and automatic changelog generation
|
||||
|
||||
## [1.7.2] - 2026-03-05
|
||||
|
||||
|
||||
161
README.md
161
README.md
@@ -1,3 +1,160 @@
|
||||
# evo-sync
|
||||
# ЭВОСИНК (EvoSync)
|
||||
|
||||
evo-sync is a command-line synchronization tool that fetches product, group, and store data from the Evo platform and syncs it with VK (VKontakte).
|
||||
Сервис автоматической синхронизации товарного каталога из [Эвотор](https://evotor.ru) в [ВКонтакте](https://vk.com).
|
||||
|
||||
## Возможности
|
||||
|
||||
- Подключение аккаунта Эвотор через OAuth
|
||||
- Подключение сообщества ВКонтакте через токен
|
||||
- Фильтрация по магазинам, группам и товарам (включить/исключить)
|
||||
- Автоматическая фоновая синхронизация по расписанию
|
||||
- Создание, обновление и удаление товаров в ВК-магазине
|
||||
- Личный кабинет с веб-интерфейсом
|
||||
- Просмотр закешированного каталога товаров
|
||||
|
||||
## Стек технологий
|
||||
|
||||
- **Backend**: FastAPI, SQLAlchemy ORM, Alembic
|
||||
- **База данных**: MariaDB (драйвер pymysql)
|
||||
- **Шаблоны**: Jinja2 (интерфейс на русском языке)
|
||||
- **Аутентификация**: Cookie-сессии, bcrypt
|
||||
- **Деплой**: Docker Compose
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
### Требования
|
||||
|
||||
- Docker и Docker Compose
|
||||
- MariaDB/MySQL (можно использовать хост-машину или отдельный контейнер)
|
||||
|
||||
### Настройка
|
||||
|
||||
1. Скопируйте файл переменных окружения:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
2. Отредактируйте `.env`:
|
||||
|
||||
```env
|
||||
# База данных
|
||||
DATABASE_URL=mysql+pymysql://evosync:evosync@db:3306/evosync
|
||||
|
||||
# Безопасность (обязательно измените в production)
|
||||
SECRET_KEY=your-random-secret-key-here
|
||||
|
||||
# URL приложения (используется в OAuth-редиректах)
|
||||
BASE_URL=https://your-domain.ru
|
||||
|
||||
# Эвотор
|
||||
EVOTOR_APP_ID=your-evotor-app-id
|
||||
EVOTOR_WEBHOOK_SECRET=your-webhook-secret
|
||||
|
||||
# Для отдельного MySQL-контейнера (опционально)
|
||||
DB_ROOT_PASSWORD=rootpass
|
||||
DB_NAME=evosync
|
||||
DB_USER=evosync
|
||||
DB_PASSWORD=evosync
|
||||
```
|
||||
|
||||
3. Запустите сервис:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Приложение будет доступно по адресу `http://localhost:8080`.
|
||||
|
||||
При старте контейнер автоматически применяет миграции базы данных (`alembic upgrade head`).
|
||||
|
||||
## Переменные окружения
|
||||
|
||||
| Переменная | Обязательно | По умолчанию | Описание |
|
||||
|---|---|---|---|
|
||||
| `DATABASE_URL` | Да | — | MySQL connection string (pymysql) |
|
||||
| `SECRET_KEY` | Да | `change-me-in-production` | Ключ для подписи сессий |
|
||||
| `BASE_URL` | Да | `http://localhost:8080` | Публичный URL (для OAuth-callback) |
|
||||
| `EVOTOR_APP_ID` | Да | — | ID приложения Эвотор |
|
||||
| `EVOTOR_WEBHOOK_SECRET` | Да | — | Секрет для верификации вебхуков Эвотор |
|
||||
| `VK_API_VERSION` | Нет | `5.131` | Версия VK API |
|
||||
| `VK_DEFAULT_PHOTO_PATH` | Нет | `/app/default_product.png` | Путь к изображению товара по умолчанию |
|
||||
| `JIVOSITE_WIDGET_ID` | Нет | — | ID виджета Jivosite (онлайн-чат) |
|
||||
| `SYNC_INTERVAL_SECONDS` | Нет | `3600` | Интервал синхронизации (сек) |
|
||||
| `CATALOG_REFRESH_INTERVAL_SECONDS` | Нет | `3600` | Интервал обновления каталога (сек) |
|
||||
| `HEALTH_CHECK_INTERVAL_SECONDS` | Нет | `600` | Интервал проверки соединений (сек) |
|
||||
|
||||
## Структура проекта
|
||||
|
||||
```
|
||||
evo-sync/
|
||||
├── web/
|
||||
│ ├── main.py # FastAPI-приложение, регистрация роутеров, фоновые задачи
|
||||
│ ├── config.py # Настройки из переменных окружения (pydantic-settings)
|
||||
│ ├── models.py # SQLAlchemy-модели (User, EvotorConnection, VkConnection, ...)
|
||||
│ ├── database.py # Движок и сессия SQLAlchemy
|
||||
│ ├── auth.py # Хеширование паролей, работа с сессиями
|
||||
│ ├── schemas.py # Pydantic-схемы для форм
|
||||
│ ├── sync_engine.py # Фоновый движок синхронизации (Эвотор → ВК)
|
||||
│ ├── routes/
|
||||
│ │ ├── auth.py # Регистрация, вход, выход, подтверждение email
|
||||
│ │ ├── profile.py # Профиль пользователя
|
||||
│ │ ├── reset.py # Сброс пароля
|
||||
│ │ ├── evotor.py # OAuth-подключение Эвотор
|
||||
│ │ ├── vk.py # Подключение ВКонтакте (ввод токена)
|
||||
│ │ ├── connections.py # Обзор всех подключений
|
||||
│ │ ├── sync.py # Настройка и управление синхронизацией
|
||||
│ │ └── catalog.py # Просмотр закешированного каталога
|
||||
│ ├── templates/ # Jinja2-шаблоны (русский интерфейс)
|
||||
│ └── migrations/ # Alembic-миграции
|
||||
├── Dockerfile.web # Docker-образ веб-приложения (Python 3.12-slim)
|
||||
├── docker-compose.yml # Оркестрация сервисов
|
||||
├── docker-entrypoint.sh # Скрипт запуска контейнера
|
||||
├── alembic.ini # Конфигурация миграций
|
||||
├── requirements.txt # Python-зависимости
|
||||
└── .env.example # Шаблон переменных окружения
|
||||
```
|
||||
|
||||
## Модели базы данных
|
||||
|
||||
| Модель | Таблица | Назначение |
|
||||
|---|---|---|
|
||||
| `User` | `users` | Аккаунт пользователя |
|
||||
| `EvotorConnection` | `evotor_connections` | OAuth-токен Эвотор |
|
||||
| `VkConnection` | `vk_connections` | Токен сообщества ВКонтакте |
|
||||
| `SyncConfig` | `sync_configs` | Настройки синхронизации пользователя |
|
||||
| `SyncFilter` | `sync_filters` | Фильтры по магазинам/группам/товарам |
|
||||
| `CachedStore` | `cached_stores` | Кеш магазинов Эвотор |
|
||||
| `CachedGroup` | `cached_groups` | Кеш групп товаров Эвотор |
|
||||
| `CachedProduct` | `cached_products` | Кеш товаров Эвотор + статус синхронизации |
|
||||
|
||||
## Как работает синхронизация
|
||||
|
||||
1. По расписанию (каждые `SYNC_INTERVAL_SECONDS` секунд) запускается `sync_engine.run_sync()`
|
||||
2. Для каждого пользователя с активным `SyncConfig` и подключёнными Эвотор и ВК:
|
||||
- Загружаются товары и группы из Эвотор API
|
||||
- Применяются фильтры (включить/исключить магазины, группы, товары)
|
||||
- Загружаются текущие товары и альбомы из ВК
|
||||
- Создаются/обновляются/удаляются альбомы и товары в ВК-магазине
|
||||
- В БД обновляется поле `synced_at` у синхронизированных товаров
|
||||
|
||||
**Особенности:**
|
||||
- Товары на развес (единицы измерения в граммах) получают скорректированную цену (×10)
|
||||
- Совпадение товаров ВК и Эвотор происходит по нормализованному названию
|
||||
- Товары с `allow_to_sell=false` не синхронизируются в ВК
|
||||
|
||||
## Разработка
|
||||
|
||||
Для локальной разработки с горячей перезагрузкой кода папка `./web` монтируется в контейнер как volume. После изменения Python-файлов uvicorn перезапустится автоматически.
|
||||
|
||||
Создание новой миграции:
|
||||
|
||||
```bash
|
||||
docker compose exec web alembic revision --autogenerate -m "описание изменений"
|
||||
```
|
||||
|
||||
Применение миграций вручную:
|
||||
|
||||
```bash
|
||||
docker compose exec web alembic upgrade head
|
||||
```
|
||||
|
||||
@@ -8,13 +8,21 @@ services:
|
||||
ports:
|
||||
- "8080:8000"
|
||||
environment:
|
||||
- DATABASE_URL=mysql+pymysql://${DB_USER}:${DB_PASSWORD}@172.25.0.1:3306/${DB_NAME}
|
||||
- DATABASE_URL=mysql+pymysql://${DB_USER}:${DB_PASSWORD}@host.docker.internal:3306/${DB_NAME}
|
||||
- SECRET_KEY=${SECRET_KEY:-change-me-in-production}
|
||||
- BASE_URL=${BASE_URL:-http://localhost:8080}
|
||||
- BASE_URL=${BASE_URL:-https://evosync.ru}
|
||||
- EVOTOR_APP_ID=${EVOTOR_APP_ID}
|
||||
- EVOTOR_WEBHOOK_SECRET=${EVOTOR_WEBHOOK_SECRET}
|
||||
- VK_CLIENT_ID=${VK_CLIENT_ID}
|
||||
- VK_CLIENT_SECRET=${VK_CLIENT_SECRET}
|
||||
volumes:
|
||||
- ./web:/app/web
|
||||
- ./alembic.ini:/app/alembic.ini
|
||||
- ./docker-entrypoint.sh:/app/docker-entrypoint.sh
|
||||
- ./5393364294319597854.png:/app/default_product.png:ro
|
||||
restart: unless-stopped
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
|
||||
# sync:
|
||||
# build:
|
||||
|
||||
36
nginx/nginx.conf
Normal file
36
nginx/nginx.conf
Normal file
@@ -0,0 +1,36 @@
|
||||
upstream web {
|
||||
server 127.0.0.1:8080;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name evosync.ru www.evosync.ru;
|
||||
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name evosync.ru www.evosync.ru;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/evosync.ru/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/evosync.ru/privkey.pem;
|
||||
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
ssl_prefer_server_ciphers on;
|
||||
|
||||
location / {
|
||||
proxy_pass http://web;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
57
scripts/evotor-get-token.sh
Normal file
57
scripts/evotor-get-token.sh
Normal file
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env bash
|
||||
# Obtain an Evotor developer access token via password grant (no browser required).
|
||||
# Uses dev.evotor.ru credentials (your Evotor developer account).
|
||||
#
|
||||
# Usage: ./scripts/evotor-get-token.sh
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# Load .env if present
|
||||
if [[ -f .env ]]; then
|
||||
set -a; source .env; set +a
|
||||
fi
|
||||
|
||||
EVOTOR_TOKEN_URL="https://dev.evotor.ru/oauth/token"
|
||||
|
||||
# Prompt for credentials
|
||||
read -rp "Evotor developer login (email): " EVOTOR_LOGIN
|
||||
read -rsp "Evotor developer password: " EVOTOR_PASSWORD
|
||||
echo
|
||||
|
||||
echo
|
||||
echo "A 2FA code will be sent to your email if this IP is not recognized."
|
||||
read -rp "2FA code (leave blank if not required): " EVOTOR_2FA
|
||||
|
||||
# Build request body
|
||||
BODY="type=LOGIN&grant_type=password&client_id=Evo-UI&username=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$EVOTOR_LOGIN")&password=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$EVOTOR_PASSWORD")"
|
||||
|
||||
EXTRA_HEADERS=()
|
||||
if [[ -n "$EVOTOR_2FA" ]]; then
|
||||
EXTRA_HEADERS+=(-H "2fa_confirmation: $EVOTOR_2FA")
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "Requesting token..."
|
||||
RESPONSE=$(curl -s -X POST "$EVOTOR_TOKEN_URL" \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
"${EXTRA_HEADERS[@]}" \
|
||||
-d "$BODY")
|
||||
|
||||
echo
|
||||
echo "Response:"
|
||||
echo "$RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$RESPONSE"
|
||||
|
||||
ACCESS_TOKEN=$(echo "$RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('access_token',''))" 2>/dev/null || true)
|
||||
|
||||
if [[ -z "$ACCESS_TOKEN" ]]; then
|
||||
echo
|
||||
echo "ERROR: No access_token in response." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "Access token:"
|
||||
echo "$ACCESS_TOKEN"
|
||||
echo
|
||||
echo "To save this token to .env, add or update:"
|
||||
echo " EVOTOR_ACCESS_TOKEN=$ACCESS_TOKEN"
|
||||
46
scripts/init-letsencrypt.sh
Executable file
46
scripts/init-letsencrypt.sh
Executable file
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
# Obtain TLS certificates from Let's Encrypt for evosync.ru
|
||||
# Run once on first deploy: sudo ./scripts/init-letsencrypt.sh
|
||||
# Requires nginx running on the host with acme-challenge location configured
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
DOMAIN="evosync.ru"
|
||||
EMAIL="${LETSENCRYPT_EMAIL:-admin@evosync.ru}"
|
||||
CERTBOT_DIR="./certbot"
|
||||
ACME_DIR="/var/www/certbot"
|
||||
|
||||
echo "==> Creating certbot directories..."
|
||||
mkdir -p "$CERTBOT_DIR/conf" "$CERTBOT_DIR/www"
|
||||
|
||||
echo "==> Ensuring acme-challenge directory exists on host..."
|
||||
sudo mkdir -p "$ACME_DIR"
|
||||
sudo chmod 755 "$ACME_DIR"
|
||||
|
||||
echo "==> Requesting certificate from Let's Encrypt..."
|
||||
sudo certbot certonly \
|
||||
--webroot \
|
||||
--webroot-path="$ACME_DIR" \
|
||||
--email "$EMAIL" \
|
||||
--agree-tos \
|
||||
--no-eff-email \
|
||||
-d "$DOMAIN" \
|
||||
-d "www.$DOMAIN"
|
||||
|
||||
echo "==> Copying certificates to project directory..."
|
||||
sudo cp "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" "$CERTBOT_DIR/conf/fullchain.pem"
|
||||
sudo cp "/etc/letsencrypt/live/$DOMAIN/privkey.pem" "$CERTBOT_DIR/conf/privkey.pem"
|
||||
sudo chown "$(whoami):$(whoami)" "$CERTBOT_DIR/conf"/*.pem
|
||||
|
||||
echo "==> Done! TLS certificate installed for $DOMAIN"
|
||||
echo ""
|
||||
echo "Certificate files:"
|
||||
echo " - $CERTBOT_DIR/conf/fullchain.pem"
|
||||
echo " - $CERTBOT_DIR/conf/privkey.pem"
|
||||
echo ""
|
||||
echo "Configure nginx:"
|
||||
echo " ssl_certificate $CERTBOT_DIR/conf/fullchain.pem;"
|
||||
echo " ssl_certificate_key $CERTBOT_DIR/conf/privkey.pem;"
|
||||
echo ""
|
||||
echo "Set up auto-renewal with: sudo crontab -e"
|
||||
echo "Add: 0 3 * * * certbot renew --quiet && systemctl reload nginx"
|
||||
@@ -4,18 +4,20 @@ from pydantic_settings import BaseSettings
|
||||
class Settings(BaseSettings):
|
||||
DATABASE_URL: str = "mysql+pymysql://evosync:evosync@localhost:3306/evosync"
|
||||
SECRET_KEY: str = "change-me-in-production"
|
||||
BASE_URL: str = "http://localhost:8000"
|
||||
BASE_URL: str = "http://localhost:8080"
|
||||
PASSWORD_RESET_EXPIRE_MINUTES: int = 60
|
||||
|
||||
EVOTOR_CLIENT_ID: str = ""
|
||||
EVOTOR_CLIENT_SECRET: str = ""
|
||||
EVOTOR_SCOPES: str = "store:read product:read"
|
||||
EVOTOR_APP_ID: str = ""
|
||||
EVOTOR_WEBHOOK_SECRET: str = ""
|
||||
|
||||
JIVOSITE_WIDGET_ID: str = ""
|
||||
|
||||
HEALTH_CHECK_INTERVAL_SECONDS: int = 600
|
||||
CATALOG_REFRESH_INTERVAL_SECONDS: int = 3600
|
||||
SYNC_INTERVAL_SECONDS: int = 3600
|
||||
|
||||
VK_DEFAULT_PHOTO_PATH: str = "/app/default_product.png"
|
||||
|
||||
VK_CLIENT_ID: str = ""
|
||||
VK_CLIENT_SECRET: str = ""
|
||||
VK_SCOPES: str = "market groups offline"
|
||||
VK_API_VERSION: str = "5.131"
|
||||
|
||||
# Docker compose vars (ignored in app, kept for env compatibility)
|
||||
|
||||
@@ -33,6 +33,8 @@ async def fetch_groups(access_token: str, store_id: str) -> list[dict]:
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
timeout=15,
|
||||
)
|
||||
if resp.status_code == 402:
|
||||
return []
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
items = data.get("items", data) if isinstance(data, dict) else data
|
||||
@@ -46,6 +48,8 @@ async def fetch_products(access_token: str, store_id: str) -> list[dict]:
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
timeout=15,
|
||||
)
|
||||
if resp.status_code == 402:
|
||||
return []
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
items = data.get("items", data) if isinstance(data, dict) else data
|
||||
|
||||
@@ -1,18 +1,46 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import httpx
|
||||
|
||||
from web.database import SessionLocal
|
||||
from web.models import EvotorConnection, VkConnection
|
||||
from web.models import EvotorConnection, VkConnection, CachedStore
|
||||
|
||||
logger = logging.getLogger("uvicorn.error")
|
||||
|
||||
EVOTOR_STORES_URL = "https://api.evotor.ru/stores"
|
||||
VK_USERS_GET_URL = "https://api.vk.com/method/users.get"
|
||||
EVOTOR_TOKEN_URL = "https://oauth.evotor.ru/oauth/token"
|
||||
VK_GROUPS_GET_URL = "https://api.vk.com/method/groups.getById"
|
||||
VK_API_VERSION = "5.131"
|
||||
|
||||
# Refresh Evotor token if it expires within this window
|
||||
REFRESH_BEFORE_EXPIRY = timedelta(hours=2)
|
||||
|
||||
|
||||
async def _refresh_evotor_token(conn: EvotorConnection) -> str | None:
|
||||
"""Attempt to refresh the Evotor access token. Returns new access token or None."""
|
||||
from web.config import settings
|
||||
if not conn.refresh_token:
|
||||
return None
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
EVOTOR_TOKEN_URL,
|
||||
data={
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": conn.refresh_token,
|
||||
},
|
||||
auth=(settings.EVOTOR_CLIENT_ID, settings.EVOTOR_CLIENT_SECRET),
|
||||
timeout=15,
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
return None
|
||||
data = resp.json()
|
||||
return data if data.get("access_token") else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
async def check_evotor_connection(access_token: str) -> bool:
|
||||
try:
|
||||
@@ -31,7 +59,7 @@ async def check_vk_connection(access_token: str) -> bool:
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.get(
|
||||
VK_USERS_GET_URL,
|
||||
VK_GROUPS_GET_URL,
|
||||
params={"access_token": access_token, "v": VK_API_VERSION},
|
||||
timeout=10,
|
||||
)
|
||||
@@ -46,21 +74,70 @@ async def check_vk_connection(access_token: str) -> bool:
|
||||
async def run_health_checks() -> None:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
now = datetime.utcnow()
|
||||
|
||||
evotor_connections = db.query(EvotorConnection).all()
|
||||
for conn in evotor_connections:
|
||||
conn.is_online = await check_evotor_connection(conn.access_token)
|
||||
conn.last_checked_at = datetime.utcnow()
|
||||
# Proactively refresh if token expires soon
|
||||
needs_refresh = (
|
||||
conn.refresh_token and
|
||||
conn.token_expires_at and
|
||||
conn.token_expires_at - now < REFRESH_BEFORE_EXPIRY
|
||||
)
|
||||
if needs_refresh:
|
||||
token_data = await _refresh_evotor_token(conn)
|
||||
if token_data:
|
||||
conn.access_token = token_data["access_token"]
|
||||
conn.refresh_token = token_data.get("refresh_token", conn.refresh_token)
|
||||
expires_in = token_data.get("expires_in")
|
||||
conn.token_expires_at = now + timedelta(seconds=expires_in) if expires_in else None
|
||||
logger.info("Refreshed Evotor token for user_id=%d", conn.user_id)
|
||||
|
||||
is_online = await check_evotor_connection(conn.access_token)
|
||||
|
||||
# If offline and not yet tried refresh, attempt it now
|
||||
if not is_online and conn.refresh_token and not needs_refresh:
|
||||
token_data = await _refresh_evotor_token(conn)
|
||||
if token_data:
|
||||
conn.access_token = token_data["access_token"]
|
||||
conn.refresh_token = token_data.get("refresh_token", conn.refresh_token)
|
||||
expires_in = token_data.get("expires_in")
|
||||
conn.token_expires_at = now + timedelta(seconds=expires_in) if expires_in else None
|
||||
is_online = await check_evotor_connection(conn.access_token)
|
||||
if is_online:
|
||||
logger.info("Evotor token refreshed after failed check for user_id=%d", conn.user_id)
|
||||
|
||||
conn.is_online = is_online
|
||||
conn.last_checked_at = now
|
||||
|
||||
vk_connections = db.query(VkConnection).all()
|
||||
for conn in vk_connections:
|
||||
conn.is_online = await check_vk_connection(conn.access_token)
|
||||
conn.last_checked_at = datetime.utcnow()
|
||||
conn.last_checked_at = now
|
||||
|
||||
db.commit()
|
||||
|
||||
# Refresh catalog cache for online Evotor connections
|
||||
from web.config import settings
|
||||
refreshed_catalog = 0
|
||||
for conn in evotor_connections:
|
||||
if not conn.is_online:
|
||||
continue
|
||||
cached = db.query(CachedStore).filter(CachedStore.user_id == conn.user_id).first()
|
||||
cache_age = (now - cached.fetched_at).total_seconds() if cached else None
|
||||
if cached is None or cache_age >= settings.CATALOG_REFRESH_INTERVAL_SECONDS:
|
||||
try:
|
||||
from web.evotor_api import refresh_catalog_cache
|
||||
await refresh_catalog_cache(conn.user_id, conn.access_token, db)
|
||||
refreshed_catalog += 1
|
||||
except Exception:
|
||||
logger.exception("Failed to refresh catalog cache for user_id=%d", conn.user_id)
|
||||
|
||||
logger.info(
|
||||
"Health checks completed: %d Evotor, %d VK",
|
||||
"Health checks completed: %d Evotor, %d VK, %d catalogs refreshed",
|
||||
len(evotor_connections),
|
||||
len(vk_connections),
|
||||
refreshed_catalog,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Error during health checks")
|
||||
|
||||
20
web/main.py
20
web/main.py
@@ -9,6 +9,7 @@ from starlette.middleware.sessions import SessionMiddleware
|
||||
from web.auth import get_current_user
|
||||
from web.config import settings
|
||||
from web.health_checker import health_check_loop
|
||||
from web.sync_engine import sync_loop
|
||||
from web.models import User
|
||||
from web.routes import auth, profile, reset, evotor, vk, sync, catalog
|
||||
from web.routes import connections
|
||||
@@ -16,16 +17,21 @@ from web.routes import connections
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
task = asyncio.create_task(health_check_loop(settings.HEALTH_CHECK_INTERVAL_SECONDS))
|
||||
tasks = [
|
||||
asyncio.create_task(health_check_loop(settings.HEALTH_CHECK_INTERVAL_SECONDS)),
|
||||
asyncio.create_task(sync_loop(settings.SYNC_INTERVAL_SECONDS)),
|
||||
]
|
||||
yield
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
for t in tasks:
|
||||
t.cancel()
|
||||
for t in tasks:
|
||||
try:
|
||||
await t
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
|
||||
app = FastAPI(title="EvoSync — Личный кабинет", lifespan=lifespan)
|
||||
app = FastAPI(title="ЭВОСИНК — Личный кабинет", lifespan=lifespan)
|
||||
|
||||
app.add_middleware(SessionMiddleware, secret_key=settings.SECRET_KEY)
|
||||
app.mount("/static", StaticFiles(directory="web/static"), name="static")
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
"""add synced_at to cached_products
|
||||
|
||||
Revision ID: a7b8c9d0e1f2
|
||||
Revises: f6a7b8c9d0e1
|
||||
Branch Labels: None
|
||||
Depends On: None
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "a7b8c9d0e1f2"
|
||||
down_revision = "f6a7b8c9d0e1"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column(
|
||||
"cached_products",
|
||||
sa.Column("synced_at", sa.DateTime(), nullable=True),
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column("cached_products", "synced_at")
|
||||
@@ -0,0 +1,24 @@
|
||||
"""add refresh_token and token_expires_at to evotor_connections
|
||||
|
||||
Revision ID: e5f6a7b8c9d0
|
||||
Revises: d4e5f6a7b8c9
|
||||
Create Date: 2026-03-06 00:04:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = 'e5f6a7b8c9d0'
|
||||
down_revision = 'd4e5f6a7b8c9'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column('evotor_connections', sa.Column('refresh_token', sa.Text(), nullable=True))
|
||||
op.add_column('evotor_connections', sa.Column('token_expires_at', sa.DateTime(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column('evotor_connections', 'token_expires_at')
|
||||
op.drop_column('evotor_connections', 'refresh_token')
|
||||
@@ -0,0 +1,53 @@
|
||||
"""evotor webhook token flow: add evotor_user_id, make user_id nullable
|
||||
|
||||
Revision ID: f6a7b8c9d0e1
|
||||
Revises: e5f6a7b8c9d0
|
||||
Branch Labels: None
|
||||
Depends On: None
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = 'f6a7b8c9d0e1'
|
||||
down_revision = 'e5f6a7b8c9d0'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
|
||||
# Check existing columns
|
||||
columns = [row[0] for row in conn.execute(sa.text(
|
||||
"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS "
|
||||
"WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'evotor_connections'"
|
||||
))]
|
||||
|
||||
if 'evotor_user_id' not in columns:
|
||||
op.add_column('evotor_connections',
|
||||
sa.Column('evotor_user_id', sa.String(255), nullable=True))
|
||||
|
||||
# Check existing indexes
|
||||
indexes = [row[2] for row in conn.execute(sa.text(
|
||||
"SHOW INDEX FROM evotor_connections"
|
||||
))]
|
||||
|
||||
if 'uq_evotor_connections_evotor_user_id' not in indexes:
|
||||
op.create_unique_constraint('uq_evotor_connections_evotor_user_id',
|
||||
'evotor_connections', ['evotor_user_id'])
|
||||
|
||||
if 'ix_evotor_connections_evotor_user_id' not in indexes:
|
||||
op.create_index('ix_evotor_connections_evotor_user_id',
|
||||
'evotor_connections', ['evotor_user_id'])
|
||||
|
||||
op.alter_column('evotor_connections', 'user_id',
|
||||
existing_type=sa.Integer(), nullable=True)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.alter_column('evotor_connections', 'user_id',
|
||||
existing_type=sa.Integer(), nullable=False)
|
||||
op.drop_index('ix_evotor_connections_evotor_user_id', 'evotor_connections')
|
||||
op.drop_constraint('uq_evotor_connections_evotor_user_id', 'evotor_connections')
|
||||
op.drop_column('evotor_connections', 'evotor_user_id')
|
||||
@@ -33,10 +33,13 @@ class EvotorConnection(Base):
|
||||
__tablename__ = "evotor_connections"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), unique=True, nullable=False)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), unique=True, nullable=True)
|
||||
evotor_user_id = Column(String(255), unique=True, nullable=True, index=True)
|
||||
access_token = Column(Text, nullable=False)
|
||||
store_id = Column(String(255), nullable=True)
|
||||
store_name = Column(String(255), nullable=True)
|
||||
refresh_token = Column(Text, nullable=True)
|
||||
token_expires_at = Column(DateTime, nullable=True)
|
||||
is_online = Column(Boolean, default=False, server_default="0", nullable=False)
|
||||
last_checked_at = Column(DateTime, nullable=True)
|
||||
connected_at = Column(DateTime, server_default=func.now(), nullable=False)
|
||||
@@ -146,6 +149,7 @@ class CachedProduct(Base):
|
||||
article_number = Column(String(100), nullable=True)
|
||||
allow_to_sell = Column(Boolean, nullable=True)
|
||||
fetched_at = Column(DateTime, nullable=False)
|
||||
synced_at = Column(DateTime, nullable=True)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("user_id", "evotor_id"),
|
||||
|
||||
@@ -2,7 +2,7 @@ import uuid
|
||||
|
||||
from fastapi import APIRouter, Request, Depends
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from web.templates_env import templates
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from web.auth import hash_password, verify_password, get_current_user
|
||||
@@ -12,7 +12,6 @@ from web.models import User
|
||||
from web.schemas import validate_registration, validate_login
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory="web/templates")
|
||||
|
||||
|
||||
@router.get("/register")
|
||||
|
||||
@@ -3,7 +3,7 @@ import io
|
||||
|
||||
from fastapi import APIRouter, Request, Depends
|
||||
from fastapi.responses import RedirectResponse, StreamingResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from web.templates_env import templates
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from web.auth import get_current_user
|
||||
@@ -12,7 +12,6 @@ from web.evotor_api import refresh_catalog_cache
|
||||
from web.models import User, EvotorConnection, SyncConfig, SyncFilter, CachedStore, CachedGroup, CachedProduct
|
||||
|
||||
router = APIRouter(prefix="/catalog")
|
||||
templates = Jinja2Templates(directory="web/templates")
|
||||
|
||||
|
||||
def _get_or_create_sync_config(db: Session, user_id: int) -> SyncConfig:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from fastapi import APIRouter, Request, Depends
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from web.templates_env import templates
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from web.auth import get_current_user
|
||||
@@ -8,7 +8,6 @@ from web.database import get_db
|
||||
from web.models import User, EvotorConnection, VkConnection
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory="web/templates")
|
||||
|
||||
SERVICE_TYPES = [
|
||||
{
|
||||
@@ -17,7 +16,7 @@ SERVICE_TYPES = [
|
||||
"icon": "bi-shop",
|
||||
"description": "Подключите кассу Эвотор для синхронизации каталога товаров.",
|
||||
"configure_url": "/evotor",
|
||||
"connect_url": "/evotor/connect",
|
||||
"connect_url": "/evotor",
|
||||
},
|
||||
{
|
||||
"type": "vk",
|
||||
@@ -25,7 +24,7 @@ SERVICE_TYPES = [
|
||||
"icon": "bi-bag",
|
||||
"description": "Подключите аккаунт ВКонтакте для публикации товаров в вашу группу.",
|
||||
"configure_url": "/vk",
|
||||
"connect_url": "/vk/connect",
|
||||
"connect_url": "/vk",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import secrets
|
||||
import logging
|
||||
import httpx
|
||||
|
||||
from fastapi import APIRouter, Request, Depends
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, Request, Depends, HTTPException
|
||||
from fastapi.responses import RedirectResponse, JSONResponse
|
||||
from web.templates_env import templates
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from web.auth import get_current_user
|
||||
@@ -11,18 +13,14 @@ from web.config import settings
|
||||
from web.database import get_db
|
||||
from web.models import User, EvotorConnection
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/evotor")
|
||||
templates = Jinja2Templates(directory="web/templates")
|
||||
|
||||
EVOTOR_AUTHORIZE_URL = "https://oauth.evotor.ru/oauth/authorize"
|
||||
EVOTOR_TOKEN_URL = "https://oauth.evotor.ru/oauth/token"
|
||||
EVOTOR_APP_URL = "https://market.evotor.ru/store/apps/{app_id}"
|
||||
EVOTOR_STORES_URL = "https://api.evotor.ru/stores"
|
||||
|
||||
|
||||
def _redirect_uri() -> str:
|
||||
return f"{settings.BASE_URL}/evotor/callback"
|
||||
|
||||
|
||||
@router.get("")
|
||||
def evotor_page(
|
||||
request: Request,
|
||||
@@ -34,78 +32,49 @@ def evotor_page(
|
||||
|
||||
connection = db.query(EvotorConnection).filter(EvotorConnection.user_id == user.id).first()
|
||||
error = request.query_params.get("error")
|
||||
app_url = EVOTOR_APP_URL.format(app_id=settings.EVOTOR_APP_ID) if settings.EVOTOR_APP_ID else None
|
||||
return templates.TemplateResponse("evotor.html", {
|
||||
"request": request,
|
||||
"user": user,
|
||||
"connection": connection,
|
||||
"error": error,
|
||||
"app_url": app_url,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/connect")
|
||||
def evotor_connect(request: Request, user: User | None = Depends(get_current_user)):
|
||||
if not user:
|
||||
return RedirectResponse("/login", 303)
|
||||
|
||||
state = secrets.token_urlsafe(32)
|
||||
request.session["evotor_oauth_state"] = state
|
||||
|
||||
params = (
|
||||
f"?client_id={settings.EVOTOR_CLIENT_ID}"
|
||||
f"&response_type=code"
|
||||
f"&redirect_uri={_redirect_uri()}"
|
||||
f"&scope={settings.EVOTOR_SCOPES.replace(' ', '%20')}"
|
||||
f"&state={state}"
|
||||
)
|
||||
return RedirectResponse(EVOTOR_AUTHORIZE_URL + params, 302)
|
||||
class EvotorTokenPayload(BaseModel):
|
||||
userId: str
|
||||
token: str
|
||||
|
||||
|
||||
@router.get("/callback")
|
||||
@router.post("/callback")
|
||||
async def evotor_callback(
|
||||
request: Request,
|
||||
payload: EvotorTokenPayload,
|
||||
db: Session = Depends(get_db),
|
||||
user: User | None = Depends(get_current_user),
|
||||
):
|
||||
if not user:
|
||||
return RedirectResponse("/login", 303)
|
||||
"""
|
||||
Webhook endpoint: Evotor POSTs {"userId": "...", "token": "..."} here
|
||||
after the user authorizes the app in their Evotor account.
|
||||
"""
|
||||
# Verify the Authorization header matches our configured webhook secret
|
||||
if settings.EVOTOR_WEBHOOK_SECRET:
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
expected = f"Bearer {settings.EVOTOR_WEBHOOK_SECRET}"
|
||||
if auth_header != expected:
|
||||
logger.warning("Evotor webhook: invalid Authorization header")
|
||||
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||
|
||||
code = request.query_params.get("code")
|
||||
state = request.query_params.get("state")
|
||||
saved_state = request.session.pop("evotor_oauth_state", None)
|
||||
now = datetime.utcnow()
|
||||
|
||||
if not code or not state or state != saved_state:
|
||||
return RedirectResponse("/evotor?error=invalid_state", 303)
|
||||
|
||||
# Exchange code for access token
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
token_response = await client.post(
|
||||
EVOTOR_TOKEN_URL,
|
||||
data={
|
||||
"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": _redirect_uri(),
|
||||
},
|
||||
auth=(settings.EVOTOR_CLIENT_ID, settings.EVOTOR_CLIENT_SECRET),
|
||||
timeout=15,
|
||||
)
|
||||
token_response.raise_for_status()
|
||||
token_data = token_response.json()
|
||||
except Exception:
|
||||
return RedirectResponse("/evotor?error=token_exchange", 303)
|
||||
|
||||
access_token = token_data.get("access_token")
|
||||
if not access_token:
|
||||
return RedirectResponse("/evotor?error=no_token", 303)
|
||||
|
||||
# Fetch first store to save store info
|
||||
# Fetch store info using the received token
|
||||
store_id = None
|
||||
store_name = None
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
stores_response = await client.get(
|
||||
EVOTOR_STORES_URL,
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
headers={"Authorization": f"Bearer {payload.token}"},
|
||||
timeout=15,
|
||||
)
|
||||
if stores_response.status_code == 200:
|
||||
@@ -115,25 +84,91 @@ async def evotor_callback(
|
||||
store_id = items[0].get("uuid") or items[0].get("id")
|
||||
store_name = items[0].get("name")
|
||||
except Exception:
|
||||
pass # Store info is optional; token is still saved
|
||||
pass # Store info is optional
|
||||
|
||||
# Upsert by evotor_user_id (user_id stays NULL until /evotor/link is called)
|
||||
connection = db.query(EvotorConnection).filter(
|
||||
EvotorConnection.evotor_user_id == payload.userId
|
||||
).first()
|
||||
|
||||
# Save or update connection
|
||||
from datetime import datetime
|
||||
connection = db.query(EvotorConnection).filter(EvotorConnection.user_id == user.id).first()
|
||||
if connection:
|
||||
connection.access_token = access_token
|
||||
connection.access_token = payload.token
|
||||
connection.store_id = store_id
|
||||
connection.store_name = store_name
|
||||
connection.is_online = True
|
||||
connection.last_checked_at = datetime.utcnow()
|
||||
connection.last_checked_at = now
|
||||
connection.updated_at = now
|
||||
else:
|
||||
connection = EvotorConnection(
|
||||
user_id=user.id,
|
||||
access_token=access_token,
|
||||
evotor_user_id=payload.userId,
|
||||
access_token=payload.token,
|
||||
store_id=store_id,
|
||||
store_name=store_name,
|
||||
is_online=True,
|
||||
last_checked_at=datetime.utcnow(),
|
||||
last_checked_at=now,
|
||||
)
|
||||
db.add(connection)
|
||||
|
||||
db.commit()
|
||||
logger.info("Evotor webhook: saved token for evotor_user_id=%s", payload.userId)
|
||||
|
||||
return JSONResponse({"status": "ok"})
|
||||
|
||||
|
||||
@router.post("/token")
|
||||
async def evotor_token_manual(
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
user: User | None = Depends(get_current_user),
|
||||
):
|
||||
"""Allow user to manually paste their Evotor token."""
|
||||
if not user:
|
||||
return RedirectResponse("/login", 303)
|
||||
|
||||
form = await request.form()
|
||||
token = (form.get("token") or "").strip()
|
||||
if not token:
|
||||
return RedirectResponse("/evotor?error=empty_token", 303)
|
||||
|
||||
now = datetime.utcnow()
|
||||
|
||||
# Fetch store info
|
||||
store_id = None
|
||||
store_name = None
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
stores_response = await client.get(
|
||||
EVOTOR_STORES_URL,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=15,
|
||||
)
|
||||
if stores_response.status_code == 200:
|
||||
stores = stores_response.json()
|
||||
items = stores.get("items", stores) if isinstance(stores, dict) else stores
|
||||
if items:
|
||||
store_id = items[0].get("uuid") or items[0].get("id")
|
||||
store_name = items[0].get("name")
|
||||
elif stores_response.status_code == 401:
|
||||
return RedirectResponse("/evotor?error=invalid_token", 303)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
connection = db.query(EvotorConnection).filter(EvotorConnection.user_id == user.id).first()
|
||||
if connection:
|
||||
connection.access_token = token
|
||||
connection.store_id = store_id
|
||||
connection.store_name = store_name
|
||||
connection.is_online = True
|
||||
connection.last_checked_at = now
|
||||
connection.updated_at = now
|
||||
else:
|
||||
connection = EvotorConnection(
|
||||
user_id=user.id,
|
||||
access_token=token,
|
||||
store_id=store_id,
|
||||
store_name=store_name,
|
||||
is_online=True,
|
||||
last_checked_at=now,
|
||||
)
|
||||
db.add(connection)
|
||||
db.commit()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from fastapi import APIRouter, Request, Depends
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from web.templates_env import templates
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from web.auth import get_current_user, verify_password, hash_password
|
||||
@@ -9,7 +9,6 @@ from web.models import User
|
||||
from web.schemas import validate_profile, validate_reset_password
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory="web/templates")
|
||||
|
||||
|
||||
# VIEW PROFILE
|
||||
|
||||
@@ -3,7 +3,7 @@ from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Request, Depends
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from web.templates_env import templates
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from web.auth import hash_password
|
||||
@@ -13,7 +13,6 @@ from web.models import User
|
||||
from web.schemas import validate_reset_password
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory="web/templates")
|
||||
|
||||
|
||||
@router.get("/forgot-password")
|
||||
|
||||
@@ -2,7 +2,7 @@ from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Request, Depends
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from web.templates_env import templates
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from web.auth import get_current_user
|
||||
@@ -10,7 +10,6 @@ from web.database import get_db
|
||||
from web.models import User, EvotorConnection, VkConnection, SyncConfig, SyncFilter
|
||||
|
||||
router = APIRouter(prefix="/sync")
|
||||
templates = Jinja2Templates(directory="web/templates")
|
||||
|
||||
|
||||
def _get_or_create_sync_config(db: Session, user_id: int) -> SyncConfig:
|
||||
|
||||
119
web/routes/vk.py
119
web/routes/vk.py
@@ -1,11 +1,10 @@
|
||||
import secrets
|
||||
from datetime import datetime
|
||||
|
||||
import httpx
|
||||
|
||||
from fastapi import APIRouter, Request, Depends
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from web.templates_env import templates
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from web.auth import get_current_user
|
||||
@@ -14,17 +13,10 @@ from web.database import get_db
|
||||
from web.models import User, VkConnection
|
||||
|
||||
router = APIRouter(prefix="/vk")
|
||||
templates = Jinja2Templates(directory="web/templates")
|
||||
|
||||
VK_AUTHORIZE_URL = "https://oauth.vk.com/authorize"
|
||||
VK_TOKEN_URL = "https://oauth.vk.com/access_token"
|
||||
VK_API_URL = "https://api.vk.com/method"
|
||||
|
||||
|
||||
def _redirect_uri() -> str:
|
||||
return f"{settings.BASE_URL}/vk/callback"
|
||||
|
||||
|
||||
@router.get("")
|
||||
def vk_page(
|
||||
request: Request,
|
||||
@@ -44,102 +36,63 @@ def vk_page(
|
||||
})
|
||||
|
||||
|
||||
@router.get("/connect")
|
||||
def vk_connect(request: Request, user: User | None = Depends(get_current_user)):
|
||||
if not user:
|
||||
return RedirectResponse("/login", 303)
|
||||
|
||||
state = secrets.token_urlsafe(32)
|
||||
request.session["vk_oauth_state"] = state
|
||||
|
||||
params = (
|
||||
f"?client_id={settings.VK_CLIENT_ID}"
|
||||
f"&response_type=code"
|
||||
f"&redirect_uri={_redirect_uri()}"
|
||||
f"&scope={settings.VK_SCOPES.replace(' ', '%20')}"
|
||||
f"&state={state}"
|
||||
f"&display=page"
|
||||
f"&v={settings.VK_API_VERSION}"
|
||||
)
|
||||
return RedirectResponse(VK_AUTHORIZE_URL + params, 302)
|
||||
|
||||
|
||||
@router.get("/callback")
|
||||
async def vk_callback(
|
||||
@router.post("/token")
|
||||
async def vk_token(
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
user: User | None = Depends(get_current_user),
|
||||
):
|
||||
"""Save a manually entered VK community access token."""
|
||||
if not user:
|
||||
return RedirectResponse("/login", 303)
|
||||
|
||||
code = request.query_params.get("code")
|
||||
state = request.query_params.get("state")
|
||||
saved_state = request.session.pop("vk_oauth_state", None)
|
||||
form = await request.form()
|
||||
token = (form.get("token") or "").strip()
|
||||
if not token:
|
||||
return RedirectResponse("/vk?error=empty_token", 303)
|
||||
|
||||
if not code or not state or state != saved_state:
|
||||
return RedirectResponse("/vk?error=invalid_state", 303)
|
||||
|
||||
# Exchange code for token (VK uses GET with query params)
|
||||
# Fetch community info to validate the token and get group name/id
|
||||
group_id = None
|
||||
group_name = None
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
token_response = await client.get(
|
||||
VK_TOKEN_URL,
|
||||
params={
|
||||
"client_id": settings.VK_CLIENT_ID,
|
||||
"client_secret": settings.VK_CLIENT_SECRET,
|
||||
"code": code,
|
||||
"redirect_uri": _redirect_uri(),
|
||||
},
|
||||
resp = await client.get(
|
||||
f"{VK_API_URL}/groups.getById",
|
||||
params={"access_token": token, "v": settings.VK_API_VERSION},
|
||||
timeout=15,
|
||||
)
|
||||
token_response.raise_for_status()
|
||||
token_data = token_response.json()
|
||||
except Exception:
|
||||
return RedirectResponse("/vk?error=token_exchange", 303)
|
||||
|
||||
access_token = token_data.get("access_token")
|
||||
vk_user_id = str(token_data.get("user_id", "")) or None
|
||||
if not access_token:
|
||||
return RedirectResponse("/vk?error=no_token", 303)
|
||||
|
||||
# Fetch VK profile info
|
||||
first_name = None
|
||||
last_name = None
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
profile_response = await client.get(
|
||||
f"{VK_API_URL}/users.get",
|
||||
params={"access_token": access_token, "v": settings.VK_API_VERSION},
|
||||
timeout=15,
|
||||
)
|
||||
if profile_response.status_code == 200:
|
||||
profile_data = profile_response.json()
|
||||
items = profile_data.get("response", [])
|
||||
if items:
|
||||
first_name = items[0].get("first_name")
|
||||
last_name = items[0].get("last_name")
|
||||
if resp.status_code == 200:
|
||||
data = resp.json()
|
||||
if "error" in data:
|
||||
return RedirectResponse("/vk?error=invalid_token", 303)
|
||||
response = data.get("response", [])
|
||||
groups = response if isinstance(response, list) else response.get("groups", [])
|
||||
if groups:
|
||||
group_id = str(groups[0].get("id", ""))
|
||||
group_name = groups[0].get("name")
|
||||
elif resp.status_code == 401:
|
||||
return RedirectResponse("/vk?error=invalid_token", 303)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Save or update connection
|
||||
connection = db.query(VkConnection).filter(VkConnection.user_id == user.id).first()
|
||||
now = datetime.utcnow()
|
||||
if connection:
|
||||
connection.access_token = access_token
|
||||
connection.vk_user_id = vk_user_id
|
||||
connection.first_name = first_name
|
||||
connection.last_name = last_name
|
||||
connection.access_token = token
|
||||
connection.vk_user_id = group_id
|
||||
connection.first_name = group_name
|
||||
connection.last_name = None
|
||||
connection.is_online = True
|
||||
connection.last_checked_at = datetime.utcnow()
|
||||
connection.last_checked_at = now
|
||||
else:
|
||||
connection = VkConnection(
|
||||
user_id=user.id,
|
||||
access_token=access_token,
|
||||
vk_user_id=vk_user_id,
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
access_token=token,
|
||||
vk_user_id=group_id,
|
||||
first_name=group_name,
|
||||
last_name=None,
|
||||
is_online=True,
|
||||
last_checked_at=datetime.utcnow(),
|
||||
last_checked_at=now,
|
||||
)
|
||||
db.add(connection)
|
||||
db.commit()
|
||||
|
||||
485
web/sync_engine.py
Normal file
485
web/sync_engine.py
Normal file
@@ -0,0 +1,485 @@
|
||||
"""
|
||||
Sync engine: syncs Evotor products to VK market for all enabled users.
|
||||
Runs as a background asyncio loop inside the web app.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
import httpx
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from web.database import SessionLocal
|
||||
from web.models import CachedProduct, EvotorConnection, VkConnection, SyncConfig, SyncFilter
|
||||
|
||||
logger = logging.getLogger("uvicorn.error")
|
||||
|
||||
VK_API_HOST = "https://api.vk.ru/method"
|
||||
VK_API_VERSION = "5.199"
|
||||
EVOTOR_API_BASE = "https://api.evotor.ru"
|
||||
VK_CATEGORY_ID = 40932
|
||||
VK_STOCK_AMOUNT = 1000
|
||||
WEIGHT_PRICE_MULTIPLIER = 10
|
||||
WEIGHT_MEASURES = {"г", "г.", "грамм", "граммов", "гр", "гр."}
|
||||
|
||||
|
||||
def _is_weight_measure(measure: str | None) -> bool:
|
||||
if not measure:
|
||||
return False
|
||||
return measure.strip().lower() in WEIGHT_MEASURES
|
||||
|
||||
|
||||
def _normalize_name(name: str) -> str:
|
||||
return name.strip().replace(";", ",")
|
||||
|
||||
|
||||
def _calc_price(price_kopecks, measure: str | None) -> tuple[int, str]:
|
||||
"""Returns (price_in_kopecks_for_vk, price_info_label)."""
|
||||
base = int(price_kopecks or 0)
|
||||
if _is_weight_measure(measure):
|
||||
return base * WEIGHT_PRICE_MULTIPLIER, f"{WEIGHT_PRICE_MULTIPLIER}{measure}"
|
||||
return base, measure or ""
|
||||
|
||||
|
||||
def _build_description(name: str, price_info: str, extra_desc: str | None) -> str:
|
||||
desc = f"{name} (цена за {price_info}.)\n\n"
|
||||
if extra_desc:
|
||||
desc += extra_desc
|
||||
return desc
|
||||
|
||||
|
||||
def _get_included_store_ids(filters: list) -> list[str]:
|
||||
return [f.entity_id for f in filters if f.entity_type == "store" and f.filter_mode == "include"]
|
||||
|
||||
|
||||
def _is_group_included(group_id: str | None, filters: list) -> bool:
|
||||
"""Returns True if the group should be synced based on filters."""
|
||||
group_filters = {f.entity_id: f.filter_mode for f in filters if f.entity_type == "group"}
|
||||
if not group_filters:
|
||||
return True # no group filters → include all
|
||||
mode = group_filters.get(group_id)
|
||||
if mode == "exclude":
|
||||
return False
|
||||
if mode == "include":
|
||||
return True
|
||||
# Not mentioned — include if there are only excludes, exclude if there are only includes
|
||||
has_includes = any(v == "include" for v in group_filters.values())
|
||||
return not has_includes
|
||||
|
||||
|
||||
def _is_product_included(product_id: str, filters: list) -> bool:
|
||||
product_filters = {f.entity_id: f.filter_mode for f in filters if f.entity_type == "product"}
|
||||
if not product_filters:
|
||||
return True
|
||||
mode = product_filters.get(product_id)
|
||||
if mode == "exclude":
|
||||
return False
|
||||
if mode == "include":
|
||||
return True
|
||||
has_includes = any(v == "include" for v in product_filters.values())
|
||||
return not has_includes
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Evotor API helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def _evo_fetch_products(token: str, store_id: str) -> list[dict]:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.get(
|
||||
f"{EVOTOR_API_BASE}/stores/{store_id}/products",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=30,
|
||||
)
|
||||
if resp.status_code in (402, 404):
|
||||
return []
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
return data.get("items", data) if isinstance(data, dict) else data
|
||||
|
||||
|
||||
async def _evo_fetch_groups(token: str, store_id: str) -> list[dict]:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.get(
|
||||
f"{EVOTOR_API_BASE}/stores/{store_id}/product-groups",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=30,
|
||||
)
|
||||
if resp.status_code in (402, 404):
|
||||
return []
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
return data.get("items", data) if isinstance(data, dict) else data
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# VK API helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _vk_params(token: str, **extra) -> dict:
|
||||
return {"access_token": token, "v": VK_API_VERSION, **extra}
|
||||
|
||||
|
||||
async def _vk_get_albums(token: str, owner_id: str) -> list[dict]:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.get(
|
||||
f"{VK_API_HOST}/market.getAlbums",
|
||||
params=_vk_params(token, owner_id=owner_id, count=200),
|
||||
timeout=30,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
return data.get("response", {}).get("items", [])
|
||||
|
||||
|
||||
async def _vk_create_album(token: str, owner_id: str, title: str) -> int | None:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{VK_API_HOST}/market.addAlbum",
|
||||
data=_vk_params(token, owner_id=owner_id, title=title),
|
||||
timeout=30,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
if "error" in data:
|
||||
logger.error("VK create album error: %s", data["error"])
|
||||
return None
|
||||
return data.get("response", {}).get("market_album_id")
|
||||
|
||||
|
||||
async def _vk_get_products(token: str, owner_id: str) -> list[dict]:
|
||||
"""Fetch all VK market items (handles pagination)."""
|
||||
items = []
|
||||
offset = 0
|
||||
count = 200
|
||||
async with httpx.AsyncClient() as client:
|
||||
while True:
|
||||
resp = await client.get(
|
||||
f"{VK_API_HOST}/market.get",
|
||||
params=_vk_params(token, owner_id=owner_id, extended=1,
|
||||
with_disabled=1, count=count, offset=offset),
|
||||
timeout=30,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
batch = data.get("response", {}).get("items", [])
|
||||
items.extend(batch)
|
||||
if len(batch) < count:
|
||||
break
|
||||
offset += count
|
||||
return items
|
||||
|
||||
|
||||
async def _vk_upload_photo(token: str, group_id: str, photo_path: str) -> str | None:
|
||||
"""Upload a photo and return photo_id."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
# Get upload URL
|
||||
resp = await client.get(
|
||||
f"{VK_API_HOST}/market.getProductPhotoUploadServer",
|
||||
params=_vk_params(token, group_id=group_id),
|
||||
timeout=30,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
if "error" in data:
|
||||
logger.error("VK get upload URL error: %s", data["error"])
|
||||
return None
|
||||
upload_url = data.get("response", {}).get("upload_url")
|
||||
if not upload_url:
|
||||
return None
|
||||
|
||||
# Upload photo
|
||||
with open(photo_path, "rb") as f:
|
||||
upload_resp = await client.post(upload_url, files={"file": f}, timeout=60)
|
||||
upload_resp.raise_for_status()
|
||||
upload_obj = upload_resp.json()
|
||||
|
||||
# Save photo
|
||||
save_resp = await client.post(
|
||||
f"{VK_API_HOST}/market.saveProductPhoto",
|
||||
data=_vk_params(token, upload_response=upload_resp.text),
|
||||
timeout=30,
|
||||
)
|
||||
save_resp.raise_for_status()
|
||||
save_data = save_resp.json()
|
||||
if "error" in save_data:
|
||||
logger.error("VK save photo error: %s", save_data["error"])
|
||||
return None
|
||||
return save_data.get("response", {}).get("photo_id")
|
||||
|
||||
|
||||
async def _vk_create_product(
|
||||
token: str, owner_id: str, name: str, description: str,
|
||||
price: int, stock_amount: int, photo_id: str, album_id: int | None,
|
||||
) -> int | None:
|
||||
params = _vk_params(
|
||||
token,
|
||||
owner_id=owner_id,
|
||||
name=name,
|
||||
description=description,
|
||||
category_id=VK_CATEGORY_ID,
|
||||
price=price,
|
||||
main_photo_id=photo_id,
|
||||
stock_amount=stock_amount,
|
||||
)
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(f"{VK_API_HOST}/market.add", data=params, timeout=30)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
if "error" in data:
|
||||
logger.error("VK create product error: %s", data["error"])
|
||||
return None
|
||||
product_id = data.get("response", {}).get("market_item_id")
|
||||
if product_id and album_id:
|
||||
await client.get(
|
||||
f"{VK_API_HOST}/market.addToAlbum",
|
||||
params=_vk_params(token, owner_id=owner_id,
|
||||
item_ids=product_id, album_ids=album_id),
|
||||
timeout=30,
|
||||
)
|
||||
return product_id
|
||||
|
||||
|
||||
async def _vk_edit_product(
|
||||
token: str, owner_id: str, item_id: int, name: str,
|
||||
description: str, price: int, stock_amount: int,
|
||||
) -> None:
|
||||
params = _vk_params(
|
||||
token,
|
||||
owner_id=owner_id,
|
||||
item_id=item_id,
|
||||
name=name,
|
||||
description=description,
|
||||
category_id=VK_CATEGORY_ID,
|
||||
price=price,
|
||||
stock_amount=stock_amount,
|
||||
)
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(f"{VK_API_HOST}/market.edit", data=params, timeout=30)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
if "error" in data:
|
||||
logger.error("VK edit product error: %s", data["error"])
|
||||
|
||||
|
||||
async def _vk_delete_product(token: str, owner_id: str, item_id: int) -> None:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{VK_API_HOST}/market.delete",
|
||||
data=_vk_params(token, owner_id=owner_id, item_id=item_id),
|
||||
timeout=30,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main sync logic per user
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _stamp_synced(db: Session, user_id: int, evo_id: str, now: datetime) -> None:
|
||||
db.query(CachedProduct).filter(
|
||||
CachedProduct.user_id == user_id,
|
||||
CachedProduct.evotor_id == evo_id,
|
||||
).update({"synced_at": now})
|
||||
db.commit()
|
||||
|
||||
|
||||
async def sync_user(
|
||||
user_id: int,
|
||||
evo_token: str,
|
||||
vk_token: str,
|
||||
vk_group_id: str,
|
||||
filters: list,
|
||||
photo_path: str,
|
||||
db: Session,
|
||||
) -> None:
|
||||
owner_id = f"-{vk_group_id}"
|
||||
now = datetime.utcnow()
|
||||
logger.info("Sync start: user_id=%d vk_group=%s", user_id, vk_group_id)
|
||||
|
||||
store_ids = _get_included_store_ids(filters)
|
||||
if not store_ids:
|
||||
logger.info("Sync skip: user_id=%d — no stores included in filters", user_id)
|
||||
return
|
||||
|
||||
# Collect all Evotor products and groups across included stores
|
||||
evo_products: list[dict] = []
|
||||
groups_by_id: dict[str, dict] = {}
|
||||
|
||||
for store_id in store_ids:
|
||||
raw_groups = await _evo_fetch_groups(evo_token, store_id)
|
||||
for g in raw_groups:
|
||||
gid = g.get("uuid") or g.get("id")
|
||||
if gid:
|
||||
groups_by_id[gid] = g
|
||||
|
||||
raw_products = await _evo_fetch_products(evo_token, store_id)
|
||||
for p in raw_products:
|
||||
pid = p.get("uuid") or p.get("id")
|
||||
gid = p.get("parentUuid") or p.get("parent_id")
|
||||
if not _is_group_included(gid, filters):
|
||||
continue
|
||||
if not _is_product_included(pid, filters):
|
||||
continue
|
||||
evo_products.append(p)
|
||||
|
||||
# Build evo product lookup by normalized name
|
||||
# {normalized_name: product_dict}
|
||||
evo_by_name: dict[str, dict] = {}
|
||||
for p in evo_products:
|
||||
raw_name = (p.get("name") or "").strip()
|
||||
norm = _normalize_name(raw_name)
|
||||
evo_by_name[norm] = p
|
||||
|
||||
# Fetch VK state
|
||||
vk_products = await _vk_get_products(vk_token, owner_id)
|
||||
vk_albums = await _vk_get_albums(vk_token, owner_id)
|
||||
vk_album_by_title: dict[str, dict] = {a["title"]: a for a in vk_albums}
|
||||
|
||||
# Ensure albums exist for all included groups
|
||||
for gid, group in groups_by_id.items():
|
||||
if not _is_group_included(gid, filters):
|
||||
continue
|
||||
title = group.get("name", "")
|
||||
if title and title not in vk_album_by_title:
|
||||
new_album_id = await _vk_create_album(vk_token, owner_id, title)
|
||||
if new_album_id:
|
||||
vk_album_by_title[title] = {"id": new_album_id, "title": title}
|
||||
logger.info("Created VK album '%s' for user_id=%d", title, user_id)
|
||||
|
||||
# Build VK product lookup by normalized name
|
||||
# {normalized_name: [vk_item, ...]}
|
||||
vk_by_name: dict[str, list[dict]] = {}
|
||||
for item in vk_products:
|
||||
norm = _normalize_name(item.get("title", ""))
|
||||
vk_by_name.setdefault(norm, []).append(item)
|
||||
|
||||
# --- UPDATE / CREATE ---
|
||||
for norm_name, evo_p in evo_by_name.items():
|
||||
evo_id = evo_p.get("uuid") or evo_p.get("id")
|
||||
raw_name = (evo_p.get("name") or "").strip()
|
||||
name_for_vk = _normalize_name(raw_name)
|
||||
measure = evo_p.get("measureName") or evo_p.get("measure_name")
|
||||
raw_price = evo_p.get("price") or 0
|
||||
price, price_info = _calc_price(raw_price, measure)
|
||||
allow_to_sell = evo_p.get("allowToSell") if evo_p.get("allowToSell") is not None else evo_p.get("allow_to_sell")
|
||||
stock_amount = VK_STOCK_AMOUNT if allow_to_sell else 0
|
||||
extra_desc = evo_p.get("description") or ""
|
||||
description = _build_description(raw_name, price_info, extra_desc).strip()
|
||||
|
||||
gid = evo_p.get("parentUuid") or evo_p.get("parent_id")
|
||||
group_name = groups_by_id.get(gid, {}).get("name") if gid else None
|
||||
album = vk_album_by_title.get(group_name) if group_name else None
|
||||
album_id = album["id"] if album else None
|
||||
|
||||
if norm_name in vk_by_name:
|
||||
# Update existing (use first match)
|
||||
vk_item = vk_by_name[norm_name][0]
|
||||
vk_id = vk_item["id"]
|
||||
orig_price = vk_item.get("price", {}).get("amount", 0)
|
||||
orig_price_int = int(orig_price) if orig_price else 0
|
||||
orig_desc = (vk_item.get("description") or "").strip()
|
||||
orig_stock = vk_item.get("stock_amount", 0)
|
||||
|
||||
price_changed = price != orig_price_int
|
||||
desc_changed = description != orig_desc
|
||||
stock_changed = stock_amount != orig_stock
|
||||
|
||||
if price_changed or desc_changed or stock_changed:
|
||||
logger.info(
|
||||
"Updating VK product '%s' user_id=%d (price=%s desc=%s stock=%s)",
|
||||
name_for_vk, user_id, price_changed, desc_changed, stock_changed,
|
||||
)
|
||||
await _vk_edit_product(
|
||||
vk_token, owner_id, vk_id, name_for_vk, description, price, stock_amount,
|
||||
)
|
||||
_stamp_synced(db, user_id, evo_id, now)
|
||||
else:
|
||||
# Create new (only if allow_to_sell)
|
||||
if not allow_to_sell:
|
||||
continue
|
||||
photo_id = await _vk_upload_photo(vk_token, vk_group_id, photo_path)
|
||||
if not photo_id:
|
||||
logger.error("Skipping product '%s' — photo upload failed", name_for_vk)
|
||||
continue
|
||||
logger.info("Creating VK product '%s' user_id=%d", name_for_vk, user_id)
|
||||
created = await _vk_create_product(
|
||||
vk_token, owner_id, name_for_vk, description,
|
||||
price, stock_amount, photo_id, album_id,
|
||||
)
|
||||
if created:
|
||||
_stamp_synced(db, user_id, evo_id, now)
|
||||
|
||||
# --- DELETE products in VK that are no longer in Evo ---
|
||||
for norm_name, vk_items in vk_by_name.items():
|
||||
if norm_name in evo_by_name:
|
||||
# Delete duplicates (keep first)
|
||||
for dup in vk_items[1:]:
|
||||
logger.info("Deleting duplicate VK product '%s' id=%d user_id=%d",
|
||||
norm_name, dup["id"], user_id)
|
||||
await _vk_delete_product(vk_token, owner_id, dup["id"])
|
||||
else:
|
||||
# Delete all — product removed from Evo
|
||||
for item in vk_items:
|
||||
logger.info("Deleting removed product '%s' id=%d user_id=%d",
|
||||
norm_name, item["id"], user_id)
|
||||
await _vk_delete_product(vk_token, owner_id, item["id"])
|
||||
|
||||
logger.info("Sync complete: user_id=%d", user_id)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Background loop
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def run_sync() -> None:
|
||||
from web.config import settings
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
configs = db.query(SyncConfig).filter(
|
||||
SyncConfig.is_enabled == True,
|
||||
SyncConfig.confirmed_at != None,
|
||||
).all()
|
||||
|
||||
for config in configs:
|
||||
user_id = config.user_id
|
||||
evo = db.query(EvotorConnection).filter(
|
||||
EvotorConnection.user_id == user_id
|
||||
).first()
|
||||
vk = db.query(VkConnection).filter(
|
||||
VkConnection.user_id == user_id
|
||||
).first()
|
||||
|
||||
if not evo or not vk:
|
||||
continue
|
||||
if not evo.access_token or not vk.access_token:
|
||||
continue
|
||||
if not vk.vk_user_id:
|
||||
continue
|
||||
|
||||
try:
|
||||
await sync_user(
|
||||
user_id=user_id,
|
||||
evo_token=evo.access_token,
|
||||
vk_token=vk.access_token,
|
||||
vk_group_id=vk.vk_user_id,
|
||||
filters=config.filters,
|
||||
photo_path=settings.VK_DEFAULT_PHOTO_PATH,
|
||||
db=db,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Sync failed for user_id=%d", user_id)
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error in sync runner")
|
||||
db.rollback()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
async def sync_loop(interval: int) -> None:
|
||||
while True:
|
||||
await run_sync()
|
||||
await asyncio.sleep(interval)
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{% block title %}EvoSync{% endblock %}</title>
|
||||
<title>{% block title %}ЭВОСИНК{% endblock %}</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
@@ -11,7 +11,7 @@
|
||||
<body>
|
||||
<nav class="navbar navbar-expand-lg bg-white border-bottom border-2 brand-border">
|
||||
<div class="container">
|
||||
<a href="/" class="navbar-brand brand-logo">EvoSync</a>
|
||||
<a href="/" class="navbar-brand brand-logo">ЭВОСИНК</a>
|
||||
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
@@ -64,6 +64,9 @@
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
|
||||
{% if jivosite_widget_id %}
|
||||
<script src="//code.jivosite.com/widget/{{ jivosite_widget_id }}" async></script>
|
||||
{% endif %}
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/inputmask@5.0.9/dist/inputmask.min.js"></script>
|
||||
<script>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Группы — {{ store.name }} — EvoSync{% endblock %}
|
||||
{% block title %}Группы — {{ store.name }} — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<nav aria-label="breadcrumb" class="mb-3">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Товары — EvoSync{% endblock %}
|
||||
{% block title %}Товары — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<nav aria-label="breadcrumb" class="mb-3">
|
||||
@@ -30,7 +30,7 @@
|
||||
<p>Товары не найдены.</p>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="table-responsive">
|
||||
<div class="table-responsive" style="overflow: visible;">
|
||||
<table class="table table-striped table-hover align-middle small">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
@@ -40,6 +40,7 @@
|
||||
<th>Кол-во</th>
|
||||
<th>Ед. изм.</th>
|
||||
<th>В продаже</th>
|
||||
<th>Синхронизирован</th>
|
||||
<th>Фильтр</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
@@ -62,6 +63,15 @@
|
||||
<i class="bi bi-x-circle-fill text-danger"></i>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{% if product.synced_at %}
|
||||
<span title="{{ product.synced_at.strftime('%d.%m.%Y %H:%M') }}">
|
||||
<i class="bi bi-check-circle-fill text-success"></i>
|
||||
</span>
|
||||
{% else %}
|
||||
<span class="text-muted">—</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{% if mode == "include" %}
|
||||
<span class="badge bg-success">✓ Включено</span>
|
||||
@@ -73,7 +83,7 @@
|
||||
</td>
|
||||
<td>
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-outline-secondary btn-sm dropdown-toggle" data-bs-toggle="dropdown">
|
||||
<button class="btn btn-outline-secondary btn-sm dropdown-toggle" data-bs-toggle="dropdown" data-bs-strategy="fixed">
|
||||
<i class="bi bi-funnel"></i>
|
||||
</button>
|
||||
<ul class="dropdown-menu dropdown-menu-end">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Каталог — EvoSync{% endblock %}
|
||||
{% block title %}Каталог — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="d-flex align-items-center justify-content-between mb-3">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Подтверждение email — EvoSync{% endblock %}
|
||||
{% block title %}Подтверждение email — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Подключения — EvoSync{% endblock %}
|
||||
{% block title %}Подключения — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="d-flex align-items-center justify-content-between mb-4">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Добавить подключение — EvoSync{% endblock %}
|
||||
{% block title %}Добавить подключение — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="d-flex align-items-center mb-4">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Email подтвержден — EvoSync{% endblock %}
|
||||
{% block title %}Email подтвержден — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Подключение Эвотор — EvoSync{% endblock %}
|
||||
{% block title %}Подключение Эвотор — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
@@ -7,12 +7,10 @@
|
||||
|
||||
{% if error %}
|
||||
<div class="alert alert-danger mt-4">
|
||||
{% if error == "invalid_state" %}
|
||||
<i class="bi bi-exclamation-triangle me-2"></i>Ошибка безопасности. Попробуйте подключить аккаунт заново.
|
||||
{% elif error == "token_exchange" %}
|
||||
<i class="bi bi-exclamation-triangle me-2"></i>Не удалось получить токен доступа от Эвотор. Попробуйте позже.
|
||||
{% elif error == "no_token" %}
|
||||
<i class="bi bi-exclamation-triangle me-2"></i>Эвотор не вернул токен доступа. Попробуйте позже.
|
||||
{% if error == "invalid_token" %}
|
||||
<i class="bi bi-exclamation-triangle me-2"></i>Токен недействителен. Проверьте правильность и попробуйте снова.
|
||||
{% elif error == "empty_token" %}
|
||||
<i class="bi bi-exclamation-triangle me-2"></i>Введите токен.
|
||||
{% else %}
|
||||
<i class="bi bi-exclamation-triangle me-2"></i>Произошла ошибка при подключении: {{ error }}
|
||||
{% endif %}
|
||||
@@ -48,8 +46,16 @@
|
||||
<span class="small">{{ connection.connected_at.strftime("%d.%m.%Y %H:%M") }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="card-body d-grid gap-2">
|
||||
<a href="/evotor/connect" class="btn btn-primary">Переподключить</a>
|
||||
<div class="card-footer">
|
||||
<p class="text-muted small mb-2">Обновить токен (Личный кабинет Эвотор → <strong>Приложения → ЭвоСинк → Настройки</strong>):</p>
|
||||
<form method="post" action="/evotor/token">
|
||||
<div class="input-group input-group-sm">
|
||||
<input type="text" name="token" class="form-control font-monospace" placeholder="Новый токен" required>
|
||||
<button type="submit" class="btn btn-outline-secondary">Обновить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="card-body d-grid">
|
||||
<form method="post" action="/evotor/disconnect">
|
||||
<button type="submit" class="btn btn-outline-danger w-100">Отключить аккаунт Эвотор</button>
|
||||
</form>
|
||||
@@ -59,17 +65,29 @@
|
||||
{# ── NOT CONNECTED STATE ── #}
|
||||
<div class="card-body">
|
||||
<p class="text-muted mb-3">
|
||||
Подключите ваш аккаунт Эвотор, чтобы система могла автоматически синхронизировать
|
||||
каталог товаров из вашей кассы в ВКонтакте.
|
||||
Для подключения вам нужно установить приложение <strong>ЭвоСинк</strong> в личном кабинете Эвотор
|
||||
и скопировать токен доступа из его настроек.
|
||||
</p>
|
||||
<ul class="text-muted small mb-4">
|
||||
<li>Вы будете перенаправлены на сайт Эвотор для авторизации</li>
|
||||
<li>После подтверждения доступа синхронизация будет настроена автоматически</li>
|
||||
<li>Вы можете отключить доступ в любой момент</li>
|
||||
</ul>
|
||||
<div class="d-grid">
|
||||
<a href="/evotor/connect" class="btn btn-primary btn-lg">Подключить Эвотор</a>
|
||||
</div>
|
||||
|
||||
<ol class="text-muted small mb-4">
|
||||
{% if app_url %}
|
||||
<li class="mb-1">Откройте <a href="{{ app_url }}" target="_blank" rel="noopener">приложение ЭвоСинк в магазине Эвотор <i class="bi bi-box-arrow-up-right small"></i></a> и установите его.</li>
|
||||
{% else %}
|
||||
<li class="mb-1">Найдите приложение <strong>ЭвоСинк</strong> в магазине Эвотор и установите его.</li>
|
||||
{% endif %}
|
||||
<li class="mb-1">Перейдите в раздел <strong>Приложения → ЭвоСинк → Настройки</strong>.</li>
|
||||
<li class="mb-1">Скопируйте токен доступа и вставьте его в поле ниже.</li>
|
||||
</ol>
|
||||
|
||||
<form method="post" action="/evotor/token">
|
||||
<div class="mb-3">
|
||||
<label class="form-label small text-muted">Токен доступа</label>
|
||||
<input type="text" name="token" class="form-control font-monospace" placeholder="Вставьте токен Эвотор" required autofocus>
|
||||
</div>
|
||||
<div class="d-grid">
|
||||
<button type="submit" class="btn btn-primary">Подключить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Забыли пароль — EvoSync{% endblock %}
|
||||
{% block title %}Забыли пароль — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Вход — EvoSync{% endblock %}
|
||||
{% block title %}Вход — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}{{ title }} — EvoSync{% endblock %}
|
||||
{% block title %}{{ title }} — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Изменить пароль — EvoSync{% endblock %}
|
||||
{% block title %}Изменить пароль — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Удалить аккаунт — EvoSync{% endblock %}
|
||||
{% block title %}Удалить аккаунт — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Редактировать профиль — EvoSync{% endblock %}
|
||||
{% block title %}Редактировать профиль — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Личный кабинет — EvoSync{% endblock %}
|
||||
{% block title %}Личный кабинет — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Регистрация — EvoSync{% endblock %}
|
||||
{% block title %}Регистрация — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Новый пароль — EvoSync{% endblock %}
|
||||
{% block title %}Новый пароль — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Синхронизация — EvoSync{% endblock %}
|
||||
{% block title %}Синхронизация — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1 class="h4 mb-4">Синхронизация</h1>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Подключение ВКонтакте — EvoSync{% endblock %}
|
||||
{% block title %}Подключение ВКонтакте — ЭВОСИНК{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
@@ -7,12 +7,10 @@
|
||||
|
||||
{% if error %}
|
||||
<div class="alert alert-danger mt-4">
|
||||
{% if error == "invalid_state" %}
|
||||
<i class="bi bi-exclamation-triangle me-2"></i>Ошибка безопасности. Попробуйте подключить аккаунт заново.
|
||||
{% elif error == "token_exchange" %}
|
||||
<i class="bi bi-exclamation-triangle me-2"></i>Не удалось получить токен доступа от ВКонтакте. Попробуйте позже.
|
||||
{% elif error == "no_token" %}
|
||||
<i class="bi bi-exclamation-triangle me-2"></i>ВКонтакте не вернул токен доступа. Попробуйте позже.
|
||||
{% if error == "invalid_token" %}
|
||||
<i class="bi bi-exclamation-triangle me-2"></i>Токен недействителен. Убедитесь, что скопировали ключ доступа сообщества правильно.
|
||||
{% elif error == "empty_token" %}
|
||||
<i class="bi bi-exclamation-triangle me-2"></i>Введите ключ доступа.
|
||||
{% else %}
|
||||
<i class="bi bi-exclamation-triangle me-2"></i>Произошла ошибка при подключении: {{ error }}
|
||||
{% endif %}
|
||||
@@ -31,15 +29,15 @@
|
||||
<span class="text-muted small">Статус</span>
|
||||
<span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>Подключено</span>
|
||||
</li>
|
||||
{% if connection.first_name or connection.last_name %}
|
||||
{% if connection.first_name %}
|
||||
<li class="list-group-item d-flex justify-content-between align-items-center">
|
||||
<span class="text-muted small">Профиль</span>
|
||||
<span>{{ connection.first_name }} {{ connection.last_name }}</span>
|
||||
<span class="text-muted small">Сообщество</span>
|
||||
<span>{{ connection.first_name }}</span>
|
||||
</li>
|
||||
{% endif %}
|
||||
{% if connection.vk_user_id %}
|
||||
<li class="list-group-item d-flex justify-content-between align-items-center">
|
||||
<span class="text-muted small">ID пользователя</span>
|
||||
<span class="text-muted small">ID сообщества</span>
|
||||
<span class="font-monospace small text-muted">{{ connection.vk_user_id }}</span>
|
||||
</li>
|
||||
{% endif %}
|
||||
@@ -48,10 +46,18 @@
|
||||
<span class="small">{{ connection.connected_at.strftime("%d.%m.%Y %H:%M") }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="card-body d-grid gap-2">
|
||||
<a href="/vk/connect" class="btn btn-primary">Переподключить</a>
|
||||
<div class="card-footer">
|
||||
<p class="text-muted small mb-2">Обновить ключ доступа:</p>
|
||||
<form method="post" action="/vk/token">
|
||||
<div class="input-group input-group-sm">
|
||||
<input type="text" name="token" class="form-control font-monospace" placeholder="Новый ключ доступа" required>
|
||||
<button type="submit" class="btn btn-outline-secondary">Обновить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="card-body d-grid">
|
||||
<form method="post" action="/vk/disconnect">
|
||||
<button type="submit" class="btn btn-outline-danger w-100">Отключить аккаунт ВКонтакте</button>
|
||||
<button type="submit" class="btn btn-outline-danger w-100">Отключить ВКонтакте</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -59,17 +65,26 @@
|
||||
{# ── NOT CONNECTED STATE ── #}
|
||||
<div class="card-body">
|
||||
<p class="text-muted mb-3">
|
||||
Подключите ваш аккаунт ВКонтакте, чтобы система могла автоматически синхронизировать
|
||||
каталог товаров из Эвотор в вашу группу ВКонтакте.
|
||||
Для подключения вам нужен <strong>ключ доступа сообщества</strong> ВКонтакте.
|
||||
Синхронизация товаров работает только через сообщество.
|
||||
</p>
|
||||
<ul class="text-muted small mb-4">
|
||||
<li>Вы будете перенаправлены на сайт ВКонтакте для авторизации</li>
|
||||
<li>После подтверждения доступа синхронизация будет настроена автоматически</li>
|
||||
<li>Вы можете отключить доступ в любой момент</li>
|
||||
</ul>
|
||||
<div class="d-grid">
|
||||
<a href="/vk/connect" class="btn btn-primary btn-lg">Подключить ВКонтакте</a>
|
||||
</div>
|
||||
|
||||
<ol class="text-muted small mb-4">
|
||||
<li class="mb-1">Откройте <a href="https://vk.com" target="_blank" rel="noopener">vk.com <i class="bi bi-box-arrow-up-right small"></i></a> и перейдите в управление вашим сообществом.</li>
|
||||
<li class="mb-1">Перейдите в раздел <strong>Настройки → Работа с API</strong>.</li>
|
||||
<li class="mb-1">Создайте ключ доступа с правами <strong>Управление товарами</strong> и <strong>Управление сообществом</strong>.</li>
|
||||
<li class="mb-1">Скопируйте ключ и вставьте его в поле ниже.</li>
|
||||
</ol>
|
||||
|
||||
<form method="post" action="/vk/token">
|
||||
<div class="mb-3">
|
||||
<label class="form-label small text-muted">Ключ доступа сообщества</label>
|
||||
<input type="text" name="token" class="form-control font-monospace" placeholder="Вставьте ключ доступа" required autofocus>
|
||||
</div>
|
||||
<div class="d-grid">
|
||||
<button type="submit" class="btn btn-primary">Подключить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
|
||||
6
web/templates_env.py
Normal file
6
web/templates_env.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from fastapi.templating import Jinja2Templates
|
||||
|
||||
from web.config import settings
|
||||
|
||||
templates = Jinja2Templates(directory="web/templates")
|
||||
templates.env.globals["jivosite_widget_id"] = settings.JIVOSITE_WIDGET_ID
|
||||
Reference in New Issue
Block a user