Spaces:
Running

MicroFunnel commited on
Commit
c997c51
·
1 Parent(s): 07214a2

feat: Админ-панель для управления клиентами и тарифами

Browse files

BACKEND:
- Создан admin API (/api/v1/admin) с защитой superuser
- Endpoints: list tenants, update subscription, activate/suspend
- Статистика: MRR, клиенты по планам и статусам
- Новые планы: trial (7 дней), start (), growth (), unlimited ()
- Обновлена модель Tenant с новыми планами

FRONTEND:
- Админ-панель (/admin) с полным управлением клиентами
- Фильтры по плану, статусу, поиск по имени/email
- Карточки статистики: всего клиентов, активных, на trial, MRR
- Модальное окно редактирования подписки
- Активация/приостановка клиентов одной кнопкой
- Визуальные бейджи для планов и статусов

ТАРИФЫ:
- Trial: 7 дней бесплатно
- Start: /мес - 300 диалогов, 1 канал
- Growth: /мес - 1000 диалогов, 2 канала
- Unlimited: /мес - безлимит

ДОСТУП:
- Только для пользователей с is_superuser=True
- Защита на уровне API и UI

backend/app/api/admin.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Admin Panel API - User and Subscription Management
3
+
4
+ Only accessible by superuser (is_superuser=True)
5
+ """
6
+
7
+ from fastapi import APIRouter, Depends, HTTPException, status, Query
8
+ from sqlmodel import select
9
+ from sqlalchemy.ext.asyncio import AsyncSession
10
+ from typing import List, Optional
11
+ from datetime import datetime, timedelta
12
+ from uuid import UUID
13
+
14
+ from app.core.database import get_async_session
15
+ from app.core.auth import get_current_user
16
+ from app.models.user import User
17
+ from app.models.tenant import Tenant, SubscriptionPlan, SubscriptionStatus
18
+ from pydantic import BaseModel
19
+
20
+ router = APIRouter(prefix="/admin", tags=["admin"])
21
+
22
+
23
+ # ==================== REQUEST/RESPONSE MODELS ====================
24
+
25
+ class TenantListItem(BaseModel):
26
+ """Tenant in admin list."""
27
+ id: str
28
+ name: str
29
+ business_name: str
30
+ email: str # Owner email
31
+ subscription_plan: str
32
+ subscription_status: str
33
+ subscription_end: Optional[str]
34
+ leads_this_month: int
35
+ created_at: str
36
+ is_active: bool
37
+
38
+
39
+ class SubscriptionUpdateRequest(BaseModel):
40
+ """Admin request to update subscription."""
41
+ plan: str # trial, start, growth, unlimited
42
+ status: str # trial, active, expired, cancelled, suspended
43
+ days_to_add: Optional[int] = 30 # Days to extend
44
+
45
+
46
+ class SubscriptionUpdateResponse(BaseModel):
47
+ """Response after updating subscription."""
48
+ success: bool
49
+ message: str
50
+ tenant_id: str
51
+ new_plan: str
52
+ new_status: str
53
+ subscription_end: Optional[str]
54
+
55
+
56
+ # ==================== DEPENDENCY: REQUIRE SUPERUSER ====================
57
+
58
+ async def require_superuser(current_user: User = Depends(get_current_user)) -> User:
59
+ """Verify current user is superuser."""
60
+ if not current_user.is_superuser:
61
+ raise HTTPException(
62
+ status_code=status.HTTP_403_FORBIDDEN,
63
+ detail="Требуется доступ суперпользователя"
64
+ )
65
+ return current_user
66
+
67
+
68
+ # ==================== ENDPOINTS ====================
69
+
70
+ @router.get("/tenants", response_model=List[TenantListItem])
71
+ async def list_all_tenants(
72
+ search: Optional[str] = Query(None, description="Search by name or email"),
73
+ plan: Optional[str] = Query(None, description="Filter by plan"),
74
+ status_filter: Optional[str] = Query(None, description="Filter by status"),
75
+ admin_user: User = Depends(require_superuser),
76
+ session: AsyncSession = Depends(get_async_session)
77
+ ):
78
+ """
79
+ Get all tenants (admin only).
80
+
81
+ Query filters:
82
+ - search: Search by tenant name or owner email
83
+ - plan: Filter by subscription_plan (trial, start, growth, unlimited)
84
+ - status: Filter by subscription_status (trial, active, expired, etc.)
85
+ """
86
+
87
+ # Build query
88
+ stmt = select(Tenant, User).join(User, Tenant.id == User.tenant_id).where(User.role == "OWNER")
89
+
90
+ # Apply filters
91
+ if search:
92
+ search_pattern = f"%{search}%"
93
+ stmt = stmt.where(
94
+ (Tenant.name.ilike(search_pattern)) |
95
+ (Tenant.business_name.ilike(search_pattern)) |
96
+ (User.email.ilike(search_pattern))
97
+ )
98
+
99
+ if plan:
100
+ stmt = stmt.where(Tenant.subscription_plan == plan)
101
+
102
+ if status_filter:
103
+ stmt = stmt.where(Tenant.subscription_status == status_filter)
104
+
105
+ # Order by newest first
106
+ stmt = stmt.order_by(Tenant.created_at.desc())
107
+
108
+ result = await session.execute(stmt)
109
+ rows = result.all()
110
+
111
+ # Format response
112
+ tenants_list = []
113
+ for tenant, user in rows:
114
+ tenants_list.append(TenantListItem(
115
+ id=str(tenant.id),
116
+ name=tenant.name,
117
+ business_name=tenant.business_name,
118
+ email=user.email,
119
+ subscription_plan=tenant.subscription_plan,
120
+ subscription_status=tenant.subscription_status,
121
+ subscription_end=tenant.subscription_end.isoformat() if tenant.subscription_end else None,
122
+ leads_this_month=tenant.leads_this_month,
123
+ created_at=tenant.created_at.isoformat(),
124
+ is_active=tenant.is_active
125
+ ))
126
+
127
+ return tenants_list
128
+
129
+
130
+ @router.post("/tenants/{tenant_id}/subscription", response_model=SubscriptionUpdateResponse)
131
+ async def update_tenant_subscription(
132
+ tenant_id: UUID,
133
+ request: SubscriptionUpdateRequest,
134
+ admin_user: User = Depends(require_superuser),
135
+ session: AsyncSession = Depends(get_async_session)
136
+ ):
137
+ """
138
+ Update tenant subscription (admin only).
139
+
140
+ Plans:
141
+ - trial: 7 дней бесплатно
142
+ - start: $99/month - 300 диалогов, 1 канал
143
+ - growth: $199/month - 1000 диалогов, 2 канала
144
+ - unlimited: $500/month - безлимит
145
+
146
+ Statuses:
147
+ - trial: Пробный период
148
+ - active: Активная подписка
149
+ - expired: Истекла
150
+ - cancelled: Отменена пользователем
151
+ - suspended: Приостановлена админом
152
+ """
153
+
154
+ # Validate plan
155
+ valid_plans = ["trial", "start", "growth", "unlimited"]
156
+ if request.plan.lower() not in valid_plans:
157
+ raise HTTPException(
158
+ status_code=status.HTTP_400_BAD_REQUEST,
159
+ detail=f"Неверный план. Доступные: {', '.join(valid_plans)}"
160
+ )
161
+
162
+ # Validate status
163
+ valid_statuses = ["trial", "active", "expired", "cancelled", "suspended"]
164
+ if request.status.lower() not in valid_statuses:
165
+ raise HTTPException(
166
+ status_code=status.HTTP_400_BAD_REQUEST,
167
+ detail=f"Неверный статус. Доступные: {', '.join(valid_statuses)}"
168
+ )
169
+
170
+ # Get tenant
171
+ stmt = select(Tenant).where(Tenant.id == tenant_id)
172
+ result = await session.execute(stmt)
173
+ tenant = result.scalar_one_or_none()
174
+
175
+ if not tenant:
176
+ raise HTTPException(
177
+ status_code=status.HTTP_404_NOT_FOUND,
178
+ detail="Tenant не найден"
179
+ )
180
+
181
+ # Update subscription
182
+ tenant.subscription_plan = request.plan.lower()
183
+ tenant.subscription_status = request.status.lower()
184
+
185
+ # Extend subscription end date
186
+ if request.days_to_add and request.days_to_add > 0:
187
+ if tenant.subscription_end and tenant.subscription_end > datetime.utcnow():
188
+ # Extend from current end date
189
+ tenant.subscription_end = tenant.subscription_end + timedelta(days=request.days_to_add)
190
+ else:
191
+ # Start from now
192
+ tenant.subscription_end = datetime.utcnow() + timedelta(days=request.days_to_add)
193
+
194
+ # Update billing dates
195
+ tenant.last_billing_date = datetime.utcnow()
196
+ if tenant.subscription_end:
197
+ tenant.next_billing_date = tenant.subscription_end
198
+
199
+ tenant.updated_at = datetime.utcnow()
200
+
201
+ session.add(tenant)
202
+ await session.commit()
203
+ await session.refresh(tenant)
204
+
205
+ return SubscriptionUpdateResponse(
206
+ success=True,
207
+ message=f"Подписка обновлена: {request.plan.upper()} ({request.status.upper()})",
208
+ tenant_id=str(tenant.id),
209
+ new_plan=tenant.subscription_plan,
210
+ new_status=tenant.subscription_status,
211
+ subscription_end=tenant.subscription_end.isoformat() if tenant.subscription_end else None
212
+ )
213
+
214
+
215
+ @router.post("/tenants/{tenant_id}/activate")
216
+ async def activate_tenant(
217
+ tenant_id: UUID,
218
+ admin_user: User = Depends(require_superuser),
219
+ session: AsyncSession = Depends(get_async_session)
220
+ ):
221
+ """Активировать tenant (is_active=True)."""
222
+
223
+ stmt = select(Tenant).where(Tenant.id == tenant_id)
224
+ result = await session.execute(stmt)
225
+ tenant = result.scalar_one_or_none()
226
+
227
+ if not tenant:
228
+ raise HTTPException(status_code=404, detail="Tenant не найден")
229
+
230
+ tenant.is_active = True
231
+ tenant.updated_at = datetime.utcnow()
232
+
233
+ session.add(tenant)
234
+ await session.commit()
235
+
236
+ return {"success": True, "message": f"Tenant {tenant.name} активирован"}
237
+
238
+
239
+ @router.post("/tenants/{tenant_id}/suspend")
240
+ async def suspend_tenant(
241
+ tenant_id: UUID,
242
+ admin_user: User = Depends(require_superuser),
243
+ session: AsyncSession = Depends(get_async_session)
244
+ ):
245
+ """Приостановить tenant (is_active=False, status=suspended)."""
246
+
247
+ stmt = select(Tenant).where(Tenant.id == tenant_id)
248
+ result = await session.execute(stmt)
249
+ tenant = result.scalar_one_or_none()
250
+
251
+ if not tenant:
252
+ raise HTTPException(status_code=404, detail="Tenant не найден")
253
+
254
+ tenant.is_active = False
255
+ tenant.subscription_status = "suspended"
256
+ tenant.updated_at = datetime.utcnow()
257
+
258
+ session.add(tenant)
259
+ await session.commit()
260
+
261
+ return {"success": True, "message": f"Tenant {tenant.name} приостановлен"}
262
+
263
+
264
+ @router.get("/stats")
265
+ async def get_admin_stats(
266
+ admin_user: User = Depends(require_superuser),
267
+ session: AsyncSession = Depends(get_async_session)
268
+ ):
269
+ """Статистика платформы для админа."""
270
+
271
+ # Total tenants
272
+ stmt = select(Tenant)
273
+ result = await session.execute(stmt)
274
+ all_tenants = result.scalars().all()
275
+
276
+ # Count by status
277
+ trial_count = len([t for t in all_tenants if t.subscription_status == "trial"])
278
+ active_count = len([t for t in all_tenants if t.subscription_status == "active"])
279
+ expired_count = len([t for t in all_tenants if t.subscription_status == "expired"])
280
+ cancelled_count = len([t for t in all_tenants if t.subscription_status == "cancelled"])
281
+
282
+ # Count by plan
283
+ start_count = len([t for t in all_tenants if t.subscription_plan == "start"])
284
+ growth_count = len([t for t in all_tenants if t.subscription_plan == "growth"])
285
+ unlimited_count = len([t for t in all_tenants if t.subscription_plan == "unlimited"])
286
+
287
+ # Revenue calculation (mock)
288
+ monthly_revenue = (start_count * 99) + (growth_count * 199) + (unlimited_count * 500)
289
+
290
+ return {
291
+ "total_tenants": len(all_tenants),
292
+ "by_status": {
293
+ "trial": trial_count,
294
+ "active": active_count,
295
+ "expired": expired_count,
296
+ "cancelled": cancelled_count
297
+ },
298
+ "by_plan": {
299
+ "start": start_count,
300
+ "growth": growth_count,
301
+ "unlimited": unlimited_count
302
+ },
303
+ "estimated_mrr": monthly_revenue
304
+ }
backend/app/main.py CHANGED
@@ -7,7 +7,7 @@ from app.core.config import settings
7
  from app.core.database import init_pgvector
8
  from app.core.logging import configure_logging, get_logger
9
  from app.middleware.request_id import RequestIDMiddleware
10
- from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, meta_webhooks, billing, ai_training, crm
11
  import asyncio
12
  import sys
13
  from slowapi import Limiter, _rate_limit_exceeded_handler
@@ -171,6 +171,7 @@ app.include_router(playbook.router, prefix="/api/v1")
171
  app.include_router(billing.router, prefix="/api/v1") # Billing & Franchise
172
  app.include_router(ai_training.router, prefix="/api/v1") # AI Training & Learning
173
  app.include_router(crm.router, prefix="/api/v1") # CRM Integration
 
174
 
175
 
176
  @app.on_event("startup")
 
7
  from app.core.database import init_pgvector
8
  from app.core.logging import configure_logging, get_logger
9
  from app.middleware.request_id import RequestIDMiddleware
10
+ from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, meta_webhooks, billing, ai_training, crm, admin
11
  import asyncio
12
  import sys
13
  from slowapi import Limiter, _rate_limit_exceeded_handler
 
171
  app.include_router(billing.router, prefix="/api/v1") # Billing & Franchise
172
  app.include_router(ai_training.router, prefix="/api/v1") # AI Training & Learning
173
  app.include_router(crm.router, prefix="/api/v1") # CRM Integration
174
+ app.include_router(admin.router, prefix="/api/v1") # Admin Panel (superuser only)
175
 
176
 
177
  @app.on_event("startup")
backend/app/models/tenant.py CHANGED
@@ -8,10 +8,10 @@ from sqlalchemy import JSON
8
 
9
  class SubscriptionPlan(str, Enum):
10
  """Subscription plan types."""
11
- FREE = "free"
12
- START = "start"
13
- GROWTH = "growth"
14
- SCALE = "scale"
15
 
16
 
17
  class SubscriptionStatus(str, Enum):
 
8
 
9
  class SubscriptionPlan(str, Enum):
10
  """Subscription plan types."""
11
+ TRIAL = "trial" # 7 days free trial
12
+ START = "start" # $99/month - 300 conversations, 1 channel
13
+ GROWTH = "growth" # $199/month - 1000 conversations, 2 channels
14
+ UNLIMITED = "unlimited" # $500/month - unlimited everything
15
 
16
 
17
  class SubscriptionStatus(str, Enum):
frontend/app/admin/page.tsx ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use client'
2
+
3
+ import { useState, useEffect } from 'react'
4
+ import { useAuth } from '@/contexts/AuthContext'
5
+ import { useToast } from '@/contexts/ToastContext'
6
+ import {
7
+ Shield,
8
+ Users,
9
+ DollarSign,
10
+ TrendingUp,
11
+ Search,
12
+ Filter,
13
+ Edit,
14
+ Check,
15
+ X,
16
+ Activity,
17
+ AlertCircle,
18
+ Crown,
19
+ Zap,
20
+ Rocket,
21
+ Ban,
22
+ Play
23
+ } from 'lucide-react'
24
+
25
+ interface Tenant {
26
+ id: string
27
+ name: string
28
+ business_name: string
29
+ email: string
30
+ subscription_plan: string
31
+ subscription_status: string
32
+ subscription_end: string | null
33
+ leads_this_month: number
34
+ created_at: string
35
+ is_active: boolean
36
+ }
37
+
38
+ interface Stats {
39
+ total_tenants: number
40
+ by_status: {
41
+ trial: number
42
+ active: number
43
+ expired: number
44
+ cancelled: number
45
+ }
46
+ by_plan: {
47
+ start: number
48
+ growth: number
49
+ unlimited: number
50
+ }
51
+ estimated_mrr: number
52
+ }
53
+
54
+ export default function AdminPanelPage() {
55
+ const { user } = useAuth()
56
+ const toast = useToast()
57
+ const [tenants, setTenants] = useState<Tenant[]>([])
58
+ const [stats, setStats] = useState<Stats | null>(null)
59
+ const [loading, setLoading] = useState(true)
60
+ const [searchQuery, setSearchQuery] = useState('')
61
+ const [filterPlan, setFilterPlan] = useState('')
62
+ const [filterStatus, setFilterStatus] = useState('')
63
+ const [selectedTenant, setSelectedTenant] = useState<Tenant | null>(null)
64
+ const [showEditModal, setShowEditModal] = useState(false)
65
+
66
+ // Edit form state
67
+ const [editPlan, setEditPlan] = useState('')
68
+ const [editStatus, setEditStatus] = useState('')
69
+ const [daysToAdd, setDaysToAdd] = useState(30)
70
+ const [updating, setUpdating] = useState(false)
71
+
72
+ useEffect(() => {
73
+ if (user && !user.is_superuser) {
74
+ toast.error('Доступ запрещён', 'Требуются права администратора')
75
+ return
76
+ }
77
+
78
+ loadData()
79
+ }, [user])
80
+
81
+ const loadData = async () => {
82
+ try {
83
+ const params = new URLSearchParams()
84
+ if (searchQuery) params.append('search', searchQuery)
85
+ if (filterPlan) params.append('plan', filterPlan)
86
+ if (filterStatus) params.append('status_filter', filterStatus)
87
+
88
+ const [tenantsRes, statsRes] = await Promise.all([
89
+ fetch(`/api/v1/admin/tenants?${params.toString()}`, {
90
+ headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }
91
+ }),
92
+ fetch('/api/v1/admin/stats', {
93
+ headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }
94
+ })
95
+ ])
96
+
97
+ if (tenantsRes.ok) {
98
+ const tenantsData = await tenantsRes.json()
99
+ setTenants(tenantsData)
100
+ }
101
+
102
+ if (statsRes.ok) {
103
+ const statsData = await statsRes.json()
104
+ setStats(statsData)
105
+ }
106
+ } catch (error) {
107
+ console.error('Error loading admin data:', error)
108
+ toast.error('Ошибка', 'Не удалось загрузить данные')
109
+ } finally {
110
+ setLoading(false)
111
+ }
112
+ }
113
+
114
+ const handleUpdateSubscription = async () => {
115
+ if (!selectedTenant) return
116
+
117
+ setUpdating(true)
118
+ try {
119
+ const response = await fetch(`/api/v1/admin/tenants/${selectedTenant.id}/subscription`, {
120
+ method: 'POST',
121
+ headers: {
122
+ 'Content-Type': 'application/json',
123
+ 'Authorization': `Bearer ${localStorage.getItem('access_token')}`
124
+ },
125
+ body: JSON.stringify({
126
+ plan: editPlan,
127
+ status: editStatus,
128
+ days_to_add: daysToAdd
129
+ })
130
+ })
131
+
132
+ if (response.ok) {
133
+ const data = await response.json()
134
+ toast.success('Успех!', data.message)
135
+ setShowEditModal(false)
136
+ loadData()
137
+ } else {
138
+ const error = await response.json()
139
+ toast.error('Ошибка', error.detail || 'Не удалось обновить подписку')
140
+ }
141
+ } catch (error) {
142
+ toast.error('Ошибка', 'Ошибка подключения к серверу')
143
+ } finally {
144
+ setUpdating(false)
145
+ }
146
+ }
147
+
148
+ const handleSuspend = async (tenantId: string) => {
149
+ try {
150
+ const response = await fetch(`/api/v1/admin/tenants/${tenantId}/suspend`, {
151
+ method: 'POST',
152
+ headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }
153
+ })
154
+
155
+ if (response.ok) {
156
+ toast.success('Успех!', 'Клиент приостановлен')
157
+ loadData()
158
+ } else {
159
+ toast.error('Ошибка', 'Не удалось приостановить')
160
+ }
161
+ } catch (error) {
162
+ toast.error('Ошибка', 'Ошибка подключения к серверу')
163
+ }
164
+ }
165
+
166
+ const handleActivate = async (tenantId: string) => {
167
+ try {
168
+ const response = await fetch(`/api/v1/admin/tenants/${tenantId}/activate`, {
169
+ method: 'POST',
170
+ headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }
171
+ })
172
+
173
+ if (response.ok) {
174
+ toast.success('Успех!', 'К��иент активирован')
175
+ loadData()
176
+ } else {
177
+ toast.error('Ошибка', 'Не удалось активировать')
178
+ }
179
+ } catch (error) {
180
+ toast.error('Ошибка', 'Ошибка подключения к серверу')
181
+ }
182
+ }
183
+
184
+ const openEditModal = (tenant: Tenant) => {
185
+ setSelectedTenant(tenant)
186
+ setEditPlan(tenant.subscription_plan)
187
+ setEditStatus(tenant.subscription_status)
188
+ setDaysToAdd(30)
189
+ setShowEditModal(true)
190
+ }
191
+
192
+ const getPlanBadge = (plan: string) => {
193
+ const badges: Record<string, { icon: any; color: string; label: string }> = {
194
+ trial: { icon: Zap, color: 'bg-slate-100 text-slate-700 border-slate-200', label: 'TRIAL' },
195
+ start: { icon: Rocket, color: 'bg-blue-100 text-blue-700 border-blue-200', label: 'START $99' },
196
+ growth: { icon: TrendingUp, color: 'bg-indigo-100 text-indigo-700 border-indigo-200', label: 'GROWTH $199' },
197
+ unlimited: { icon: Crown, color: 'bg-purple-100 text-purple-700 border-purple-200', label: 'UNLIMITED $500' }
198
+ }
199
+ const badge = badges[plan] || badges.trial
200
+ const Icon = badge.icon
201
+ return (
202
+ <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold border-2 ${badge.color}`}>
203
+ <Icon className="w-4 h-4" />
204
+ {badge.label}
205
+ </span>
206
+ )
207
+ }
208
+
209
+ const getStatusBadge = (status: string) => {
210
+ const badges: Record<string, { color: string; label: string }> = {
211
+ trial: { color: 'bg-amber-100 text-amber-800', label: 'ПРОБНЫЙ' },
212
+ active: { color: 'bg-emerald-100 text-emerald-800', label: 'АКТИВЕН' },
213
+ expired: { color: 'bg-red-100 text-red-800', label: 'ИСТЁК' },
214
+ cancelled: { color: 'bg-slate-100 text-slate-800', label: 'ОТМЕНЁН' },
215
+ suspended: { color: 'bg-orange-100 text-orange-800', label: 'ПРИОСТАНОВЛЕН' }
216
+ }
217
+ const badge = badges[status] || badges.trial
218
+ return (
219
+ <span className={`px-2 py-1 rounded-lg text-xs font-bold ${badge.color}`}>
220
+ {badge.label}
221
+ </span>
222
+ )
223
+ }
224
+
225
+ if (!user?.is_superuser) {
226
+ return (
227
+ <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-8">
228
+ <div className="bg-white rounded-2xl shadow-lg border-2 border-red-200 p-8 text-center max-w-md">
229
+ <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
230
+ <Shield className="w-8 h-8 text-red-600" />
231
+ </div>
232
+ <h1 className="text-2xl font-bold text-slate-900 mb-2">Доступ запрещён</h1>
233
+ <p className="text-slate-600">Требуются права администратора</p>
234
+ </div>
235
+ </div>
236
+ )
237
+ }
238
+
239
+ if (loading) {
240
+ return (
241
+ <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center">
242
+ <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
243
+ </div>
244
+ )
245
+ }
246
+
247
+ return (
248
+ <div className="min-h-screen bg-gradient-to-br from-slate-50 via-indigo-50/20 to-purple-50/20">
249
+ {/* Header */}
250
+ <div className="bg-white border-b-2 border-indigo-100 shadow-sm">
251
+ <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
252
+ <div className="flex items-center gap-4">
253
+ <div className="p-3 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-xl shadow-lg">
254
+ <Shield className="w-8 h-8 text-white" />
255
+ </div>
256
+ <div>
257
+ <h1 className="text-3xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
258
+ Админ-панель
259
+ </h1>
260
+ <p className="text-sm text-slate-600 mt-1">Управление клиентами и подписками</p>
261
+ </div>
262
+ </div>
263
+ </div>
264
+ </div>
265
+
266
+ <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
267
+ {/* Stats Cards */}
268
+ {stats && (
269
+ <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
270
+ <div className="bg-white rounded-2xl shadow-lg border-2 border-indigo-100 p-6">
271
+ <div className="flex items-center gap-3 mb-2">
272
+ <Users className="w-6 h-6 text-indigo-600" />
273
+ <span className="text-sm font-semibold text-slate-600">Всего клиентов</span>
274
+ </div>
275
+ <p className="text-3xl font-bold text-slate-900">{stats.total_tenants}</p>
276
+ </div>
277
+
278
+ <div className="bg-white rounded-2xl shadow-lg border-2 border-emerald-100 p-6">
279
+ <div className="flex items-center gap-3 mb-2">
280
+ <Check className="w-6 h-6 text-emerald-600" />
281
+ <span className="text-sm font-semibold text-slate-600">Активных</span>
282
+ </div>
283
+ <p className="text-3xl font-bold text-emerald-600">{stats.by_status.active}</p>
284
+ </div>
285
+
286
+ <div className="bg-white rounded-2xl shadow-lg border-2 border-amber-100 p-6">
287
+ <div className="flex items-center gap-3 mb-2">
288
+ <Zap className="w-6 h-6 text-amber-600" />
289
+ <span className="text-sm font-semibold text-slate-600">На пробном</span>
290
+ </div>
291
+ <p className="text-3xl font-bold text-amber-600">{stats.by_status.trial}</p>
292
+ </div>
293
+
294
+ <div className="bg-white rounded-2xl shadow-lg border-2 border-purple-100 p-6">
295
+ <div className="flex items-center gap-3 mb-2">
296
+ <DollarSign className="w-6 h-6 text-purple-600" />
297
+ <span className="text-sm font-semibold text-slate-600">MRR</span>
298
+ </div>
299
+ <p className="text-3xl font-bold text-purple-600">${stats.estimated_mrr.toLocaleString()}</p>
300
+ </div>
301
+ </div>
302
+ )}
303
+
304
+ {/* Filters */}
305
+ <div className="bg-white rounded-2xl shadow-lg border-2 border-indigo-100 p-6 mb-6">
306
+ <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
307
+ <div className="md:col-span-2">
308
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
309
+ <Search className="w-4 h-4 inline mr-2" />
310
+ Поиск
311
+ </label>
312
+ <input
313
+ type="text"
314
+ value={searchQuery}
315
+ onChange={(e) => setSearchQuery(e.target.value)}
316
+ placeholder="Имя, email, компания..."
317
+ className="w-full px-4 py-2 border-2 border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
318
+ />
319
+ </div>
320
+
321
+ <div>
322
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
323
+ <Filter className="w-4 h-4 inline mr-2" />
324
+ План
325
+ </label>
326
+ <select
327
+ value={filterPlan}
328
+ onChange={(e) => setFilterPlan(e.target.value)}
329
+ className="w-full px-4 py-2 border-2 border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
330
+ >
331
+ <option value="">Все планы</option>
332
+ <option value="trial">Trial</option>
333
+ <option value="start">Start ($99)</option>
334
+ <option value="growth">Growth ($199)</option>
335
+ <option value="unlimited">Unlimited ($500)</option>
336
+ </select>
337
+ </div>
338
+
339
+ <div>
340
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
341
+ <Activity className="w-4 h-4 inline mr-2" />
342
+ Статус
343
+ </label>
344
+ <select
345
+ value={filterStatus}
346
+ onChange={(e) => setFilterStatus(e.target.value)}
347
+ className="w-full px-4 py-2 border-2 border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
348
+ >
349
+ <option value="">Все статусы</option>
350
+ <option value="trial">Пробный</option>
351
+ <option value="active">Активен</option>
352
+ <option value="expired">Истёк</option>
353
+ <option value="cancelled">Отменён</option>
354
+ <option value="suspended">Приостановлен</option>
355
+ </select>
356
+ </div>
357
+ </div>
358
+
359
+ <div className="mt-4">
360
+ <button
361
+ onClick={loadData}
362
+ className="px-6 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold rounded-lg transition-colors"
363
+ >
364
+ Применить фильтры
365
+ </button>
366
+ </div>
367
+ </div>
368
+
369
+ {/* Tenants Table */}
370
+ <div className="bg-white rounded-2xl shadow-lg border-2 border-indigo-100 overflow-hidden">
371
+ <div className="overflow-x-auto">
372
+ <table className="w-full">
373
+ <thead className="bg-gradient-to-r from-indigo-50 to-purple-50">
374
+ <tr>
375
+ <th className="px-6 py-4 text-left text-xs font-bold text-slate-700 uppercase">Клиент</th>
376
+ <th className="px-6 py-4 text-left text-xs font-bold text-slate-700 uppercase">Email</th>
377
+ <th className="px-6 py-4 text-left text-xs font-bold text-slate-700 uppercase">План</th>
378
+ <th className="px-6 py-4 text-left text-xs font-bold text-slate-700 uppercase">Статус</th>
379
+ <th className="px-6 py-4 text-left text-xs font-bold text-slate-700 uppercase">Диалоги</th>
380
+ <th className="px-6 py-4 text-left text-xs font-bold text-slate-700 uppercase">Окончание</th>
381
+ <th className="px-6 py-4 text-left text-xs font-bold text-slate-700 uppercase">Действия</th>
382
+ </tr>
383
+ </thead>
384
+ <tbody className="divide-y divide-slate-100">
385
+ {tenants.map((tenant) => (
386
+ <tr key={tenant.id} className="hover:bg-slate-50 transition-colors">
387
+ <td className="px-6 py-4">
388
+ <div>
389
+ <p className="font-semibold text-slate-900">{tenant.business_name}</p>
390
+ <p className="text-xs text-slate-500">{tenant.name}</p>
391
+ </div>
392
+ </td>
393
+ <td className="px-6 py-4 text-sm text-slate-600">{tenant.email}</td>
394
+ <td className="px-6 py-4">{getPlanBadge(tenant.subscription_plan)}</td>
395
+ <td className="px-6 py-4">{getStatusBadge(tenant.subscription_status)}</td>
396
+ <td className="px-6 py-4">
397
+ <span className="text-sm font-semibold text-indigo-600">{tenant.leads_this_month}</span>
398
+ </td>
399
+ <td className="px-6 py-4 text-sm text-slate-600">
400
+ {tenant.subscription_end
401
+ ? new Date(tenant.subscription_end).toLocaleDateString('ru-RU')
402
+ : '—'}
403
+ </td>
404
+ <td className="px-6 py-4">
405
+ <div className="flex items-center gap-2">
406
+ <button
407
+ onClick={() => openEditModal(tenant)}
408
+ className="p-2 text-indigo-600 hover:bg-indigo-100 rounded-lg transition-colors"
409
+ title="Редактировать"
410
+ >
411
+ <Edit className="w-5 h-5" />
412
+ </button>
413
+ {tenant.is_active ? (
414
+ <button
415
+ onClick={() => handleSuspend(tenant.id)}
416
+ className="p-2 text-orange-600 hover:bg-orange-100 rounded-lg transition-colors"
417
+ title="Приостановить"
418
+ >
419
+ <Ban className="w-5 h-5" />
420
+ </button>
421
+ ) : (
422
+ <button
423
+ onClick={() => handleActivate(tenant.id)}
424
+ className="p-2 text-emerald-600 hover:bg-emerald-100 rounded-lg transition-colors"
425
+ title="Активировать"
426
+ >
427
+ <Play className="w-5 h-5" />
428
+ </button>
429
+ )}
430
+ </div>
431
+ </td>
432
+ </tr>
433
+ ))}
434
+ </tbody>
435
+ </table>
436
+ </div>
437
+ </div>
438
+ </div>
439
+
440
+ {/* Edit Modal */}
441
+ {showEditModal && selectedTenant && (
442
+ <div className="fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
443
+ <div className="bg-white rounded-2xl shadow-2xl max-w-lg w-full">
444
+ <div className="bg-gradient-to-r from-indigo-600 to-purple-600 px-6 py-4 rounded-t-2xl flex items-center justify-between">
445
+ <h3 className="text-xl font-bold text-white">Изменить подписку</h3>
446
+ <button
447
+ onClick={() => setShowEditModal(false)}
448
+ className="p-1 hover:bg-white/20 rounded-lg transition-colors"
449
+ >
450
+ <X className="w-6 h-6 text-white" />
451
+ </button>
452
+ </div>
453
+
454
+ <div className="p-6 space-y-4">
455
+ <div>
456
+ <p className="text-sm text-slate-600 mb-1">Клиент:</p>
457
+ <p className="font-bold text-slate-900">{selectedTenant.business_name}</p>
458
+ <p className="text-xs text-slate-500">{selectedTenant.email}</p>
459
+ </div>
460
+
461
+ <div>
462
+ <label className="block text-sm font-semibold text-slate-700 mb-2">План</label>
463
+ <select
464
+ value={editPlan}
465
+ onChange={(e) => setEditPlan(e.target.value)}
466
+ className="w-full px-4 py-2 border-2 border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
467
+ >
468
+ <option value="trial">Trial (7 дней бесплатно)</option>
469
+ <option value="start">Start ($99/мес - 300 диалогов, 1 канал)</option>
470
+ <option value="growth">Growth ($199/мес - 1000 диалогов, 2 канала)</option>
471
+ <option value="unlimited">Unlimited ($500/мес - безлимит)</option>
472
+ </select>
473
+ </div>
474
+
475
+ <div>
476
+ <label className="block text-sm font-semibold text-slate-700 mb-2">Статус</label>
477
+ <select
478
+ value={editStatus}
479
+ onChange={(e) => setEditStatus(e.target.value)}
480
+ className="w-full px-4 py-2 border-2 border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
481
+ >
482
+ <option value="trial">Пробный период</option>
483
+ <option value="active">Активна</option>
484
+ <option value="expired">Истекла</option>
485
+ <option value="cancelled">Отменена</option>
486
+ <option value="suspended">Приостановлена</option>
487
+ </select>
488
+ </div>
489
+
490
+ <div>
491
+ <label className="block text-sm font-semibold text-slate-700 mb-2">Продлить на (дней)</label>
492
+ <input
493
+ type="number"
494
+ value={daysToAdd}
495
+ onChange={(e) => setDaysToAdd(parseInt(e.target.value))}
496
+ className="w-full px-4 py-2 border-2 border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
497
+ min="0"
498
+ />
499
+ </div>
500
+
501
+ <div className="flex gap-3 pt-4">
502
+ <button
503
+ onClick={handleUpdateSubscription}
504
+ disabled={updating}
505
+ className="flex-1 px-6 py-3 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 text-white font-bold rounded-lg transition-all disabled:opacity-50"
506
+ >
507
+ {updating ? 'Сохранение...' : 'Сохранить'}
508
+ </button>
509
+ <button
510
+ onClick={() => setShowEditModal(false)}
511
+ className="px-6 py-3 bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold rounded-lg transition-colors"
512
+ >
513
+ Отмена
514
+ </button>
515
+ </div>
516
+ </div>
517
+ </div>
518
+ </div>
519
+ )}
520
+ </div>
521
+ )
522
+ }
frontend/contexts/AuthContext.tsx CHANGED
@@ -10,6 +10,7 @@ interface User {
10
  tenant_id: string
11
  tenant_name: string
12
  role: string // 'OWNER' or 'MANAGER'
 
13
  }
14
 
15
  interface AuthContextType {
 
10
  tenant_id: string
11
  tenant_name: string
12
  role: string // 'OWNER' or 'MANAGER'
13
+ is_superuser: boolean // Admin access
14
  }
15
 
16
  interface AuthContextType {