feat: implement backend core with repricing logic, case management, and multi-service architecture
This commit is contained in:
@@ -45,6 +45,8 @@ from .routes.ai import ai_blueprint
|
||||
from .routes.seo import seo_blueprint
|
||||
from .routes.content import content_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(credentials_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(content_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 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:
|
||||
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:
|
||||
return jsonify({'message': 'Token is invalid or expired!'}), 401
|
||||
|
||||
return f(current_user_id, *args, **kwargs)
|
||||
return f(user_info, *args, **kwargs)
|
||||
return decorated
|
||||
|
||||
@@ -13,3 +13,4 @@ flask-socketio==5.3.6
|
||||
google-generativeai==0.5.2
|
||||
ImageHash==4.3.1
|
||||
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
|
||||
card_data = generate_product_card(title)
|
||||
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')):
|
||||
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({
|
||||
'user_id': user[0],
|
||||
'user_id': user_id,
|
||||
'company_id': company_id,
|
||||
'role': role,
|
||||
'exp': datetime.utcnow() + timedelta(days=7)
|
||||
}, SECRET_KEY, algorithm="HS256")
|
||||
|
||||
|
||||
@@ -26,7 +26,9 @@ def serialize_case(row):
|
||||
# ---------- CASE CRUD ----------
|
||||
@cases_blueprint.route('/cases', methods=['GET'])
|
||||
@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'])
|
||||
@token_required
|
||||
def get_stats(current_user_id):
|
||||
"""
|
||||
Получить общую статистику для дашборда
|
||||
---
|
||||
tags:
|
||||
- Dashboard
|
||||
security:
|
||||
- APIKeyHeader: []
|
||||
responses:
|
||||
200:
|
||||
description: Объект со статистикой и трендами
|
||||
"""
|
||||
def get_stats(user_info):
|
||||
company_id = user_info['company_id']
|
||||
conn = get_db_connection()
|
||||
cur = conn.cursor()
|
||||
|
||||
# 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]
|
||||
|
||||
# 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()
|
||||
cases_by_status = {row[0]: row[1] for row in status_rows}
|
||||
|
||||
# 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]
|
||||
|
||||
# 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()]
|
||||
|
||||
# 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_activity = [
|
||||
{
|
||||
@@ -56,7 +46,7 @@ def get_stats(current_user_id):
|
||||
trend = []
|
||||
for i in range(6, -1, -1):
|
||||
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]
|
||||
trend.append({
|
||||
"date": day.strftime('%d.%m'),
|
||||
@@ -64,23 +54,30 @@ def get_stats(current_user_id):
|
||||
})
|
||||
|
||||
# 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 = []
|
||||
total_sales = 0
|
||||
|
||||
for s in stores_rows:
|
||||
# В реальной жизни здесь был бы вызов API Ozon/WB для получения продаж за сегодня
|
||||
# Для демонстрации генерируем случайные данные
|
||||
import random
|
||||
daily_sales = random.randint(5000, 50000)
|
||||
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({
|
||||
"id": s[0],
|
||||
"platform": s[1],
|
||||
"name": s[2],
|
||||
"status": "active",
|
||||
"daily_sales": daily_sales
|
||||
"daily_sales": daily_sales,
|
||||
"stock": current_stock,
|
||||
"velocity": sales_velocity,
|
||||
"days_left": days_left
|
||||
})
|
||||
|
||||
release_db_connection(conn)
|
||||
@@ -98,21 +95,11 @@ def get_stats(current_user_id):
|
||||
|
||||
@dashboard_blueprint.route('/dashboard/logs', methods=['GET'])
|
||||
@token_required
|
||||
def get_logs(current_user_id):
|
||||
"""
|
||||
Получить лог аудита действий пользователя
|
||||
---
|
||||
tags:
|
||||
- Dashboard
|
||||
security:
|
||||
- APIKeyHeader: []
|
||||
responses:
|
||||
200:
|
||||
description: Список действий из лога
|
||||
"""
|
||||
def get_logs(user_info):
|
||||
company_id = user_info['company_id']
|
||||
conn = get_db_connection()
|
||||
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()
|
||||
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)
|
||||
except Exception as 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)}"}
|
||||
|
||||
Reference in New Issue
Block a user