feat: implement backend core with repricing logic, case management, and multi-service architecture
This commit is contained in:
@@ -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)
|
||||
Reference in New Issue
Block a user