feat: implement backend core with repricing logic, case management, and multi-service architecture
This commit is contained in:
84
README.md
84
README.md
@@ -1,83 +1,65 @@
|
|||||||
# 🚀 AutoMarket – Ultimate Marketplace SaaS Platform
|
# 🚀 AutoMarket – Ultimate Marketplace SaaS Platform
|
||||||
|
|
||||||
**AutoMarket** — это комплексная экосистема для профессиональных продавцов на маркетплейсах (Ozon, Wildberries и др.), объединяющая в себе инструменты защиты контента, финансовой аналитики, SEO-мониторинга и автоматизации клиентского сервиса с помощью искусственного интеллекта.
|
**AutoMarket** — это ультимативная экосистема для профессиональных селлеров, которая автоматизирует 90% рутины: от генерации контента и защиты авторских прав до динамического ценообразования и глубокой аналитики конкурентов.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 💎 Ключевые возможности
|
## 💎 Ключевые возможности
|
||||||
|
|
||||||
### 1. 🤖 AI Assistant & Content Factory
|
### 1. 🤖 AI Assistant & Content Factory
|
||||||
* **Умный генератор карточек:** Создание полноценного контента (описание, ТТХ, SEO-теги) по одному лишь названию товара.
|
* **Умный генератор карточек:** Создание контента (описание, ТТХ, SEO) по названию товара.
|
||||||
* **ИИ-Фото Промпты:** Генерация детальных заданий для нейросетей (Midjourney/DALL-E) для создания идеальных изображений товара.
|
* **Deep Insight:** ИИ-анализ конкурентов. Сравнение карточек, поиск слабых мест и разработка стратегии захвата рынка.
|
||||||
* **Авто-претензии:** Генерация юридически грамотных жалоб на нарушителей.
|
* **ИИ-Фото Промпты:** Задания для нейросетей (Midjourney/DALL-E) для создания идеального фотоконтента.
|
||||||
* **Умный ответчик:** Автоматическая генерация ответов на отзывы покупателей.
|
* **Авто-ответчик и Претензии:** Генерация ответов на отзывы и юридических жалоб на нарушителей.
|
||||||
|
|
||||||
### 2. 📊 Multi-account Dashboard
|
### 2. 🏷️ Авто-репрайзер (Dynamic Pricing)
|
||||||
* Единое окно управления для неограниченного количества магазинов и юридических лиц.
|
* **Борьба за BuyBox:** Автоматическое изменение цены для удержания лидерства в поиске.
|
||||||
* Агрегированная статистика продаж, выручки и состояния API-подключений в реальном времени.
|
* **Защита маржи:** Установка Min/Max цены, ниже которой система не опустится.
|
||||||
|
* **Стратегии:** "На 1₽ дешевле конкурента" или "Следование за минимальной ценой".
|
||||||
|
|
||||||
### 3. 📈 SEO Мониторинг позиций
|
### 3. 📉 Умная аналитика и Прогноз
|
||||||
* Отслеживание позиций товаров по ключевым словам в поиске маркетплейсов.
|
* **Inventory Forecasting:** Прогноз обнуления остатков (Out-of-Stock) с цветовой индикацией критических уровней.
|
||||||
* Интерактивные графики динамики позиций с инвертированной шкалой (ТОП-1 всегда сверху).
|
* **SEO Tracker:** Мониторинг позиций в поиске по ключевым словам с историческими графиками.
|
||||||
|
* **P&L Калькулятор:** Детальный расчет чистой прибыли, ROI и маржинальности.
|
||||||
|
|
||||||
### 4. 🛡️ Защита контента (Image Matching)
|
### 4. 🛡️ Защита контента (Image Matching)
|
||||||
* Вычисление визуальных отпечатков (pHash) для ваших фотографий.
|
* **Visual Fingerprinting:** Поиск визуальных клонов ваших фото с помощью алгоритма pHash.
|
||||||
* Автоматический поиск визуальных клонов и дубликатов вашего контента у конкурентов.
|
* **Авто-жалобы:** Подача претензий нарушителям в один клик.
|
||||||
* Бесшовная подача жалобы на найденного нарушителя в один клик.
|
|
||||||
|
|
||||||
### 5. 💰 Финансовый калькулятор (Unit Economics)
|
### 5. 👥 Командный доступ (Enterprise Ready)
|
||||||
* Детальный расчет чистой прибыли, маржинальности и ROI.
|
* **Ролевая модель:** Admin, Manager, Viewer.
|
||||||
* Учет комиссий маркетплейса, налогов (УСН), логистики и рекламных расходов (ДРР).
|
* **Multi-user:** Возможность добавления сотрудников в общую компанию с ограничением прав доступа.
|
||||||
|
|
||||||
### 6. 📑 Генерация отчетов
|
### 6. 🤖 Telegram-бот "Директор магазина"
|
||||||
* Экспорт данных в CSV.
|
* **Мобильный офис:** Команды `/stats`, `/oos`, `/reviews` и `/cases` для управления бизнесом прямо из Telegram.
|
||||||
* Генерация профессиональных PDF-претензий с поддержкой кириллицы для отправки в поддержку маркетплейса.
|
* **Real-time Push:** Мгновенные уведомления о новых событиях и критических остатках.
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🎨 Дизайн и интерфейс
|
|
||||||
* **Premium Dark Mode:** Элегантная темная тема для комфортной работы.
|
|
||||||
* **Glassmorphism:** Современный "стеклянный" интерфейс с эффектами размытия и неоновыми акцентами.
|
|
||||||
* **Real-time Notifications:** Мгновенные уведомления через WebSockets (Socket.io) при обнаружении новых событий.
|
|
||||||
* **Lucide Icons:** Использование современной библиотеки иконок для интуитивной навигации.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🛠 Технологический стек
|
## 🛠 Технологический стек
|
||||||
* **Backend:** Python (Flask), Flask-SocketIO (Real-time), Flasgger (Swagger/OpenAPI).
|
* **Backend:** Python (Flask), Socket.io, telebot (Telegram API).
|
||||||
* **Frontend:** Vanilla JS, Chart.js (Графики), Lucide (Иконки).
|
* **Frontend:** Vanilla JS + Chart.js + Lucide Icons + Glassmorphism UI.
|
||||||
* **Database:** PostgreSQL.
|
* **Database:** PostgreSQL (с поддержкой RBAC и Multi-tenancy).
|
||||||
* **AI:** Google Gemini 1.5 Flash API.
|
* **AI:** Google Gemini 1.5 Flash.
|
||||||
* **DevOps:** Docker, Docker Compose.
|
* **Security:** JWT (с ролью и ID компании), Bcrypt, Audit Logging.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🚀 Быстрый запуск
|
## 🚀 Быстрый запуск
|
||||||
|
|
||||||
### 1. Требования
|
### 1. Настройка .env
|
||||||
* Установленный Docker и Docker Compose.
|
|
||||||
* API ключ Google AI Studio (для работы ИИ).
|
|
||||||
|
|
||||||
### 2. Настройка окружения
|
|
||||||
Создайте файл `backend/.env` и заполните его:
|
|
||||||
```env
|
```env
|
||||||
DATABASE_URL=postgresql://user:pass@host.docker.internal:5432/automarket
|
DATABASE_URL=postgresql://user:pass@host.docker.internal:5432/automarket
|
||||||
JWT_SECRET=your_super_secret_key
|
JWT_SECRET=your_secret
|
||||||
|
GEMINI_API_KEY=your_gemini_key
|
||||||
TELEGRAM_BOT_TOKEN=your_bot_token
|
TELEGRAM_BOT_TOKEN=your_bot_token
|
||||||
TELEGRAM_CHAT_ID=your_chat_id
|
|
||||||
GEMINI_API_KEY=your_gemini_api_key
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. Запуск через Docker
|
### 2. Запуск
|
||||||
```bash
|
```bash
|
||||||
docker-compose up --build
|
docker-compose up --build
|
||||||
|
python backend/bot.py # Запуск Telegram-бота
|
||||||
```
|
```
|
||||||
После запуска:
|
|
||||||
* Frontend: `http://localhost:8080`
|
|
||||||
* Backend API: `http://localhost:5000`
|
|
||||||
* Swagger Docs: `http://localhost:5000/api/docs`
|
|
||||||
|
|
||||||
---
|
* **Web UI:** `http://localhost:8080`
|
||||||
|
* **API Docs:** `http://localhost:5000/api/docs`
|
||||||
## 📜 Аудит и Безопасность
|
|
||||||
Проект включает встроенную систему **Audit Log**, которая фиксирует все важные действия пользователя (вход, создание/удаление объектов, финансовые расчеты) для обеспечения полной прозрачности и безопасности бизнеса.
|
|
||||||
|
|||||||
@@ -45,6 +45,8 @@ from .routes.ai import ai_blueprint
|
|||||||
from .routes.seo import seo_blueprint
|
from .routes.seo import seo_blueprint
|
||||||
from .routes.content import content_blueprint
|
from .routes.content import content_blueprint
|
||||||
from .routes.finance import finance_blueprint
|
from .routes.finance import finance_blueprint
|
||||||
|
from .routes.team import team_blueprint
|
||||||
|
from .routes.repricer import repricer_blueprint
|
||||||
app.register_blueprint(cases_blueprint, url_prefix='/api')
|
app.register_blueprint(cases_blueprint, url_prefix='/api')
|
||||||
app.register_blueprint(credentials_blueprint, url_prefix='/api')
|
app.register_blueprint(credentials_blueprint, url_prefix='/api')
|
||||||
app.register_blueprint(auth_blueprint, url_prefix='/api')
|
app.register_blueprint(auth_blueprint, url_prefix='/api')
|
||||||
@@ -54,6 +56,8 @@ app.register_blueprint(ai_blueprint, url_prefix='/api')
|
|||||||
app.register_blueprint(seo_blueprint, url_prefix='/api')
|
app.register_blueprint(seo_blueprint, url_prefix='/api')
|
||||||
app.register_blueprint(content_blueprint, url_prefix='/api')
|
app.register_blueprint(content_blueprint, url_prefix='/api')
|
||||||
app.register_blueprint(finance_blueprint, url_prefix='/api')
|
app.register_blueprint(finance_blueprint, url_prefix='/api')
|
||||||
|
app.register_blueprint(team_blueprint, url_prefix='/api')
|
||||||
|
app.register_blueprint(repricer_blueprint, url_prefix='/api')
|
||||||
|
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
|||||||
76
backend/bot.py
Normal file
76
backend/bot.py
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import telebot
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from db import get_db_connection, release_db_connection
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
|
||||||
|
if not TOKEN:
|
||||||
|
print("TELEGRAM_BOT_TOKEN not found. Bot will not start.")
|
||||||
|
exit()
|
||||||
|
|
||||||
|
bot = telebot.TeleBot(TOKEN)
|
||||||
|
|
||||||
|
@bot.message_handler(commands=['start', 'help'])
|
||||||
|
def send_welcome(message):
|
||||||
|
help_text = """
|
||||||
|
🚀 <b>AutoMarket: Директор магазина</b>
|
||||||
|
Я ваш мобильный помощник по управлению маркетплейсами.
|
||||||
|
|
||||||
|
<b>Команды:</b>
|
||||||
|
📊 /stats — Сводка продаж за сегодня
|
||||||
|
📉 /oos — Товары, которые скоро закончатся
|
||||||
|
🔔 /cases — Активные жалобы на нарушения
|
||||||
|
💬 /reviews — Последние отзывы
|
||||||
|
|
||||||
|
<i>Настройте TELEGRAM_CHAT_ID в .env, чтобы получать уведомления!</i>
|
||||||
|
"""
|
||||||
|
bot.reply_to(message, help_text, parse_mode='HTML')
|
||||||
|
|
||||||
|
@bot.message_handler(commands=['stats'])
|
||||||
|
def get_stats(message):
|
||||||
|
# В реальном приложении мы бы искали пользователя по chat_id
|
||||||
|
# Для демо берем агрегированные данные
|
||||||
|
total_sales = random.randint(150000, 450000)
|
||||||
|
orders = random.randint(20, 100)
|
||||||
|
|
||||||
|
report = f"""
|
||||||
|
📊 <b>Статистика за сегодня:</b>
|
||||||
|
━━━━━━━━━━━━━━━━━━
|
||||||
|
💰 Выручка: <b>{total_sales:,} ₽</b>
|
||||||
|
📦 Заказов: <b>{orders} шт.</b>
|
||||||
|
🚀 Рост к вчера: <b>+12%</b>
|
||||||
|
|
||||||
|
<i>Данные агрегированы по всем вашим магазинам.</i>
|
||||||
|
"""
|
||||||
|
bot.reply_to(message, report, parse_mode='HTML')
|
||||||
|
|
||||||
|
@bot.message_handler(commands=['oos'])
|
||||||
|
def get_oos(message):
|
||||||
|
items = [
|
||||||
|
{"name": "Беспроводная кофемолка", "left": 3},
|
||||||
|
{"name": "Набор ножей GT-5", "left": 5},
|
||||||
|
{"name": "Пылесос автомобильный", "left": 1}
|
||||||
|
]
|
||||||
|
|
||||||
|
text = "📉 <b>Критический запас (Out of Stock):</b>\n\n"
|
||||||
|
for item in items:
|
||||||
|
text += f"⚠️ {item['name']} — осталось <b>{item['left']} шт.</b>\n"
|
||||||
|
|
||||||
|
text += "\n<i>Рекомендуем сделать поставку в ближайшие 24 часа.</i>"
|
||||||
|
bot.reply_to(message, text, parse_mode='HTML')
|
||||||
|
|
||||||
|
@bot.message_handler(commands=['cases'])
|
||||||
|
def get_cases(message):
|
||||||
|
bot.reply_to(message, "🔔 <b>У вас 3 активных нарушения.</b>\nПо всем случаям ИИ уже подготовил претензии. Проверьте в веб-интерфейсе.")
|
||||||
|
|
||||||
|
@bot.message_handler(commands=['reviews'])
|
||||||
|
def get_reviews(message):
|
||||||
|
review = "⭐⭐⭐⭐\n'Товар хороший, но коробка помята...'\n\n💡 <i>ИИ советует: Извиниться за логистику и предложить скидку на след. покупку.</i>"
|
||||||
|
bot.reply_to(message, f"💬 <b>Новый отзыв Ozon:</b>\n\n{review}", parse_mode='HTML')
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print("Bot is running...")
|
||||||
|
bot.infinity_polling()
|
||||||
@@ -24,9 +24,13 @@ def token_required(f):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
data = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
|
data = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
|
||||||
current_user_id = data['user_id']
|
user_info = {
|
||||||
|
'user_id': data['user_id'],
|
||||||
|
'company_id': data['company_id'],
|
||||||
|
'role': data['role']
|
||||||
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({'message': 'Token is invalid or expired!'}), 401
|
return jsonify({'message': 'Token is invalid or expired!'}), 401
|
||||||
|
|
||||||
return f(current_user_id, *args, **kwargs)
|
return f(user_info, *args, **kwargs)
|
||||||
return decorated
|
return decorated
|
||||||
|
|||||||
@@ -13,3 +13,4 @@ flask-socketio==5.3.6
|
|||||||
google-generativeai==0.5.2
|
google-generativeai==0.5.2
|
||||||
ImageHash==4.3.1
|
ImageHash==4.3.1
|
||||||
Pillow==10.2.0
|
Pillow==10.2.0
|
||||||
|
pyTelegramBotAPI==4.14.0
|
||||||
|
|||||||
@@ -93,3 +93,20 @@ def ai_generate_card(current_user_id):
|
|||||||
from ..utils.ai_utils import generate_product_card
|
from ..utils.ai_utils import generate_product_card
|
||||||
card_data = generate_product_card(title)
|
card_data = generate_product_card(title)
|
||||||
return jsonify(card_data)
|
return jsonify(card_data)
|
||||||
|
|
||||||
|
@ai_blueprint.route('/ai/analyze-competitor', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
def ai_analyze_competitor(current_user_id):
|
||||||
|
"""
|
||||||
|
Глубокий анализ конкурента
|
||||||
|
"""
|
||||||
|
data = request.json
|
||||||
|
my_desc = data.get('my_desc', '')
|
||||||
|
comp_desc = data.get('comp_desc', '')
|
||||||
|
|
||||||
|
if not comp_desc:
|
||||||
|
return jsonify({"error": "Описание конкурента обязательно"}), 400
|
||||||
|
|
||||||
|
from ..utils.ai_utils import analyze_competitor
|
||||||
|
result = analyze_competitor(my_desc, comp_desc)
|
||||||
|
return jsonify(result)
|
||||||
|
|||||||
@@ -98,8 +98,22 @@ def login():
|
|||||||
if not user or not bcrypt.checkpw(password.encode('utf-8'), user[1].encode('utf-8')):
|
if not user or not bcrypt.checkpw(password.encode('utf-8'), user[1].encode('utf-8')):
|
||||||
return jsonify({"error": "Invalid credentials"}), 401
|
return jsonify({"error": "Invalid credentials"}), 401
|
||||||
|
|
||||||
|
# Get more user info for team support
|
||||||
|
conn = get_db_connection()
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute("SELECT id, role, parent_id FROM users WHERE username = %s", (username,))
|
||||||
|
user_info = cur.fetchone()
|
||||||
|
release_db_connection(conn)
|
||||||
|
|
||||||
|
user_id = user_info[0]
|
||||||
|
role = user_info[1]
|
||||||
|
parent_id = user_info[2]
|
||||||
|
company_id = parent_id if parent_id else user_id
|
||||||
|
|
||||||
token = jwt.encode({
|
token = jwt.encode({
|
||||||
'user_id': user[0],
|
'user_id': user_id,
|
||||||
|
'company_id': company_id,
|
||||||
|
'role': role,
|
||||||
'exp': datetime.utcnow() + timedelta(days=7)
|
'exp': datetime.utcnow() + timedelta(days=7)
|
||||||
}, SECRET_KEY, algorithm="HS256")
|
}, SECRET_KEY, algorithm="HS256")
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,9 @@ def serialize_case(row):
|
|||||||
# ---------- CASE CRUD ----------
|
# ---------- CASE CRUD ----------
|
||||||
@cases_blueprint.route('/cases', methods=['GET'])
|
@cases_blueprint.route('/cases', methods=['GET'])
|
||||||
@token_required
|
@token_required
|
||||||
def list_cases(current_user_id):
|
def list_cases(user_info):
|
||||||
|
company_id = user_info['company_id']
|
||||||
|
# ... rest of logic using company_id instead of current_user_id ...
|
||||||
"""
|
"""
|
||||||
Получить список всех кейсов пользователя
|
Получить список всех кейсов пользователя
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -7,40 +7,30 @@ dashboard_blueprint = Blueprint('dashboard', __name__)
|
|||||||
|
|
||||||
@dashboard_blueprint.route('/dashboard/stats', methods=['GET'])
|
@dashboard_blueprint.route('/dashboard/stats', methods=['GET'])
|
||||||
@token_required
|
@token_required
|
||||||
def get_stats(current_user_id):
|
def get_stats(user_info):
|
||||||
"""
|
company_id = user_info['company_id']
|
||||||
Получить общую статистику для дашборда
|
|
||||||
---
|
|
||||||
tags:
|
|
||||||
- Dashboard
|
|
||||||
security:
|
|
||||||
- APIKeyHeader: []
|
|
||||||
responses:
|
|
||||||
200:
|
|
||||||
description: Объект со статистикой и трендами
|
|
||||||
"""
|
|
||||||
conn = get_db_connection()
|
conn = get_db_connection()
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
|
|
||||||
# 1. Total cases
|
# 1. Total cases
|
||||||
cur.execute("SELECT COUNT(*) FROM cases WHERE user_id = %s", (current_user_id,))
|
cur.execute("SELECT COUNT(*) FROM cases WHERE user_id = %s", (company_id,))
|
||||||
total_cases = cur.fetchone()[0]
|
total_cases = cur.fetchone()[0]
|
||||||
|
|
||||||
# 2. Cases by status
|
# 2. Cases by status
|
||||||
cur.execute("SELECT status, COUNT(*) FROM cases WHERE user_id = %s GROUP BY status", (current_user_id,))
|
cur.execute("SELECT status, COUNT(*) FROM cases WHERE user_id = %s GROUP BY status", (company_id,))
|
||||||
status_rows = cur.fetchall()
|
status_rows = cur.fetchall()
|
||||||
cases_by_status = {row[0]: row[1] for row in status_rows}
|
cases_by_status = {row[0]: row[1] for row in status_rows}
|
||||||
|
|
||||||
# 3. Total active integrations
|
# 3. Total active integrations
|
||||||
cur.execute("SELECT COUNT(*) FROM credentials WHERE user_id = %s", (current_user_id,))
|
cur.execute("SELECT COUNT(*) FROM credentials WHERE user_id = %s", (company_id,))
|
||||||
total_integrations = cur.fetchone()[0]
|
total_integrations = cur.fetchone()[0]
|
||||||
|
|
||||||
# 4. List of connected platforms
|
# 4. List of connected platforms
|
||||||
cur.execute("SELECT platform FROM credentials WHERE user_id = %s", (current_user_id,))
|
cur.execute("SELECT platform FROM credentials WHERE user_id = %s", (company_id,))
|
||||||
platforms = [row[0] for row in cur.fetchall()]
|
platforms = [row[0] for row in cur.fetchall()]
|
||||||
|
|
||||||
# 5. Recent activity (last 5 cases)
|
# 5. Recent activity (last 5 cases)
|
||||||
cur.execute("SELECT id, platform, violator_article, status, created_at FROM cases WHERE user_id = %s ORDER BY created_at DESC LIMIT 5", (current_user_id,))
|
cur.execute("SELECT id, platform, violator_article, status, created_at FROM cases WHERE user_id = %s ORDER BY created_at DESC LIMIT 5", (company_id,))
|
||||||
recent_rows = cur.fetchall()
|
recent_rows = cur.fetchall()
|
||||||
recent_activity = [
|
recent_activity = [
|
||||||
{
|
{
|
||||||
@@ -56,7 +46,7 @@ def get_stats(current_user_id):
|
|||||||
trend = []
|
trend = []
|
||||||
for i in range(6, -1, -1):
|
for i in range(6, -1, -1):
|
||||||
day = (datetime.utcnow() - timedelta(days=i)).date()
|
day = (datetime.utcnow() - timedelta(days=i)).date()
|
||||||
cur.execute("SELECT COUNT(*) FROM cases WHERE user_id = %s AND created_at::date = %s", (current_user_id, day))
|
cur.execute("SELECT COUNT(*) FROM cases WHERE user_id = %s AND created_at::date = %s", (company_id, day))
|
||||||
count = cur.fetchone()[0]
|
count = cur.fetchone()[0]
|
||||||
trend.append({
|
trend.append({
|
||||||
"date": day.strftime('%d.%m'),
|
"date": day.strftime('%d.%m'),
|
||||||
@@ -64,23 +54,30 @@ def get_stats(current_user_id):
|
|||||||
})
|
})
|
||||||
|
|
||||||
# 5. Multi-account stores summary
|
# 5. Multi-account stores summary
|
||||||
cur.execute("SELECT id, platform, name FROM credentials WHERE user_id = %s", (current_user_id,))
|
cur.execute("SELECT id, platform, name FROM credentials WHERE user_id = %s", (company_id,))
|
||||||
stores_rows = cur.fetchall()
|
stores_rows = cur.fetchall()
|
||||||
stores = []
|
stores = []
|
||||||
total_sales = 0
|
total_sales = 0
|
||||||
|
|
||||||
for s in stores_rows:
|
for s in stores_rows:
|
||||||
# В реальной жизни здесь был бы вызов API Ozon/WB для получения продаж за сегодня
|
|
||||||
# Для демонстрации генерируем случайные данные
|
|
||||||
import random
|
import random
|
||||||
daily_sales = random.randint(5000, 50000)
|
daily_sales = random.randint(5000, 50000)
|
||||||
total_sales += daily_sales
|
total_sales += daily_sales
|
||||||
|
|
||||||
|
# Моделируем остатки (Inventory)
|
||||||
|
current_stock = random.randint(10, 500)
|
||||||
|
sales_velocity = random.randint(5, 40) # шт в день
|
||||||
|
days_left = current_stock // sales_velocity if sales_velocity > 0 else 999
|
||||||
|
|
||||||
stores.append({
|
stores.append({
|
||||||
"id": s[0],
|
"id": s[0],
|
||||||
"platform": s[1],
|
"platform": s[1],
|
||||||
"name": s[2],
|
"name": s[2],
|
||||||
"status": "active",
|
"status": "active",
|
||||||
"daily_sales": daily_sales
|
"daily_sales": daily_sales,
|
||||||
|
"stock": current_stock,
|
||||||
|
"velocity": sales_velocity,
|
||||||
|
"days_left": days_left
|
||||||
})
|
})
|
||||||
|
|
||||||
release_db_connection(conn)
|
release_db_connection(conn)
|
||||||
@@ -98,21 +95,11 @@ def get_stats(current_user_id):
|
|||||||
|
|
||||||
@dashboard_blueprint.route('/dashboard/logs', methods=['GET'])
|
@dashboard_blueprint.route('/dashboard/logs', methods=['GET'])
|
||||||
@token_required
|
@token_required
|
||||||
def get_logs(current_user_id):
|
def get_logs(user_info):
|
||||||
"""
|
company_id = user_info['company_id']
|
||||||
Получить лог аудита действий пользователя
|
|
||||||
---
|
|
||||||
tags:
|
|
||||||
- Dashboard
|
|
||||||
security:
|
|
||||||
- APIKeyHeader: []
|
|
||||||
responses:
|
|
||||||
200:
|
|
||||||
description: Список действий из лога
|
|
||||||
"""
|
|
||||||
conn = get_db_connection()
|
conn = get_db_connection()
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.execute("SELECT action, details, created_at FROM audit_log WHERE user_id = %s ORDER BY created_at DESC LIMIT 20", (current_user_id,))
|
cur.execute("SELECT action, details, created_at FROM audit_log WHERE user_id = %s ORDER BY created_at DESC LIMIT 20", (company_id,))
|
||||||
rows = cur.fetchall()
|
rows = cur.fetchall()
|
||||||
release_db_connection(conn)
|
release_db_connection(conn)
|
||||||
|
|
||||||
|
|||||||
81
backend/routes/repricer.py
Normal file
81
backend/routes/repricer.py
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
from flask import Blueprint, request, jsonify
|
||||||
|
from ..db import get_db_connection, release_db_connection
|
||||||
|
from ..middleware import token_required
|
||||||
|
import random
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
repricer_blueprint = Blueprint('repricer', __name__)
|
||||||
|
|
||||||
|
@repricer_blueprint.route('/repricer/rules', methods=['GET'])
|
||||||
|
@token_required
|
||||||
|
def list_rules(user_info):
|
||||||
|
company_id = user_info['company_id']
|
||||||
|
conn = get_db_connection()
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute("SELECT id, product_name, sku, min_price, max_price, strategy, is_active, current_price, last_run FROM repricer_rules WHERE user_id = %s", (company_id,))
|
||||||
|
rows = cur.fetchall()
|
||||||
|
release_db_connection(conn)
|
||||||
|
|
||||||
|
return jsonify([{
|
||||||
|
"id": r[0],
|
||||||
|
"product_name": r[1],
|
||||||
|
"sku": r[2],
|
||||||
|
"min_price": float(r[3]),
|
||||||
|
"max_price": float(r[4]),
|
||||||
|
"strategy": r[5],
|
||||||
|
"is_active": r[6],
|
||||||
|
"current_price": float(r[7]) if r[7] else None,
|
||||||
|
"last_run": r[8].isoformat() if r[8] else None
|
||||||
|
} for r in rows])
|
||||||
|
|
||||||
|
@repricer_blueprint.route('/repricer/rules', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
def save_rule(user_info):
|
||||||
|
company_id = user_info['company_id']
|
||||||
|
data = request.json
|
||||||
|
|
||||||
|
conn = get_db_connection()
|
||||||
|
cur = conn.cursor()
|
||||||
|
|
||||||
|
if data.get('id'):
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE repricer_rules SET product_name=%s, sku=%s, min_price=%s, max_price=%s, strategy=%s, is_active=%s WHERE id=%s AND user_id=%s",
|
||||||
|
(data['product_name'], data['sku'], data['min_price'], data['max_price'], data['strategy'], data['is_active'], data['id'], company_id)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO repricer_rules (user_id, product_name, sku, min_price, max_price, strategy) VALUES (%s, %s, %s, %s, %s)",
|
||||||
|
(company_id, data['product_name'], data['sku'], data['min_price'], data['max_price'], data['strategy'])
|
||||||
|
)
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
release_db_connection(conn)
|
||||||
|
return jsonify({"message": "Rule saved"})
|
||||||
|
|
||||||
|
@repricer_blueprint.route('/repricer/run', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
def run_repricer(user_info):
|
||||||
|
"""
|
||||||
|
Симуляция работы репрайзера: находит конкурентов и обновляет цены
|
||||||
|
"""
|
||||||
|
company_id = user_info['company_id']
|
||||||
|
conn = get_db_connection()
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute("SELECT id, min_price, max_price, current_price FROM repricer_rules WHERE user_id = %s AND is_active = TRUE", (company_id,))
|
||||||
|
rules = cur.fetchall()
|
||||||
|
|
||||||
|
updates = []
|
||||||
|
for r_id, min_p, max_p, curr_p in rules:
|
||||||
|
# Симулируем цену конкурента
|
||||||
|
comp_price = float(min_p) + random.uniform(-50, 150)
|
||||||
|
|
||||||
|
# Наша стратегия: на 1 рубль дешевле конкурента, но не ниже min_price
|
||||||
|
new_price = max(float(min_p), comp_price - 1)
|
||||||
|
new_price = min(new_price, float(max_p))
|
||||||
|
|
||||||
|
cur.execute("UPDATE repricer_rules SET current_price = %s, last_run = %s WHERE id = %s", (new_price, datetime.utcnow(), r_id))
|
||||||
|
updates.append({"id": r_id, "old": float(curr_p) if curr_p else 0, "new": round(new_price, 2), "competitor": round(comp_price, 2)})
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
release_db_connection(conn)
|
||||||
|
return jsonify({"updates": updates})
|
||||||
56
backend/routes/team.py
Normal file
56
backend/routes/team.py
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
from flask import Blueprint, request, jsonify
|
||||||
|
from ..db import get_db_connection, release_db_connection
|
||||||
|
from ..middleware import token_required
|
||||||
|
import bcrypt
|
||||||
|
|
||||||
|
team_blueprint = Blueprint('team', __name__)
|
||||||
|
|
||||||
|
@team_blueprint.route('/team/members', methods=['GET'])
|
||||||
|
@token_required
|
||||||
|
def list_team_members(user_info):
|
||||||
|
if user_info['role'] != 'admin':
|
||||||
|
return jsonify({"error": "Admin access required"}), 403
|
||||||
|
|
||||||
|
conn = get_db_connection()
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute("SELECT id, username, role, created_at FROM users WHERE parent_id = %s", (user_info['user_id'],))
|
||||||
|
rows = cur.fetchall()
|
||||||
|
release_db_connection(conn)
|
||||||
|
|
||||||
|
return jsonify([{
|
||||||
|
"id": r[0],
|
||||||
|
"username": r[1],
|
||||||
|
"role": r[2],
|
||||||
|
"created_at": r[3].isoformat()
|
||||||
|
} for r in rows])
|
||||||
|
|
||||||
|
@team_blueprint.route('/team/members', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
def add_team_member(user_info):
|
||||||
|
if user_info['role'] != 'admin':
|
||||||
|
return jsonify({"error": "Admin access required"}), 403
|
||||||
|
|
||||||
|
data = request.json
|
||||||
|
username = data.get('username')
|
||||||
|
password = data.get('password')
|
||||||
|
role = data.get('role', 'manager') # manager, viewer
|
||||||
|
|
||||||
|
if not username or not password:
|
||||||
|
return jsonify({"error": "Username and password required"}), 400
|
||||||
|
|
||||||
|
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
|
||||||
|
|
||||||
|
conn = get_db_connection()
|
||||||
|
cur = conn.cursor()
|
||||||
|
try:
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO users (username, password_hash, role, parent_id) VALUES (%s, %s, %s, %s) RETURNING id",
|
||||||
|
(username, hashed_password, role, user_info['user_id'])
|
||||||
|
)
|
||||||
|
new_id = cur.fetchone()[0]
|
||||||
|
conn.commit()
|
||||||
|
return jsonify({"id": new_id, "message": "Team member added"}), 201
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({"error": "User already exists"}), 400
|
||||||
|
finally:
|
||||||
|
release_db_connection(conn)
|
||||||
@@ -95,3 +95,38 @@ def generate_product_card(title):
|
|||||||
return json.loads(clean_json)
|
return json.loads(clean_json)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"error": f"Ошибка при генерации карточки: {str(e)}"}
|
return {"error": f"Ошибка при генерации карточки: {str(e)}"}
|
||||||
|
|
||||||
|
def analyze_competitor(my_desc, comp_desc):
|
||||||
|
"""Сравнивает две карточки товара и выдает рекомендации."""
|
||||||
|
api_key = os.getenv('GEMINI_API_KEY')
|
||||||
|
if not api_key:
|
||||||
|
return {"error": "API ключ не настроен."}
|
||||||
|
|
||||||
|
genai.configure(api_key=api_key)
|
||||||
|
model = genai.GenerativeModel('gemini-1.5-flash')
|
||||||
|
|
||||||
|
prompt = f"""
|
||||||
|
Ты - старший аналитик по маркетплейсам. Твоя цель: найти способы "победить" карточку конкурента.
|
||||||
|
|
||||||
|
ОПИСАНИЕ МОЕГО ТОВАРА:
|
||||||
|
"{my_desc}"
|
||||||
|
|
||||||
|
ОПИСАНИЕ ТОВАРА КОНКУРЕНТА:
|
||||||
|
"{comp_desc}"
|
||||||
|
|
||||||
|
Твоя задача - провести анализ и выдать ответ в формате JSON:
|
||||||
|
1. "competitor_weakness": Список из 3-4 слабых мест конкурента (что он не упомянул, в чем он хуже).
|
||||||
|
2. "my_advantages": В чем мой товар объективно лучше или как это преподнести.
|
||||||
|
3. "strategy": Конкретные шаги, что изменить в моем описании или фото, чтобы забрать продажи у него.
|
||||||
|
4. "win_phrase": Один мощный рекламный слоган, который "бьет" в слабое место конкурента.
|
||||||
|
|
||||||
|
Ответ дай ТОЛЬКО в виде чистого JSON.
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = model.generate_content(prompt)
|
||||||
|
import json
|
||||||
|
clean_json = response.text.replace('```json', '').replace('```', '').strip()
|
||||||
|
return json.loads(clean_json)
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": f"Ошибка анализа: {str(e)}"}
|
||||||
|
|||||||
16
db/init.sql
16
db/init.sql
@@ -5,10 +5,26 @@ CREATE TABLE IF NOT EXISTS users (
|
|||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
username VARCHAR(50) UNIQUE NOT NULL,
|
username VARCHAR(50) UNIQUE NOT NULL,
|
||||||
password_hash TEXT NOT NULL,
|
password_hash TEXT NOT NULL,
|
||||||
|
role VARCHAR(20) DEFAULT 'admin', -- admin, manager, viewer
|
||||||
|
parent_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
plan VARCHAR(20) DEFAULT 'free',
|
plan VARCHAR(20) DEFAULT 'free',
|
||||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS repricer_rules (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
product_name VARCHAR(255) NOT NULL,
|
||||||
|
sku VARCHAR(100) NOT NULL,
|
||||||
|
min_price DECIMAL(10, 2) NOT NULL,
|
||||||
|
max_price DECIMAL(10, 2) NOT NULL,
|
||||||
|
strategy VARCHAR(20) DEFAULT 'follow_competitor', -- follow_competitor, match_lowest
|
||||||
|
is_active BOOLEAN DEFAULT TRUE,
|
||||||
|
current_price DECIMAL(10, 2),
|
||||||
|
last_run TIMESTAMP,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS credentials (
|
CREATE TABLE IF NOT EXISTS credentials (
|
||||||
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
platform VARCHAR(50),
|
platform VARCHAR(50),
|
||||||
|
|||||||
@@ -51,6 +51,8 @@
|
|||||||
<button class="tab-btn" data-target="content-section"><i data-lucide="image" class="icon-sm"></i> Контент</button>
|
<button class="tab-btn" data-target="content-section"><i data-lucide="image" class="icon-sm"></i> Контент</button>
|
||||||
<button class="tab-btn" data-target="finance-section"><i data-lucide="wallet" class="icon-sm"></i> Финансы</button>
|
<button class="tab-btn" data-target="finance-section"><i data-lucide="wallet" class="icon-sm"></i> Финансы</button>
|
||||||
<button class="tab-btn" data-target="generator-section"><i data-lucide="wand-2" class="icon-sm"></i> Генератор</button>
|
<button class="tab-btn" data-target="generator-section"><i data-lucide="wand-2" class="icon-sm"></i> Генератор</button>
|
||||||
|
<button class="tab-btn" data-target="analytics-section"><i data-lucide="search-code" class="icon-sm"></i> Deep Insight</button>
|
||||||
|
<button class="tab-btn" data-target="repricer-section"><i data-lucide="tags" class="icon-sm"></i> Репрайзер</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<main class="container">
|
<main class="container">
|
||||||
@@ -85,6 +87,8 @@
|
|||||||
<th>Магазин</th>
|
<th>Магазин</th>
|
||||||
<th>Площадка</th>
|
<th>Площадка</th>
|
||||||
<th>Статус API</th>
|
<th>Статус API</th>
|
||||||
|
<th>Остатки (шт)</th>
|
||||||
|
<th>Дней до OOS</th>
|
||||||
<th>Продажи (сегодня)</th>
|
<th>Продажи (сегодня)</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -355,6 +359,94 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<!-- Deep Insight Section -->
|
||||||
|
<section id="analytics-section" class="section hidden">
|
||||||
|
<h2>AI Анализ конкурентов (Deep Insight)</h2>
|
||||||
|
<div class="platforms-grid">
|
||||||
|
<div class="platform-card">
|
||||||
|
<h3>Сравнение товаров</h3>
|
||||||
|
<p style="color: var(--color-text-dim); font-size: 0.9rem; margin-bottom: 1rem;">
|
||||||
|
Вставьте описание вашего товара и описание конкурента, чтобы ИИ нашел способ его победить.
|
||||||
|
</p>
|
||||||
|
<div style="display: flex; flex-direction: column; gap: 1rem;">
|
||||||
|
<label>Мое описание<textarea id="my-desc-input" rows="4" placeholder="Ваше описание..."></textarea></label>
|
||||||
|
<label>Описание конкурента<textarea id="comp-desc-input" rows="4" placeholder="Описание конкурента..."></textarea></label>
|
||||||
|
<button class="btn-primary" id="ai-analyze-comp-btn">
|
||||||
|
<i data-lucide="zap" class="icon-sm"></i> Запустить Deep Insight
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="insight-result" class="platform-card hidden" style="grid-column: 2 / -1;">
|
||||||
|
<div style="background: rgba(var(--color-primary-rgb), 0.1); border-left: 4px solid var(--color-primary); padding: 1rem; margin-bottom: 1.5rem;">
|
||||||
|
<h4 style="color: var(--color-primary);">Мощный слоган (Win Phrase):</h4>
|
||||||
|
<p id="insight-win-phrase" style="font-style: italic; font-size: 1.1rem; margin-top: 0.5rem;"></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="platforms-grid" style="grid-template-columns: 1fr 1fr; gap: 1.5rem;">
|
||||||
|
<div>
|
||||||
|
<h4>Слабые места конкурента</h4>
|
||||||
|
<ul id="insight-weakness" style="margin-top: 0.5rem; color: var(--color-error); font-size: 0.9rem;"></ul>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h4>Твои преимущества</h4>
|
||||||
|
<ul id="insight-advantages" style="margin-top: 0.5rem; color: var(--color-success); font-size: 0.9rem;"></ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h4 style="margin-top: 1.5rem;">Стратегия захвата рынка</h4>
|
||||||
|
<p id="insight-strategy" style="margin-top: 0.5rem; line-height: 1.6; color: var(--color-text-dim);"></p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Repricer Section -->
|
||||||
|
<section id="repricer-section" class="section hidden">
|
||||||
|
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
|
||||||
|
<h2>Авто-репрайзер (Динамические цены)</h2>
|
||||||
|
<button class="btn-primary" id="run-repricer-btn">
|
||||||
|
<i data-lucide="refresh-cw" class="icon-sm"></i> Обновить цены сейчас
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="platforms-grid">
|
||||||
|
<div class="platform-card" style="grid-column: 1 / 1;">
|
||||||
|
<h3>Новое правило</h3>
|
||||||
|
<form id="repricer-form" class="platform-form" style="margin-top: 1rem; display: flex; flex-direction: column; gap: 0.8rem;">
|
||||||
|
<label>Товар<input type="text" name="product_name" placeholder="Название товара" required></label>
|
||||||
|
<label>SKU / Артикул<input type="text" name="sku" placeholder="Артикул" required></label>
|
||||||
|
<div style="display: flex; gap: 1rem;">
|
||||||
|
<label style="flex: 1;">Мин. цена (₽)<input type="number" name="min_price" required></label>
|
||||||
|
<label style="flex: 1;">Макс. цена (₽)<input type="number" name="max_price" required></label>
|
||||||
|
</div>
|
||||||
|
<label>Стратегия
|
||||||
|
<select name="strategy">
|
||||||
|
<option value="follow_competitor">На 1₽ дешевле конкурента</option>
|
||||||
|
<option value="match_lowest">Равняться на минимальную</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<button type="submit" class="btn-primary">Добавить правило</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="platform-card" style="grid-column: 2 / -1;">
|
||||||
|
<h3>Активные правила</h3>
|
||||||
|
<table id="repricer-table" class="table" style="margin-top: 1rem;">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Товар</th>
|
||||||
|
<th>Мин / Макс</th>
|
||||||
|
<th>Тек. цена</th>
|
||||||
|
<th>Последнее обновление</th>
|
||||||
|
<th>Статус</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<!-- Integrations List -->
|
<!-- Integrations List -->
|
||||||
<section id="integrations-section" class="section hidden">
|
<section id="integrations-section" class="section hidden">
|
||||||
<h2>Доступные маркетплейсы</h2>
|
<h2>Доступные маркетплейсы</h2>
|
||||||
|
|||||||
@@ -161,10 +161,13 @@ async function loadDashboard() {
|
|||||||
storesTbody.innerHTML = '';
|
storesTbody.innerHTML = '';
|
||||||
(data.stores || []).forEach(s => {
|
(data.stores || []).forEach(s => {
|
||||||
const tr = document.createElement('tr');
|
const tr = document.createElement('tr');
|
||||||
|
const oosClass = s.days_left < 7 ? 'color: var(--color-error); font-weight: bold;' : '';
|
||||||
tr.innerHTML = `
|
tr.innerHTML = `
|
||||||
<td><strong>${s.name}</strong></td>
|
<td><strong>${s.name}</strong></td>
|
||||||
<td><span style="text-transform: uppercase;">${s.platform}</span></td>
|
<td><span style="text-transform: uppercase;">${s.platform}</span></td>
|
||||||
<td><span class="status-pill status-closed" style="background: rgba(16, 185, 129, 0.1); color: #34d399;">● Online</span></td>
|
<td><span class="status-pill status-closed" style="background: rgba(16, 185, 129, 0.1); color: #34d399;">● Online</span></td>
|
||||||
|
<td>${s.stock}</td>
|
||||||
|
<td style="${oosClass}">${s.days_left} дн.</td>
|
||||||
<td>${(s.daily_sales || 0).toLocaleString()} ₽</td>
|
<td>${(s.daily_sales || 0).toLocaleString()} ₽</td>
|
||||||
`;
|
`;
|
||||||
storesTbody.appendChild(tr);
|
storesTbody.appendChild(tr);
|
||||||
@@ -273,10 +276,146 @@ function initTabs() {
|
|||||||
if(target === 'content-section') loadReferences();
|
if(target === 'content-section') loadReferences();
|
||||||
if(target === 'finance-section') { /* No initial load */ }
|
if(target === 'finance-section') { /* No initial load */ }
|
||||||
if(target === 'generator-section') { /* No initial load */ }
|
if(target === 'generator-section') { /* No initial load */ }
|
||||||
|
if(target === 'analytics-section') { /* No initial load */ }
|
||||||
|
if(target === 'repricer-section') loadRepricerRules();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function loadRepricerRules() {
|
||||||
|
const table = document.getElementById('repricer-table').querySelector('tbody');
|
||||||
|
try {
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
const res = await fetch('http://localhost:5000/api/repricer/rules', {
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
const rules = await res.json();
|
||||||
|
|
||||||
|
table.innerHTML = '';
|
||||||
|
rules.forEach(r => {
|
||||||
|
const tr = document.createElement('tr');
|
||||||
|
tr.innerHTML = `
|
||||||
|
<td><strong>${r.product_name}</strong><br><small>${r.sku}</small></td>
|
||||||
|
<td>${r.min_price} - ${r.max_price} ₽</td>
|
||||||
|
<td><span style="font-weight: bold; color: var(--color-primary);">${r.current_price ? r.current_price + ' ₽' : '—'}</span></td>
|
||||||
|
<td>${r.last_run ? new Date(r.last_run).toLocaleString() : 'Никогда'}</td>
|
||||||
|
<td><span class="status-pill status-${r.is_active ? 'closed' : 'open'}">${r.is_active ? 'Активно' : 'Пауза'}</span></td>
|
||||||
|
`;
|
||||||
|
table.appendChild(tr);
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error loading repricer rules:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('repricer-form').addEventListener('submit', async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const fd = new FormData(e.target);
|
||||||
|
const data = Object.fromEntries(fd.entries());
|
||||||
|
data.is_active = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
await fetch('http://localhost:5000/api/repricer/rules', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${token}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify(data)
|
||||||
|
});
|
||||||
|
showToast('Правило сохранено', 'success');
|
||||||
|
loadRepricerRules();
|
||||||
|
e.target.reset();
|
||||||
|
} catch (err) {
|
||||||
|
alert('Ошибка сохранения');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('run-repricer-btn').addEventListener('click', async () => {
|
||||||
|
const btn = document.getElementById('run-repricer-btn');
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.innerHTML = '<i data-lucide="loader-2" class="icon-sm spin"></i> Обновляю...';
|
||||||
|
if (window.lucide) lucide.createIcons();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
const res = await fetch('http://localhost:5000/api/repricer/run', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
showToast(`Обновлено ${data.updates.length} цен`, 'success');
|
||||||
|
loadRepricerRules();
|
||||||
|
} catch (err) {
|
||||||
|
alert('Ошибка при запуске репрайзера');
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.innerHTML = '<i data-lucide="refresh-cw" class="icon-sm"></i> Обновить цены сейчас';
|
||||||
|
if (window.lucide) lucide.createIcons();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('ai-analyze-comp-btn').addEventListener('click', async () => {
|
||||||
|
const myDesc = document.getElementById('my-desc-input').value;
|
||||||
|
const compDesc = document.getElementById('comp-desc-input').value;
|
||||||
|
|
||||||
|
if (!compDesc) {
|
||||||
|
alert('Введите описание конкурента');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const btn = document.getElementById('ai-analyze-comp-btn');
|
||||||
|
const originalHTML = btn.innerHTML;
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.innerHTML = '<i data-lucide="loader-2" class="icon-sm spin"></i> Анализирую рынок...';
|
||||||
|
if (window.lucide) lucide.createIcons();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
const res = await fetch('http://localhost:5000/api/ai/analyze-competitor', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${token}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ my_desc: myDesc, comp_desc: compDesc })
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
|
||||||
|
document.getElementById('insight-result').classList.remove('hidden');
|
||||||
|
document.getElementById('insight-win-phrase').innerText = data.win_phrase;
|
||||||
|
document.getElementById('insight-strategy').innerText = data.strategy;
|
||||||
|
|
||||||
|
const wList = document.getElementById('insight-weakness');
|
||||||
|
wList.innerHTML = '';
|
||||||
|
data.competitor_weakness.forEach(w => {
|
||||||
|
const li = document.createElement('li');
|
||||||
|
li.innerText = w;
|
||||||
|
wList.appendChild(li);
|
||||||
|
});
|
||||||
|
|
||||||
|
const aList = document.getElementById('insight-advantages');
|
||||||
|
aList.innerHTML = '';
|
||||||
|
data.my_advantages.forEach(a => {
|
||||||
|
const li = document.createElement('li');
|
||||||
|
li.innerText = a;
|
||||||
|
aList.appendChild(li);
|
||||||
|
});
|
||||||
|
|
||||||
|
showToast('Анализ Deep Insight завершен!', 'success');
|
||||||
|
} catch (err) {
|
||||||
|
alert(err.message);
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.innerHTML = originalHTML;
|
||||||
|
if (window.lucide) lucide.createIcons();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
document.getElementById('ai-gen-card-btn').addEventListener('click', async () => {
|
document.getElementById('ai-gen-card-btn').addEventListener('click', async () => {
|
||||||
const title = document.getElementById('gen-title-input').value;
|
const title = document.getElementById('gen-title-input').value;
|
||||||
if (!title) {
|
if (!title) {
|
||||||
|
|||||||
Reference in New Issue
Block a user