Spaces:
Running

axeronis commited on
Commit
f6ef3ae
·
1 Parent(s): 047a8e1

feat: add admin dashboard with restricted access

Browse files
backend/app/api/admin.py CHANGED
@@ -1,385 +1,129 @@
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.api.deps 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
- # ✅ СБРОС СЧЁТЧИКА ДИАЛОГОВ ПРИ ПРОДЛЕНИИ/СМЕНЕ ПЛАНА
195
- # Это даёт клиенту свежий лимит на новый период
196
- tenant.leads_this_month = 0
197
-
198
- # Update billing dates
199
- tenant.last_billing_date = datetime.utcnow()
200
- if tenant.subscription_end:
201
- tenant.next_billing_date = tenant.subscription_end
202
-
203
- tenant.updated_at = datetime.utcnow()
204
-
205
- session.add(tenant)
206
- await session.commit()
207
- await session.refresh(tenant)
208
-
209
- return SubscriptionUpdateResponse(
210
- success=True,
211
- message=f"Подписка обновлена: {request.plan.upper()} ({request.status.upper()})",
212
- tenant_id=str(tenant.id),
213
- new_plan=tenant.subscription_plan,
214
- new_status=tenant.subscription_status,
215
- subscription_end=tenant.subscription_end.isoformat() if tenant.subscription_end else None
216
- )
217
-
218
-
219
- @router.post("/tenants/{tenant_id}/activate")
220
- async def activate_tenant(
221
- tenant_id: UUID,
222
- admin_user: User = Depends(require_superuser),
223
- session: AsyncSession = Depends(get_async_session)
224
- ):
225
- """Активировать tenant (is_active=True)."""
226
-
227
- stmt = select(Tenant).where(Tenant.id == tenant_id)
228
- result = await session.execute(stmt)
229
- tenant = result.scalar_one_or_none()
230
-
231
- if not tenant:
232
- raise HTTPException(status_code=404, detail="Tenant не найден")
233
-
234
- tenant.is_active = True
235
- tenant.updated_at = datetime.utcnow()
236
-
237
- session.add(tenant)
238
- await session.commit()
239
-
240
- return {"success": True, "message": f"Tenant {tenant.name} активирован"}
241
-
242
-
243
- @router.post("/tenants/{tenant_id}/suspend")
244
- async def suspend_tenant(
245
- tenant_id: UUID,
246
- admin_user: User = Depends(require_superuser),
247
- session: AsyncSession = Depends(get_async_session)
248
- ):
249
- """Приостановить tenant (is_active=False, status=suspended)."""
250
-
251
- stmt = select(Tenant).where(Tenant.id == tenant_id)
252
- result = await session.execute(stmt)
253
- tenant = result.scalar_one_or_none()
254
-
255
- if not tenant:
256
- raise HTTPException(status_code=404, detail="Tenant не найден")
257
-
258
- tenant.is_active = False
259
- tenant.subscription_status = "suspended"
260
- tenant.updated_at = datetime.utcnow()
261
-
262
- session.add(tenant)
263
- await session.commit()
264
-
265
- return {"success": True, "message": f"Tenant {tenant.name} приостановлен"}
266
-
267
-
268
- @router.get("/stats")
269
- async def get_admin_stats(
270
- admin_user: User = Depends(require_superuser),
271
- session: AsyncSession = Depends(get_async_session)
272
- ):
273
- """Статистика платформы для админа."""
274
-
275
- # Total tenants
276
- stmt = select(Tenant)
277
- result = await session.execute(stmt)
278
- all_tenants = result.scalars().all()
279
-
280
- # Count by status
281
- trial_count = len([t for t in all_tenants if t.subscription_status == "trial"])
282
- active_count = len([t for t in all_tenants if t.subscription_status == "active"])
283
- expired_count = len([t for t in all_tenants if t.subscription_status == "expired"])
284
- cancelled_count = len([t for t in all_tenants if t.subscription_status == "cancelled"])
285
-
286
- # Count by plan
287
- trial_plan_count = len([t for t in all_tenants if t.subscription_plan == "trial"])
288
- start_count = len([t for t in all_tenants if t.subscription_plan == "start"])
289
- growth_count = len([t for t in all_tenants if t.subscription_plan == "growth"])
290
- unlimited_count = len([t for t in all_tenants if t.subscription_plan == "unlimited"])
291
-
292
- # Revenue calculation (mock)
293
- monthly_revenue = (start_count * 99) + (growth_count * 199) + (unlimited_count * 500)
294
-
295
- return {
296
- "total_tenants": len(all_tenants),
297
- "by_status": {
298
- "trial": trial_count,
299
- "active": active_count,
300
- "expired": expired_count,
301
- "cancelled": cancelled_count
302
- },
303
- "by_plan": {
304
- "trial": trial_plan_count,
305
- "start": start_count,
306
- "growth": growth_count,
307
- "unlimited": unlimited_count
308
- },
309
- "estimated_mrr": monthly_revenue
310
- }
311
-
312
-
313
- @router.get("/tenants/{tenant_id}/usage")
314
- async def get_tenant_usage(
315
- tenant_id: UUID,
316
- admin_user: User = Depends(require_superuser),
317
- session: AsyncSession = Depends(get_async_session)
318
- ):
319
- """Получить статистику использования конкретного tenant."""
320
- from app.services.subscription_manager import SubscriptionManager
321
-
322
- stmt = select(Tenant).where(Tenant.id == tenant_id)
323
- result = await session.execute(stmt)
324
- tenant = result.scalar_one_or_none()
325
-
326
- if not tenant:
327
- raise HTTPException(status_code=404, detail="Tenant не найден")
328
-
329
- usage_stats = await SubscriptionManager.get_usage_stats(tenant)
330
- plan_info = SubscriptionManager.get_plan_info(tenant.subscription_plan)
331
-
332
- return {
333
- "tenant_id": str(tenant.id),
334
- "tenant_name": tenant.name,
335
- "plan": plan_info,
336
- "usage": usage_stats
337
- }
338
-
339
-
340
- # ==================== LANDING PAGE CONFIG ====================
341
-
342
- import json
343
- import os
344
-
345
- CONFIG_FILE = "landing_config.json"
346
-
347
- class LandingConfig(BaseModel):
348
- pricing: dict
349
- companies: List[dict]
350
-
351
- @router.get("/landing-config")
352
- async def get_landing_config(
353
- session: AsyncSession = Depends(get_async_session)
354
- ):
355
- """Get landing page configuration."""
356
- if not os.path.exists(CONFIG_FILE):
357
- return {
358
- "pricing": {
359
- "starter": {"price": 99, "features": ["1 Channel", "300 dialogs"]},
360
- "growth": {"price": 199, "features": ["3 Channels", "1000 dialogs"]},
361
- "scale": {"price": 499, "features": ["Unlimited Channels", "5000+ dialogs"]}
362
- },
363
- "companies": []
364
- }
365
-
366
- try:
367
- with open(CONFIG_FILE, "r", encoding="utf-8") as f:
368
- return json.load(f)
369
- except Exception as e:
370
- print(f"Error reading config: {e}")
371
- return {}
372
-
373
- @router.post("/landing-config")
374
- async def update_landing_config(
375
- config: LandingConfig,
376
- admin_user: User = Depends(require_superuser),
377
- session: AsyncSession = Depends(get_async_session)
378
- ):
379
- """Update landing page configuration."""
380
- try:
381
- with open(CONFIG_FILE, "w", encoding="utf-8") as f:
382
- json.dump(config.dict(), f, indent=2, ensure_ascii=False)
383
- return {"success": True, "message": "Configuration saved"}
384
- except Exception as e:
385
- raise HTTPException(status_code=500, detail=str(e))
 
1
+ from fastapi import APIRouter, Depends, HTTPException, status
2
+ from sqlmodel import select, func
3
+ from sqlmodel.ext.asyncio.session import AsyncSession
4
+ from pydantic import BaseModel
 
 
 
 
 
5
  from typing import List, Optional
6
+ from datetime import datetime
7
  from uuid import UUID
8
 
9
  from app.core.database import get_async_session
10
  from app.api.deps import get_current_user
11
+ from app.models import User, Tenant, Partner, PartnerEarning
 
 
12
 
13
+ router = APIRouter(prefix="/admin", tags=["Admin"])
14
 
15
+ ADMIN_EMAIL = "axeroni.s2@gmail.com"
16
 
17
+ # ============================================================================
18
+ # Schemas
19
+ # ============================================================================
20
 
21
+ class AdminTenantResponse(BaseModel):
22
+ id: UUID
 
23
  name: str
24
+ business_name: Optional[str]
25
+ email: str
26
  subscription_plan: str
27
+ conversations_count: int
 
 
 
28
  is_active: bool
29
+ created_at: datetime
30
+ partner_email: Optional[str] = None
31
+
32
+ class AdminPartnerResponse(BaseModel):
33
+ id: UUID
34
+ company_name: str
35
+ contact_email: Optional[str]
36
+ referral_code: str
37
+ status: str
38
+ balance_usd: float
39
+ total_earned: float
40
+ tenants_count: int
41
+ created_at: datetime
42
+
43
+ # ============================================================================
44
+ # Dependencies
45
+ # ============================================================================
46
+
47
+ async def get_admin_user(current_user: User = Depends(get_current_user)):
48
+ """
49
+ Restrict access to specific admin email.
50
+ """
51
+ if current_user.email != ADMIN_EMAIL:
 
52
  raise HTTPException(
53
  status_code=status.HTTP_403_FORBIDDEN,
54
+ detail="Access denied. Admin rights required."
55
  )
56
  return current_user
57
 
58
+ # ============================================================================
59
+ # Endpoints
60
+ # ============================================================================
61
 
62
+ @router.get("/tenants", response_model=List[AdminTenantResponse])
 
 
63
  async def list_all_tenants(
64
+ session: AsyncSession = Depends(get_async_session),
65
+ current_user: User = Depends(get_admin_user)
 
 
 
66
  ):
67
  """
68
+ List all tenants with their stats.
 
 
 
 
 
69
  """
70
+ # Use explicit join to avoid async relationship loading issues
71
+ statement = select(Tenant, User.email, Partner.contact_email)\
72
+ .join(User, Tenant.id == User.tenant_id)\
73
+ .outerjoin(Partner, Tenant.partner_ref_id == Partner.id)
74
+
75
+ result = await session.execute(statement)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  rows = result.all()
77
 
78
+ response = []
79
+ for tenant, user_email, partner_email in rows:
80
+ # Count conversations (simplified count for now)
81
+ # In real app, might need a separate query or counter cache
82
+
83
+ response.append(AdminTenantResponse(
84
+ id=tenant.id,
85
  name=tenant.name,
86
  business_name=tenant.business_name,
87
+ email=user_email,
88
+ subscription_plan=tenant.subscription_plan or "trial",
89
+ conversations_count=0, # Placeholder, needs aggregation query
90
+ is_active=tenant.is_active,
91
+ created_at=tenant.created_at,
92
+ partner_email=partner_email
 
93
  ))
94
+
95
+ return response
96
 
97
 
98
+ @router.get("/partners", response_model=List[AdminPartnerResponse])
99
+ async def list_all_partners(
100
+ session: AsyncSession = Depends(get_async_session),
101
+ current_user: User = Depends(get_admin_user)
 
 
102
  ):
103
  """
104
+ List all partners with their stats.
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  """
106
+ statement = select(Partner)
107
+ result = await session.execute(statement)
108
+ partners = result.scalars().all()
109
+
110
+ response = []
111
+ for partner in partners:
112
+ # Count tenants referred by this partner
113
+ count_stmt = select(func.count(Tenant.id)).where(Tenant.partner_ref_id == partner.id)
114
+ count_result = await session.execute(count_stmt)
115
+ tenants_count = count_result.scalar_one()
116
+
117
+ response.append(AdminPartnerResponse(
118
+ id=partner.id,
119
+ company_name=partner.company_name,
120
+ contact_email=partner.contact_email,
121
+ referral_code=partner.referral_code,
122
+ status=partner.status,
123
+ balance_usd=partner.balance_usd,
124
+ total_earned=partner.total_earned,
125
+ tenants_count=tenants_count,
126
+ created_at=partner.created_at
127
+ ))
128
+
129
+ return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/app/main.py CHANGED
@@ -1,173 +1,6 @@
1
  from fastapi import FastAPI, Request, status
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import JSONResponse
4
- from fastapi.exceptions import RequestValidationError
5
- from starlette.exceptions import HTTPException as StarletteHTTPException
6
- 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, billing, ai_training, crm, admin, team, evolution_webhook, telegram_webhook
11
- import asyncio
12
- import sys
13
- from slowapi import Limiter, _rate_limit_exceeded_handler
14
- from slowapi.util import get_remote_address
15
- from slowapi.errors import RateLimitExceeded
16
- import sentry_sdk
17
- from sentry_sdk.integrations.fastapi import FastApiIntegration
18
- from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
19
-
20
- # Fix for Windows: psycopg requires SelectorEventLoop on Windows
21
- if sys.platform == 'win32':
22
- asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
23
-
24
- # Configure structured logging
25
- configure_logging()
26
- logger = get_logger(__name__)
27
-
28
- # Initialize Sentry (error tracking)
29
- if settings.SENTRY_DSN:
30
- sentry_sdk.init(
31
- dsn=settings.SENTRY_DSN,
32
- environment=settings.ENVIRONMENT,
33
- traces_sample_rate=0.1 if settings.ENVIRONMENT == "production" else 1.0,
34
- integrations=[
35
- FastApiIntegration(),
36
- SqlalchemyIntegration(),
37
- ],
38
- # Don't send PII
39
- send_default_pii=False,
40
- )
41
- logger.info("Sentry initialized", environment=settings.ENVIRONMENT)
42
-
43
- # Rate limiter
44
- limiter = Limiter(key_func=get_remote_address)
45
-
46
- app = FastAPI(
47
- title=settings.APP_NAME,
48
- debug=settings.DEBUG,
49
- version="1.0.0",
50
- description="MicroFunnel - AI Sales Platform"
51
- )
52
-
53
- # Add rate limiter to app state
54
- app.state.limiter = limiter
55
- app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
56
-
57
-
58
- # ============================================================================
59
- # ГЛОБАЛЬНЫЕ EXCEPTION HANDLERS (Production-Ready)
60
- # ============================================================================
61
-
62
- @app.exception_handler(StarletteHTTPException)
63
- async def http_exception_handler(request: Request, exc: StarletteHTTPException):
64
- """Обработчик для всех HTTP-исключений (404, 403, и т.д.)."""
65
- request_id = getattr(request.state, 'request_id', 'unknown')
66
-
67
- logger.warning(
68
- "HTTP Exception",
69
- status_code=exc.status_code,
70
- detail=exc.detail,
71
- request_id=request_id,
72
- path=request.url.path
73
- )
74
-
75
- return JSONResponse(
76
- status_code=exc.status_code,
77
- content={
78
- "detail": exc.detail,
79
- "request_id": request_id
80
- }
81
- )
82
-
83
-
84
- @app.exception_handler(RequestValidationError)
85
- async def validation_exception_handler(request: Request, exc: RequestValidationError):
86
- """Обработчик ошибок валидации Pydantic (422 Unprocessable Entity)."""
87
- request_id = getattr(request.state, 'request_id', 'unknown')
88
-
89
- logger.warning(
90
- "Validation Error",
91
- errors=exc.errors(),
92
- request_id=request_id,
93
- path=request.url.path
94
- )
95
-
96
- return JSONResponse(
97
- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
98
- content={
99
- "detail": "Ошибка валидации данных",
100
- "errors": exc.errors(),
101
- "request_id": request_id
102
- }
103
- )
104
-
105
-
106
- @app.exception_handler(Exception)
107
- async def global_exception_handler(request: Request, exc: Exception):
108
- """
109
- Глобальный обработчик для ВСЕХ необработанных исключений.
110
-
111
- КРИТИЧНО для production:
112
- - НЕ раскрывает технические детали клиенту
113
- - Логирует полный traceback в Sentry
114
- - Возвращает user-friendly сообщение
115
- """
116
- request_id = getattr(request.state, 'request_id', 'unknown')
117
-
118
- # Логируем ПОЛНУЮ ошибку (с traceback) для debugging
119
- logger.error(
120
- "Unhandled Exception",
121
- exc_info=exc,
122
- request_id=request_id,
123
- path=request.url.path,
124
- method=request.method,
125
- error_type=type(exc).__name__
126
- )
127
-
128
- # Отправляем в Sentry (если настроен)
129
- if settings.SENTRY_DSN:
130
- sentry_sdk.capture_exception(exc)
131
-
132
- # Возвращаем безопасный ответ клиенту (БЕЗ технических деталей)
133
- return JSONResponse(
134
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
135
- content={
136
- "detail": "Внутренняя ошибка сервера. Мы уже работаем над исправлением.",
137
- "request_id": request_id,
138
- "support_hint": "Сообщите этот request_id в поддержку для быстрого решения проблемы."
139
- }
140
- )
141
-
142
- # Log CORS settings
143
- allowed_origins = settings.get_allowed_origins()
144
- logger.info(f"CORS allowed origins: {allowed_origins}")
145
-
146
- # CORS middleware - MUST be added BEFORE other middleware
147
- app.add_middleware(
148
- CORSMiddleware,
149
- allow_origins=allowed_origins,
150
- allow_credentials=True,
151
- allow_methods=["*"],
152
- allow_headers=["*"],
153
- expose_headers=["*"], # Allow frontend to access all headers
154
- max_age=3600, # Cache preflight requests for 1 hour
155
- )
156
-
157
- # Request ID middleware for tracing
158
- app.add_middleware(RequestIDMiddleware)
159
-
160
- # Include API routers with /api/v1 prefix
161
- app.include_router(auth.router, prefix="/api/v1")
162
- app.include_router(webhook.router, prefix="/api/v1") # Email webhook
163
- app.include_router(evolution_webhook.router, prefix="/api/v1") # Evolution API (WhatsApp)
164
- app.include_router(telegram_webhook.router, prefix="/api/v1") # Telegram webhook
165
- # app.include_router(linkedin_webhook.router, prefix="/api/v1") # LinkedIn webhook (TODO: Implement)
166
- app.include_router(leads.router, prefix="/api/v1")
167
- app.include_router(knowledge.router, prefix="/api/v1")
168
- app.include_router(channels.router, prefix="/api/v1")
169
- app.include_router(channels.router) # Fallback for requests missing /api/v1
170
- app.include_router(tenants.router, prefix="/api/v1")
171
  app.include_router(analytics.router, prefix="/api/v1")
172
  app.include_router(chats.router, prefix="/api/v1")
173
  app.include_router(playbook.router, prefix="/api/v1")
 
1
  from fastapi import FastAPI, Request, status
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import JSONResponse
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  app.include_router(analytics.router, prefix="/api/v1")
5
  app.include_router(chats.router, prefix="/api/v1")
6
  app.include_router(playbook.router, prefix="/api/v1")
frontend/app/admin/dashboard/page.tsx ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use client'
2
+
3
+ import { useState, useEffect } from 'react'
4
+ import {
5
+ Users, Building, DollarSign, Search, Shield,
6
+ MoreVertical, CheckCircle, XCircle, TrendingUp,
7
+ Store, Briefcase
8
+ } from 'lucide-react'
9
+ import { motion } from 'framer-motion'
10
+ import { cn } from '@/lib/utils'
11
+ import { api } from '@/lib/api'
12
+
13
+ // Interfaces
14
+ interface AdminTenant {
15
+ id: string
16
+ name: string
17
+ business_name: string | null
18
+ email: string
19
+ subscription_plan: string
20
+ conversations_count: number
21
+ is_active: boolean
22
+ created_at: string
23
+ partner_email: string | null
24
+ }
25
+
26
+ interface AdminPartner {
27
+ id: string
28
+ company_name: string
29
+ contact_email: string | null
30
+ referral_code: string
31
+ status: string
32
+ balance_usd: number
33
+ total_earned: number
34
+ tenants_count: number
35
+ created_at: string
36
+ }
37
+
38
+ export default function AdminDashboard() {
39
+ const [activeTab, setActiveTab] = useState<'tenants' | 'partners'>('tenants')
40
+ const [loading, setLoading] = useState(true)
41
+ const [tenants, setTenants] = useState<AdminTenant[]>([])
42
+ const [partners, setPartners] = useState<AdminPartner[]>([])
43
+ const [error, setError] = useState<string | null>(null)
44
+
45
+ useEffect(() => {
46
+ fetchData()
47
+ }, [])
48
+
49
+ const fetchData = async () => {
50
+ setError(null)
51
+ try {
52
+ const [tenantsRes, partnersRes] = await Promise.all([
53
+ api.get('/api/v1/admin/tenants'),
54
+ api.get('/api/v1/admin/partners')
55
+ ])
56
+ setTenants(tenantsRes.data)
57
+ setPartners(partnersRes.data)
58
+ } catch (err: any) {
59
+ console.error('Failed to fetch admin data:', err)
60
+ if (err.response?.status === 403) {
61
+ setError('⛔ Доступ запрещен. Требуются права администратора.')
62
+ } else {
63
+ setError('Ошибка загрузки данных.')
64
+ }
65
+ } finally {
66
+ setLoading(false)
67
+ }
68
+ }
69
+
70
+ if (loading) {
71
+ return <div className="min-h-screen flex items-center justify-center">Загрузка...</div>
72
+ }
73
+
74
+ if (error) {
75
+ return (
76
+ <div className="min-h-screen flex items-center justify-center p-4">
77
+ <div className="bg-red-50 p-6 rounded-2xl max-w-md text-center border border-red-100">
78
+ <Shield className="w-12 h-12 text-red-500 mx-auto mb-4" />
79
+ <h2 className="text-xl font-bold text-red-700 mb-2">Ошибка доступа</h2>
80
+ <p className="text-red-600">{error}</p>
81
+ </div>
82
+ </div>
83
+ )
84
+ }
85
+
86
+ return (
87
+ <div className="min-h-screen bg-slate-50 p-6 md:p-8">
88
+ <div className="max-w-7xl mx-auto space-y-6">
89
+
90
+ {/* Header */}
91
+ <div className="flex items-center justify-between">
92
+ <div>
93
+ <h1 className="text-3xl font-bold text-slate-900 flex items-center gap-3">
94
+ <Shield className="w-8 h-8 text-indigo-600" />
95
+ Панель Администратора
96
+ </h1>
97
+ <p className="text-slate-600 mt-1">
98
+ {tenants.length} клиентов • {partners.length} партнеров
99
+ </p>
100
+ </div>
101
+ </div>
102
+
103
+ {/* Tabs */}
104
+ <div className="flex gap-2 p-1 bg-white rounded-xl w-fit shadow-sm border border-slate-200">
105
+ <button
106
+ onClick={() => setActiveTab('tenants')}
107
+ className={cn(
108
+ "px-4 py-2 rounded-lg text-sm font-medium transition-all flex items-center gap-2",
109
+ activeTab === 'tenants'
110
+ ? "bg-indigo-50 text-indigo-700 shadow-sm"
111
+ : "text-slate-500 hover:bg-slate-50"
112
+ )}
113
+ >
114
+ <Building className="w-4 h-4" />
115
+ Клиенты (Tenants)
116
+ </button>
117
+ <button
118
+ onClick={() => setActiveTab('partners')}
119
+ className={cn(
120
+ "px-4 py-2 rounded-lg text-sm font-medium transition-all flex items-center gap-2",
121
+ activeTab === 'partners'
122
+ ? "bg-indigo-50 text-indigo-700 shadow-sm"
123
+ : "text-slate-500 hover:bg-slate-50"
124
+ )}
125
+ >
126
+ <Briefcase className="w-4 h-4" />
127
+ Партнеры
128
+ </button>
129
+ </div>
130
+
131
+ {/* Content */}
132
+ {activeTab === 'tenants' ? (
133
+ <motion.div
134
+ initial={{ opacity: 0 }}
135
+ animate={{ opacity: 1 }}
136
+ className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden"
137
+ >
138
+ <div className="overflow-x-auto">
139
+ <table className="w-full text-left">
140
+ <thead className="bg-slate-50 border-b border-slate-200">
141
+ <tr>
142
+ <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase">Компания</th>
143
+ <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase">Email Владельца</th>
144
+ <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase">План</th>
145
+ <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase">Партнер</th>
146
+ <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase">Статус</th>
147
+ <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase">Создан</th>
148
+ </tr>
149
+ </thead>
150
+ <tbody className="divide-y divide-slate-100">
151
+ {tenants.map((tenant) => (
152
+ <tr key={tenant.id} className="hover:bg-slate-50/50">
153
+ <td className="px-6 py-4">
154
+ <div className="font-medium text-slate-900">{tenant.business_name || tenant.name}</div>
155
+ <div className="text-xs text-slate-500 font-mono">{tenant.id.slice(0, 8)}...</div>
156
+ </td>
157
+ <td className="px-6 py-4 text-sm text-slate-600">{tenant.email}</td>
158
+ <td className="px-6 py-4">
159
+ <span className={cn(
160
+ "px-2 py-1 rounded-full text-xs font-bold uppercase",
161
+ tenant.subscription_plan === 'unlimited' ? "bg-purple-100 text-purple-700" :
162
+ tenant.subscription_plan === 'growth' ? "bg-indigo-100 text-indigo-700" :
163
+ "bg-slate-100 text-slate-600"
164
+ )}>
165
+ {tenant.subscription_plan}
166
+ </span>
167
+ </td>
168
+ <td className="px-6 py-4 text-sm text-slate-500">
169
+ {tenant.partner_email || '-'}
170
+ </td>
171
+ <td className="px-6 py-4">
172
+ {tenant.is_active ? (
173
+ <span className="flex items-center gap-1.5 text-emerald-600 text-xs font-bold">
174
+ <CheckCircle className="w-3 h-3" /> Активен
175
+ </span>
176
+ ) : (
177
+ <span className="flex items-center gap-1.5 text-red-500 text-xs font-bold">
178
+ <XCircle className="w-3 h-3" /> Заблокирован
179
+ </span>
180
+ )}
181
+ </td>
182
+ <td className="px-6 py-4 text-sm text-slate-500">
183
+ {new Date(tenant.created_at).toLocaleDateString()}
184
+ </td>
185
+ </tr>
186
+ ))}
187
+ </tbody>
188
+ </table>
189
+ </div>
190
+ </motion.div>
191
+ ) : (
192
+ <motion.div
193
+ initial={{ opacity: 0 }}
194
+ animate={{ opacity: 1 }}
195
+ className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden"
196
+ >
197
+ <div className="overflow-x-auto">
198
+ <table className="w-full text-left">
199
+ <thead className="bg-slate-50 border-b border-slate-200">
200
+ <tr>
201
+ <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase">Компания</th>
202
+ <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase">Контакты</th>
203
+ <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase">Реф. Код</th>
204
+ <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase">Клиенты</th>
205
+ <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase">Баланс</th>
206
+ <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase">Статус</th>
207
+ </tr>
208
+ </thead>
209
+ <tbody className="divide-y divide-slate-100">
210
+ {partners.map((partner) => (
211
+ <tr key={partner.id} className="hover:bg-slate-50/50">
212
+ <td className="px-6 py-4">
213
+ <div className="font-medium text-slate-900">{partner.company_name}</div>
214
+ </td>
215
+ <td className="px-6 py-4 text-sm text-slate-600">
216
+ {partner.contact_email}
217
+ </td>
218
+ <td className="px-6 py-4">
219
+ <code className="bg-slate-100 px-2 py-1 rounded text-xs">
220
+ {partner.referral_code}
221
+ </code>
222
+ </td>
223
+ <td className="px-6 py-4">
224
+ <div className="flex items-center gap-2">
225
+ <Users className="w-4 h-4 text-slate-400" />
226
+ <span className="font-bold">{partner.tenants_count}</span>
227
+ </div>
228
+ </td>
229
+ <td className="px-6 py-4">
230
+ <div className="font-bold text-emerald-600">
231
+ ${partner.balance_usd.toFixed(2)}
232
+ </div>
233
+ <div className="text-xs text-slate-400">
234
+ Всего: ${partner.total_earned.toFixed(2)}
235
+ </div>
236
+ </td>
237
+ <td className="px-6 py-4">
238
+ <span className={cn(
239
+ "px-2 py-1 rounded-full text-xs font-bold uppercase",
240
+ partner.status === 'ACTIVE' ? "bg-emerald-100 text-emerald-700" :
241
+ "bg-amber-100 text-amber-700"
242
+ )}>
243
+ {partner.status}
244
+ </span>
245
+ </td>
246
+ </tr>
247
+ ))}
248
+ </tbody>
249
+ </table>
250
+ </div>
251
+ </motion.div>
252
+ )}
253
+ </div>
254
+ </div>
255
+ )
256
+ }