Spaces:
Running

axeronis commited on
Commit
ca13047
·
1 Parent(s): ccfa937

Refactor Sidebar and Landing Page with premium design

Browse files
backend/app/api/channels.py CHANGED
@@ -1,5 +1,5 @@
1
  """
2
- Channels API - Telegram, WhatsApp, LinkedIn Connection
3
  """
4
  from fastapi import APIRouter, HTTPException, Depends
5
  from pydantic import BaseModel
@@ -13,6 +13,7 @@ from app.core.logging import get_logger
13
  from app.models import User
14
  from app.api.deps import get_current_user
15
  from app.services.whatsapp_qr import whatsapp_qr_service
 
16
 
17
  logger = get_logger(__name__)
18
  router = APIRouter(prefix="/channels", tags=["Channels"])
@@ -31,13 +32,6 @@ class TelegramConnectResponse(BaseModel):
31
  message: str
32
 
33
 
34
- class MetaChannelConnectRequest(BaseModel):
35
- """Meta (WhatsApp) channel connection request."""
36
- access_token: str
37
- phone_number_id: str | None = None # WhatsApp only
38
- verify_token: str
39
-
40
-
41
  class LinkedInConnectRequest(BaseModel):
42
  """LinkedIn channel connection request."""
43
  access_token: str
@@ -45,14 +39,6 @@ class LinkedInConnectRequest(BaseModel):
45
  verify_token: str
46
 
47
 
48
- class MetaChannelResponse(BaseModel):
49
- """Meta channel connection response."""
50
- ok: bool
51
- status: str
52
- webhook_url: str
53
- message: str
54
-
55
-
56
  @router.post("/telegram/connect", response_model=TelegramConnectResponse)
57
  async def connect_telegram_bot(
58
  request: TelegramConnectRequest,
@@ -61,40 +47,28 @@ async def connect_telegram_bot(
61
  ):
62
  """
63
  Connect Telegram bot to authenticated user's tenant account.
64
-
65
- Steps:
66
- 1. Validate bot token
67
- 2. Update tenant's bot token in DB
68
- 3. Automatically set webhook in Telegram
69
- 4. Return success/failure
70
  """
71
  try:
72
- # Use authenticated user's tenant_id (prevents tenant isolation breach)
73
  tenant_id = current_user.tenant_id
74
 
75
- # Get tenant
76
  tenant = await session.get(Tenant, tenant_id)
77
  if not tenant:
78
  raise HTTPException(status_code=404, detail="Tenant not found")
79
 
80
  bot_token = request.bot_token.strip()
81
 
82
- # Validate token format (basic check)
83
  if not bot_token or ":" not in bot_token:
84
  raise HTTPException(
85
  status_code=400,
86
  detail="Неверный формат токена. Токен должен быть вида: 123456:ABC-DEF..."
87
  )
88
 
89
- # Construct webhook URL
90
  webhook_base = settings.TELEGRAM_WEBHOOK_URL or "https://your-domain.com"
91
  webhook_url = f"{webhook_base}/webhook/telegram/{tenant_id}"
92
 
93
- # Set webhook in Telegram
94
  telegram_api_url = f"https://api.telegram.org/bot{bot_token}/setWebhook"
95
 
96
  async with httpx.AsyncClient(timeout=30.0) as client:
97
- # First, verify bot token is valid by getting bot info
98
  bot_info_response = await client.get(
99
  f"https://api.telegram.org/bot{bot_token}/getMe"
100
  )
@@ -114,7 +88,6 @@ async def connect_telegram_bot(
114
 
115
  bot_username = bot_data.get("result", {}).get("username", "Unknown")
116
 
117
- # Set webhook
118
  webhook_response = await client.post(
119
  telegram_api_url,
120
  json={
@@ -133,7 +106,6 @@ async def connect_telegram_bot(
133
  detail=f"Ошибка при установке webhook: {error_description}"
134
  )
135
 
136
- # Update tenant in database
137
  tenant.telegram_bot_token = bot_token
138
  tenant.webhook_url = webhook_url
139
  session.add(tenant)
@@ -149,11 +121,8 @@ async def connect_telegram_bot(
149
  except HTTPException:
150
  raise
151
  except Exception as e:
152
- print(f"❌ Telegram connection error: {e}")
153
- raise HTTPException(
154
- status_code=500,
155
- detail=f"Ошибка подключения: {str(e)}"
156
- )
157
 
158
 
159
  @router.get("/telegram/status")
@@ -161,9 +130,8 @@ async def get_telegram_status(
161
  current_user: User = Depends(get_current_user),
162
  session = Depends(get_session)
163
  ):
164
- """Get current Telegram bot connection status for authenticated user's tenant."""
165
  try:
166
- # Use authenticated user's tenant_id (prevents tenant isolation breach)
167
  tenant_id = current_user.tenant_id
168
 
169
  tenant = await session.get(Tenant, tenant_id)
@@ -174,7 +142,6 @@ async def get_telegram_status(
174
 
175
  bot_info = None
176
  if has_token:
177
- # Verify token is still valid
178
  try:
179
  async with httpx.AsyncClient(timeout=10.0) as client:
180
  response = await client.get(
@@ -199,15 +166,9 @@ async def get_telegram_status(
199
  "bot_info": bot_info
200
  }
201
 
202
- except HTTPException:
203
- raise
204
  except Exception as e:
205
- logger.error(
206
- "Failed to get Telegram bot status",
207
- error=str(e),
208
- exc_info=True
209
- )
210
- raise
211
 
212
 
213
  @router.delete("/telegram/disconnect")
@@ -215,17 +176,15 @@ async def disconnect_telegram_bot(
215
  current_user: User = Depends(get_current_user),
216
  session = Depends(get_session)
217
  ):
218
- """Disconnect Telegram bot from authenticated user's tenant account."""
219
  try:
220
- # Use authenticated user's tenant_id (prevents tenant isolation breach)
221
  tenant_id = current_user.tenant_id
222
 
223
  tenant = await session.get(Tenant, tenant_id)
224
  if not tenant:
225
  raise HTTPException(status_code=404, detail="Tenant not found")
226
 
227
- # Remove webhook from Telegram
228
- if tenant.telegram_bot_token and tenant.telegram_bot_token.strip():
229
  try:
230
  async with httpx.AsyncClient(timeout=10.0) as client:
231
  await client.post(
@@ -233,203 +192,18 @@ async def disconnect_telegram_bot(
233
  json={"drop_pending_updates": True}
234
  )
235
  except:
236
- pass # Continue even if webhook deletion fails
237
 
238
- # Clear bot token in database
239
  tenant.telegram_bot_token = None
240
  tenant.webhook_url = None
241
  session.add(tenant)
242
  await session.commit()
243
 
244
- return {
245
- "ok": True,
246
- "status": "disconnected",
247
- }
248
-
249
- except HTTPException:
250
- raise
251
- except Exception as e:
252
- logger.error(
253
- "Failed to disconnect Telegram bot",
254
- error=str(e),
255
- exc_info=True
256
- )
257
- raise
258
-
259
-
260
- @router.post("/meta/{channel}/connect", response_model=MetaChannelResponse)
261
- async def connect_meta_channel(
262
- channel: str,
263
- request: MetaChannelConnectRequest,
264
- current_user: User = Depends(get_current_user),
265
- session = Depends(get_session)
266
- ):
267
- """
268
- Connect WhatsApp or Instagram channel to authenticated user's tenant account.
269
-
270
- Args:
271
- channel: 'whatsapp' or 'instagram'
272
- request: Channel configuration (access_token, phone_number_id/page_id, verify_token)
273
- """
274
- try:
275
- # Use authenticated user's tenant_id (prevents tenant isolation breach)
276
- tenant_id = current_user.tenant_id
277
-
278
- # Validate channel
279
- if channel not in ["whatsapp"]:
280
- raise HTTPException(status_code=400, detail=f"Invalid channel: {channel}. Only 'whatsapp' is supported.")
281
-
282
- # Get tenant
283
- tenant = await session.get(Tenant, tenant_id)
284
- if not tenant:
285
- raise HTTPException(status_code=404, detail="Tenant not found")
286
-
287
- # Validate required fields
288
- if not request.access_token or not request.verify_token:
289
- raise HTTPException(
290
- status_code=400,
291
- detail="Access Token и Verify Token обязательны"
292
- )
293
-
294
- if channel == "whatsapp" and not request.phone_number_id:
295
- raise HTTPException(
296
- status_code=400,
297
- detail="Phone Number ID обязателен для WhatsApp"
298
- )
299
-
300
- # Construct webhook URL
301
- webhook_base = settings.TELEGRAM_WEBHOOK_URL or "https://your-domain.com"
302
- # Remove trailing /api/v1 to avoid duplication
303
- webhook_base = webhook_base.rstrip('/').replace('/api/v1', '')
304
- webhook_url = f"{webhook_base}/api/v1/webhook/meta/{channel}/{tenant_id}"
305
-
306
- # Build config object
307
- config = {
308
- "access_token": request.access_token.strip(),
309
- "verify_token": request.verify_token.strip(),
310
- "phone_number_id": request.phone_number_id.strip()
311
- }
312
-
313
- # Update tenant config
314
- config_field = f"{channel}_config"
315
- setattr(tenant, config_field, config)
316
-
317
- session.add(tenant)
318
- await session.commit()
319
-
320
- return MetaChannelResponse(
321
- ok=True,
322
- status="connected",
323
- webhook_url=webhook_url,
324
- message=f"{channel.capitalize()} успешно подключен! Настройте Webhook в Meta Developers."
325
- )
326
 
327
- except HTTPException:
328
- raise
329
  except Exception as e:
330
- logger.error(
331
- "Failed to connect Meta channel",
332
- channel=channel,
333
- error=str(e),
334
- exc_info=True
335
- )
336
- raise
337
-
338
-
339
- @router.get("/meta/{channel}/status")
340
- async def get_meta_channel_status(
341
- channel: str,
342
- current_user: User = Depends(get_current_user),
343
- session = Depends(get_session)
344
- ):
345
- """Get Meta channel connection status for authenticated user's tenant."""
346
- try:
347
- # Use authenticated user's tenant_id (prevents tenant isolation breach)
348
- tenant_id = current_user.tenant_id
349
-
350
- if channel not in ["whatsapp"]:
351
- raise HTTPException(status_code=400, detail=f"Invalid channel: {channel}")
352
-
353
- tenant = await session.get(Tenant, tenant_id)
354
- if not tenant:
355
- raise HTTPException(status_code=404, detail="Tenant not found")
356
-
357
- config_field = f"{channel}_config"
358
- config = getattr(tenant, config_field)
359
-
360
- is_connected = bool(config and isinstance(config, dict) and config.get("access_token"))
361
-
362
- webhook_url = None
363
- if is_connected:
364
- webhook_base = settings.TELEGRAM_WEBHOOK_URL or "https://your-domain.com"
365
- # Remove trailing /api/v1 to avoid duplication
366
- webhook_base = webhook_base.rstrip('/').replace('/api/v1', '')
367
- webhook_url = f"{webhook_base}/api/v1/webhook/meta/{channel}/{tenant_id}"
368
-
369
- return {
370
- "ok": True,
371
- "connected": is_connected,
372
- "webhook_url": webhook_url,
373
- "config": {
374
- "has_access_token": bool(config and config.get("access_token")),
375
- "has_verify_token": bool(config and config.get("verify_token")),
376
- "phone_number_id": config.get("phone_number_id") if config else None
377
- } if config else None
378
- }
379
-
380
- except HTTPException:
381
- raise
382
- except Exception as e:
383
- logger.error(
384
- "Failed to get Meta channel status",
385
- channel=channel,
386
- error=str(e),
387
- exc_info=True
388
- )
389
- raise
390
-
391
-
392
- @router.delete("/meta/{channel}/disconnect")
393
- async def disconnect_meta_channel(
394
- channel: str,
395
- current_user: User = Depends(get_current_user),
396
- session = Depends(get_session)
397
- ):
398
- """Disconnect Meta channel from authenticated user's tenant account."""
399
- try:
400
- # Use authenticated user's tenant_id (prevents tenant isolation breach)
401
- tenant_id = current_user.tenant_id
402
-
403
- if channel not in ["whatsapp"]:
404
- raise HTTPException(status_code=400, detail=f"Invalid channel: {channel}")
405
-
406
- tenant = await session.get(Tenant, tenant_id)
407
- if not tenant:
408
- raise HTTPException(status_code=404, detail="Tenant not found")
409
-
410
- # Clear config
411
- config_field = f"{channel}_config"
412
- setattr(tenant, config_field, None)
413
-
414
- session.add(tenant)
415
- await session.commit()
416
-
417
- return {
418
- "ok": True,
419
- "status": "disconnected",
420
- "message": f"{channel.capitalize()} успешно отключен"
421
- }
422
-
423
- except HTTPException:
424
- raise
425
- except Exception as e:
426
- logger.error(
427
- "Failed to disconnect Meta channel",
428
- channel=channel,
429
- error=str(e),
430
- exc_info=True
431
- )
432
- raise
433
 
434
 
435
  # ==================== LINKEDIN ENDPOINTS ====================
@@ -441,9 +215,7 @@ async def connect_linkedin(
441
  session = Depends(get_session)
442
  ):
443
  """
444
- Connect LinkedIn channel to authenticated user's tenant account.
445
-
446
- LinkedIn Messaging API integration.
447
  """
448
  try:
449
  tenant_id = current_user.tenant_id
@@ -452,49 +224,46 @@ async def connect_linkedin(
452
  if not tenant:
453
  raise HTTPException(status_code=404, detail="Tenant not found")
454
 
455
- # Validate required fields
456
  if not request.access_token or not request.organization_id:
457
  raise HTTPException(
458
  status_code=400,
459
  detail="Access Token и Organization ID обязательны"
460
  )
 
 
 
 
 
 
 
 
 
 
 
 
461
 
462
- # Build config object
463
  config = {
464
  "access_token": request.access_token.strip(),
465
  "organization_id": request.organization_id.strip(),
466
- "verify_token": request.verify_token.strip()
 
467
  }
468
 
469
- # Update tenant config
470
  tenant.linkedin_config = config
471
-
472
  session.add(tenant)
473
  await session.commit()
474
 
475
- webhook_base = settings.TELEGRAM_WEBHOOK_URL or "https://your-domain.com"
476
- webhook_base = webhook_base.rstrip('/').replace('/api/v1', '')
477
- webhook_url = f"{webhook_base}/api/v1/webhook/linkedin/{tenant_id}"
478
-
479
  return {
480
  "ok": True,
481
  "status": "connected",
482
- "webhook_url": webhook_url,
483
- "message": "LinkedIn успешно подключен! Настройте Webhook в LinkedIn Developers."
484
  }
485
 
486
  except HTTPException:
487
  raise
488
  except Exception as e:
489
- logger.error(
490
- "Failed to connect LinkedIn",
491
- error=str(e),
492
- exc_info=True
493
- )
494
- raise HTTPException(
495
- status_code=500,
496
- detail=f"Ошибка подключения LinkedIn: {str(e)}"
497
- )
498
 
499
 
500
  @router.get("/linkedin/status")
@@ -502,7 +271,7 @@ async def get_linkedin_status(
502
  current_user: User = Depends(get_current_user),
503
  session = Depends(get_session)
504
  ):
505
- """Get LinkedIn connection status for authenticated user's tenant."""
506
  try:
507
  tenant_id = current_user.tenant_id
508
 
@@ -513,31 +282,18 @@ async def get_linkedin_status(
513
  config = tenant.linkedin_config
514
  is_connected = bool(config and isinstance(config, dict) and config.get("access_token"))
515
 
516
- webhook_url = None
517
- if is_connected:
518
- webhook_base = settings.TELEGRAM_WEBHOOK_URL or "https://your-domain.com"
519
- webhook_base = webhook_base.rstrip('/').replace('/api/v1', '')
520
- webhook_url = f"{webhook_base}/api/v1/webhook/linkedin/{tenant_id}"
521
-
522
  return {
523
  "ok": True,
524
  "connected": is_connected,
525
- "webhook_url": webhook_url,
526
  "config": {
527
- "has_access_token": bool(config and config.get("access_token")),
528
- "organization_id": config.get("organization_id") if config else None
529
  } if config else None
530
  }
531
 
532
- except HTTPException:
533
- raise
534
  except Exception as e:
535
- logger.error(
536
- "Failed to get LinkedIn status",
537
- error=str(e),
538
- exc_info=True
539
- )
540
- raise
541
 
542
 
543
  @router.delete("/linkedin/disconnect")
@@ -545,7 +301,7 @@ async def disconnect_linkedin(
545
  current_user: User = Depends(get_current_user),
546
  session = Depends(get_session)
547
  ):
548
- """Disconnect LinkedIn from authenticated user's tenant account."""
549
  try:
550
  tenant_id = current_user.tenant_id
551
 
@@ -553,30 +309,18 @@ async def disconnect_linkedin(
553
  if not tenant:
554
  raise HTTPException(status_code=404, detail="Tenant not found")
555
 
556
- # Clear config
557
  tenant.linkedin_config = None
558
-
559
  session.add(tenant)
560
  await session.commit()
561
 
562
- return {
563
- "ok": True,
564
- "status": "disconnected",
565
- "message": "LinkedIn успешно отключен"
566
- }
567
 
568
- except HTTPException:
569
- raise
570
  except Exception as e:
571
- logger.error(
572
- "Failed to disconnect LinkedIn",
573
- error=str(e),
574
- exc_info=True
575
- )
576
- raise
577
 
578
 
579
- # ==================== WhatsApp QR (Grey API) ====================
580
 
581
  @router.post("/whatsapp/qr/generate")
582
  async def generate_whatsapp_qr(
@@ -584,12 +328,11 @@ async def generate_whatsapp_qr(
584
  session = Depends(get_session)
585
  ):
586
  """
587
- Generate QR code for WhatsApp connection (simple user-friendly method)
588
  """
589
  try:
590
  tenant_id = str(current_user.tenant_id)
591
 
592
- # Generate QR code
593
  qr_url = await whatsapp_qr_service.generate_qr(tenant_id)
594
 
595
  return {
@@ -599,15 +342,8 @@ async def generate_whatsapp_qr(
599
  }
600
 
601
  except Exception as e:
602
- logger.error(
603
- "Failed to generate WhatsApp QR",
604
- error=str(e),
605
- exc_info=True
606
- )
607
- raise HTTPException(
608
- status_code=500,
609
- detail=f"QR generation error: {str(e)}"
610
- )
611
 
612
 
613
  @router.get("/whatsapp/qr/status")
@@ -616,12 +352,11 @@ async def get_whatsapp_qr_status(
616
  session = Depends(get_session)
617
  ):
618
  """
619
- Check WhatsApp QR connection status
620
  """
621
  try:
622
  tenant_id = str(current_user.tenant_id)
623
 
624
- # Check session status
625
  status = await whatsapp_qr_service.check_session(tenant_id)
626
 
627
  return {
@@ -632,15 +367,8 @@ async def get_whatsapp_qr_status(
632
  }
633
 
634
  except Exception as e:
635
- logger.error(
636
- "Failed to check WhatsApp QR status",
637
- error=str(e),
638
- exc_info=True
639
- )
640
- raise HTTPException(
641
- status_code=500,
642
- detail=f"Status check error: {str(e)}"
643
- )
644
 
645
 
646
  @router.post("/whatsapp/qr/disconnect")
@@ -649,27 +377,19 @@ async def disconnect_whatsapp_qr(
649
  session = Depends(get_session)
650
  ):
651
  """
652
- Disconnect WhatsApp QR session
653
  """
654
  try:
655
  tenant_id = str(current_user.tenant_id)
656
 
657
- # Disconnect session
658
  await whatsapp_qr_service.disconnect(tenant_id)
659
 
660
  return {
661
  "ok": True,
662
  "status": "disconnected",
663
- "message": "WhatsApp QR disconnected successfully"
664
  }
665
 
666
  except Exception as e:
667
- logger.error(
668
- "Failed to disconnect WhatsApp QR",
669
- error=str(e),
670
- exc_info=True
671
- )
672
- raise HTTPException(
673
- status_code=500,
674
- detail=f"Disconnect error: {str(e)}"
675
- )
 
1
  """
2
+ Channels API - Telegram, WhatsApp (Evolution API), LinkedIn Connection
3
  """
4
  from fastapi import APIRouter, HTTPException, Depends
5
  from pydantic import BaseModel
 
13
  from app.models import User
14
  from app.api.deps import get_current_user
15
  from app.services.whatsapp_qr import whatsapp_qr_service
16
+ from app.services.linkedin_service import linkedin_service
17
 
18
  logger = get_logger(__name__)
19
  router = APIRouter(prefix="/channels", tags=["Channels"])
 
32
  message: str
33
 
34
 
 
 
 
 
 
 
 
35
  class LinkedInConnectRequest(BaseModel):
36
  """LinkedIn channel connection request."""
37
  access_token: str
 
39
  verify_token: str
40
 
41
 
 
 
 
 
 
 
 
 
42
  @router.post("/telegram/connect", response_model=TelegramConnectResponse)
43
  async def connect_telegram_bot(
44
  request: TelegramConnectRequest,
 
47
  ):
48
  """
49
  Connect Telegram bot to authenticated user's tenant account.
 
 
 
 
 
 
50
  """
51
  try:
 
52
  tenant_id = current_user.tenant_id
53
 
 
54
  tenant = await session.get(Tenant, tenant_id)
55
  if not tenant:
56
  raise HTTPException(status_code=404, detail="Tenant not found")
57
 
58
  bot_token = request.bot_token.strip()
59
 
 
60
  if not bot_token or ":" not in bot_token:
61
  raise HTTPException(
62
  status_code=400,
63
  detail="Неверный формат токена. Токен должен быть вида: 123456:ABC-DEF..."
64
  )
65
 
 
66
  webhook_base = settings.TELEGRAM_WEBHOOK_URL or "https://your-domain.com"
67
  webhook_url = f"{webhook_base}/webhook/telegram/{tenant_id}"
68
 
 
69
  telegram_api_url = f"https://api.telegram.org/bot{bot_token}/setWebhook"
70
 
71
  async with httpx.AsyncClient(timeout=30.0) as client:
 
72
  bot_info_response = await client.get(
73
  f"https://api.telegram.org/bot{bot_token}/getMe"
74
  )
 
88
 
89
  bot_username = bot_data.get("result", {}).get("username", "Unknown")
90
 
 
91
  webhook_response = await client.post(
92
  telegram_api_url,
93
  json={
 
106
  detail=f"Ошибка при установке webhook: {error_description}"
107
  )
108
 
 
109
  tenant.telegram_bot_token = bot_token
110
  tenant.webhook_url = webhook_url
111
  session.add(tenant)
 
121
  except HTTPException:
122
  raise
123
  except Exception as e:
124
+ logger.error(f"Telegram connection error: {e}")
125
+ raise HTTPException(status_code=500, detail=f"Ошибка подключения: {str(e)}")
 
 
 
126
 
127
 
128
  @router.get("/telegram/status")
 
130
  current_user: User = Depends(get_current_user),
131
  session = Depends(get_session)
132
  ):
133
+ """Get current Telegram bot connection status."""
134
  try:
 
135
  tenant_id = current_user.tenant_id
136
 
137
  tenant = await session.get(Tenant, tenant_id)
 
142
 
143
  bot_info = None
144
  if has_token:
 
145
  try:
146
  async with httpx.AsyncClient(timeout=10.0) as client:
147
  response = await client.get(
 
166
  "bot_info": bot_info
167
  }
168
 
 
 
169
  except Exception as e:
170
+ logger.error(f"Failed to get Telegram status: {e}")
171
+ raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
172
 
173
 
174
  @router.delete("/telegram/disconnect")
 
176
  current_user: User = Depends(get_current_user),
177
  session = Depends(get_session)
178
  ):
179
+ """Disconnect Telegram bot."""
180
  try:
 
181
  tenant_id = current_user.tenant_id
182
 
183
  tenant = await session.get(Tenant, tenant_id)
184
  if not tenant:
185
  raise HTTPException(status_code=404, detail="Tenant not found")
186
 
187
+ if tenant.telegram_bot_token:
 
188
  try:
189
  async with httpx.AsyncClient(timeout=10.0) as client:
190
  await client.post(
 
192
  json={"drop_pending_updates": True}
193
  )
194
  except:
195
+ pass
196
 
 
197
  tenant.telegram_bot_token = None
198
  tenant.webhook_url = None
199
  session.add(tenant)
200
  await session.commit()
201
 
202
+ return {"ok": True, "status": "disconnected"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
 
 
204
  except Exception as e:
205
+ logger.error(f"Failed to disconnect Telegram: {e}")
206
+ raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
 
208
 
209
  # ==================== LINKEDIN ENDPOINTS ====================
 
215
  session = Depends(get_session)
216
  ):
217
  """
218
+ Connect LinkedIn channel.
 
 
219
  """
220
  try:
221
  tenant_id = current_user.tenant_id
 
224
  if not tenant:
225
  raise HTTPException(status_code=404, detail="Tenant not found")
226
 
 
227
  if not request.access_token or not request.organization_id:
228
  raise HTTPException(
229
  status_code=400,
230
  detail="Access Token и Organization ID обязательны"
231
  )
232
+
233
+ # Verify credentials with LinkedIn Service
234
+ org_info = await linkedin_service.get_organization_info(
235
+ request.access_token,
236
+ request.organization_id
237
+ )
238
+
239
+ if not org_info:
240
+ raise HTTPException(
241
+ status_code=400,
242
+ detail="Не удалось верифицировать Organization ID или Access Token"
243
+ )
244
 
 
245
  config = {
246
  "access_token": request.access_token.strip(),
247
  "organization_id": request.organization_id.strip(),
248
+ "verify_token": request.verify_token.strip(),
249
+ "org_name": org_info.get("vanityName", "LinkedIn Page")
250
  }
251
 
 
252
  tenant.linkedin_config = config
 
253
  session.add(tenant)
254
  await session.commit()
255
 
 
 
 
 
256
  return {
257
  "ok": True,
258
  "status": "connected",
259
+ "message": "LinkedIn успешно подключен!"
 
260
  }
261
 
262
  except HTTPException:
263
  raise
264
  except Exception as e:
265
+ logger.error(f"Failed to connect LinkedIn: {e}")
266
+ raise HTTPException(status_code=500, detail=f"Ошибка подключения LinkedIn: {str(e)}")
 
 
 
 
 
 
 
267
 
268
 
269
  @router.get("/linkedin/status")
 
271
  current_user: User = Depends(get_current_user),
272
  session = Depends(get_session)
273
  ):
274
+ """Get LinkedIn connection status."""
275
  try:
276
  tenant_id = current_user.tenant_id
277
 
 
282
  config = tenant.linkedin_config
283
  is_connected = bool(config and isinstance(config, dict) and config.get("access_token"))
284
 
 
 
 
 
 
 
285
  return {
286
  "ok": True,
287
  "connected": is_connected,
 
288
  "config": {
289
+ "organization_id": config.get("organization_id"),
290
+ "org_name": config.get("org_name")
291
  } if config else None
292
  }
293
 
 
 
294
  except Exception as e:
295
+ logger.error(f"Failed to get LinkedIn status: {e}")
296
+ raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
297
 
298
 
299
  @router.delete("/linkedin/disconnect")
 
301
  current_user: User = Depends(get_current_user),
302
  session = Depends(get_session)
303
  ):
304
+ """Disconnect LinkedIn."""
305
  try:
306
  tenant_id = current_user.tenant_id
307
 
 
309
  if not tenant:
310
  raise HTTPException(status_code=404, detail="Tenant not found")
311
 
 
312
  tenant.linkedin_config = None
 
313
  session.add(tenant)
314
  await session.commit()
315
 
316
+ return {"ok": True, "status": "disconnected", "message": "LinkedIn успешно отключен"}
 
 
 
 
317
 
 
 
318
  except Exception as e:
319
+ logger.error(f"Failed to disconnect LinkedIn: {e}")
320
+ raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
321
 
322
 
323
+ # ==================== WhatsApp QR (Evolution API) ====================
324
 
325
  @router.post("/whatsapp/qr/generate")
326
  async def generate_whatsapp_qr(
 
328
  session = Depends(get_session)
329
  ):
330
  """
331
+ Generate QR code for WhatsApp connection via Evolution API.
332
  """
333
  try:
334
  tenant_id = str(current_user.tenant_id)
335
 
 
336
  qr_url = await whatsapp_qr_service.generate_qr(tenant_id)
337
 
338
  return {
 
342
  }
343
 
344
  except Exception as e:
345
+ logger.error(f"Failed to generate WhatsApp QR: {e}")
346
+ raise HTTPException(status_code=500, detail=f"QR generation error: {str(e)}")
 
 
 
 
 
 
 
347
 
348
 
349
  @router.get("/whatsapp/qr/status")
 
352
  session = Depends(get_session)
353
  ):
354
  """
355
+ Check WhatsApp QR connection status.
356
  """
357
  try:
358
  tenant_id = str(current_user.tenant_id)
359
 
 
360
  status = await whatsapp_qr_service.check_session(tenant_id)
361
 
362
  return {
 
367
  }
368
 
369
  except Exception as e:
370
+ logger.error(f"Failed to check WhatsApp QR status: {e}")
371
+ raise HTTPException(status_code=500, detail=f"Status check error: {str(e)}")
 
 
 
 
 
 
 
372
 
373
 
374
  @router.post("/whatsapp/qr/disconnect")
 
377
  session = Depends(get_session)
378
  ):
379
  """
380
+ Disconnect WhatsApp QR session.
381
  """
382
  try:
383
  tenant_id = str(current_user.tenant_id)
384
 
 
385
  await whatsapp_qr_service.disconnect(tenant_id)
386
 
387
  return {
388
  "ok": True,
389
  "status": "disconnected",
390
+ "message": "WhatsApp disconnected successfully"
391
  }
392
 
393
  except Exception as e:
394
+ logger.error(f"Failed to disconnect WhatsApp QR: {e}")
395
+ raise HTTPException(status_code=500, detail=f"Disconnect error: {str(e)}")
 
 
 
 
 
 
 
backend/app/api/{meta_webhooks.py → evolution_webhook.py} RENAMED
@@ -1,9 +1,9 @@
1
  """
2
- Meta (WhatsApp & Instagram) Webhook Handlers.
3
- Handles webhook verification and incoming messages from Meta Cloud API.
4
  """
5
 
6
- from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, Query
7
  from sqlalchemy.ext.asyncio import AsyncSession
8
  from sqlalchemy import select
9
  from uuid import UUID
@@ -14,86 +14,14 @@ from app.core.database import get_async_session
14
  from app.models.tenant import Tenant
15
  from app.models.lead import Lead, Message, Conversation
16
  from app.services.ai_core import get_ai_core
17
- from fastapi import Depends
18
 
 
 
19
 
20
- router = APIRouter(prefix="/webhook/meta", tags=["Meta Webhooks"])
21
 
22
-
23
- @router.get("/{channel}/{tenant_id}")
24
- async def verify_meta_webhook(
25
- channel: str,
26
- tenant_id: UUID,
27
- hub_mode: str = Query(None, alias="hub.mode"),
28
- hub_verify_token: str = Query(None, alias="hub.verify_token"),
29
- hub_challenge: str = Query(None, alias="hub.challenge"),
30
- session: AsyncSession = Depends(get_async_session)
31
- ):
32
- """
33
- Webhook Verification Endpoint (GET).
34
- Meta sends this request to verify webhook URL ownership.
35
-
36
- Args:
37
- channel: 'whatsapp' or 'instagram'
38
- tenant_id: Tenant UUID
39
- hub.mode: Should be 'subscribe'
40
- hub.verify_token: Token to verify (must match stored token)
41
- hub.challenge: Challenge string to echo back
42
-
43
- Returns:
44
- hub.challenge integer if verification succeeds
45
- """
46
-
47
- print(f"🔐 Meta Webhook Verification Request:")
48
- print(f" Channel: {channel}")
49
- print(f" Tenant: {tenant_id}")
50
- print(f" Mode: {hub_mode}")
51
- print(f" Verify Token: {hub_verify_token}")
52
-
53
- # 1. Validate channel
54
- if channel not in ["whatsapp", "instagram"]:
55
- raise HTTPException(status_code=400, detail=f"Invalid channel: {channel}")
56
-
57
- # 2. Validate mode
58
- if hub_mode != "subscribe":
59
- raise HTTPException(status_code=400, detail="Invalid hub.mode")
60
-
61
- # 3. Get tenant
62
- tenant = await session.get(Tenant, tenant_id)
63
- if not tenant:
64
- raise HTTPException(status_code=404, detail="Tenant not found")
65
-
66
- # 4. Get stored verify token
67
- config_field = f"{channel}_config"
68
- config = getattr(tenant, config_field)
69
-
70
- if not config or not isinstance(config, dict):
71
- raise HTTPException(
72
- status_code=400,
73
- detail=f"{channel.capitalize()} not configured for this tenant"
74
- )
75
-
76
- stored_verify_token = config.get("verify_token")
77
-
78
- if not stored_verify_token:
79
- raise HTTPException(
80
- status_code=400,
81
- detail=f"No verify_token configured for {channel}"
82
- )
83
-
84
- # 5. Verify token matches
85
- if hub_verify_token != stored_verify_token:
86
- print(f"❌ Token mismatch: {hub_verify_token} != {stored_verify_token}")
87
- raise HTTPException(status_code=403, detail="Invalid verify_token")
88
-
89
- # 6. Return challenge (as integer)
90
- print(f"✅ Webhook verified successfully for {channel}")
91
- return int(hub_challenge)
92
-
93
-
94
- @router.post("/{channel}/{tenant_id}")
95
- async def handle_meta_webhook(
96
- channel: str,
97
  tenant_id: UUID,
98
  request: Request,
99
  background_tasks: BackgroundTasks,
@@ -101,9 +29,7 @@ async def handle_meta_webhook(
101
  ):
102
  """
103
  Webhook Message Handler (POST).
104
- Receives incoming messages from WhatsApp or Instagram.
105
-
106
- Normalizes the message structure and processes it through AI.
107
  """
108
 
109
  # 1. Parse incoming webhook data
@@ -112,165 +38,87 @@ async def handle_meta_webhook(
112
  except Exception as e:
113
  raise HTTPException(status_code=400, detail=f"Invalid JSON: {str(e)}")
114
 
115
- print(f"\n📩 {channel.upper()} Webhook Received:")
116
- print(f" Tenant: {tenant_id}")
117
- print(f" Data: {data}")
118
 
119
- # 2. Validate channel
120
- if channel not in ["whatsapp", "instagram"]:
121
- raise HTTPException(status_code=400, detail=f"Invalid channel: {channel}")
122
-
123
- # 3. Get tenant
124
  tenant = await session.get(Tenant, tenant_id)
125
  if not tenant:
126
  raise HTTPException(status_code=404, detail="Tenant not found")
127
 
128
- # 4. Extract message based on channel
129
  try:
130
- if channel == "whatsapp":
131
- message_data = extract_whatsapp_message(data)
132
- else: # instagram
133
- message_data = extract_instagram_message(data)
134
 
135
  if not message_data:
136
  # No message to process (could be status update, etc.)
137
  return {"status": "ok", "message": "No message to process"}
138
 
139
  except Exception as e:
140
- print(f"❌ Error extracting message: {e}")
141
  raise HTTPException(status_code=400, detail=f"Failed to parse message: {str(e)}")
142
 
143
- # 5. Process message in background
144
  background_tasks.add_task(
145
- process_meta_message,
146
  tenant_id=tenant.id,
147
- channel=channel,
148
  message_data=message_data
149
  )
150
 
151
  return {"status": "ok"}
152
 
153
 
154
- def extract_whatsapp_message(data: dict) -> dict | None:
155
  """
156
- Extract message from WhatsApp webhook payload.
157
-
158
- Structure: entry[0].changes[0].value.messages[0]
159
  """
160
  try:
161
- entry = data.get("entry", [])[0]
162
- changes = entry.get("changes", [])[0]
163
- value = changes.get("value", {})
 
 
 
 
164
 
165
- messages = value.get("messages", [])
166
- if not messages:
167
  return None
 
 
 
 
168
 
169
- msg = messages[0]
 
170
 
 
 
 
 
 
 
 
 
 
 
171
  return {
172
- "sender_id": msg.get("from"), # Phone number
173
- "message_id": msg.get("id"),
174
- "text": msg.get("text", {}).get("body", ""),
175
- "timestamp": msg.get("timestamp")
176
  }
177
 
178
  except (IndexError, KeyError) as e:
179
- print(f"⚠️ WhatsApp payload parsing error: {e}")
180
- return None
181
-
182
-
183
- def extract_instagram_message(data: dict) -> dict | None:
184
- """
185
- Extract message from Instagram webhook payload.
186
-
187
- Supports two formats:
188
- 1. Real events: entry[0].messaging[0]
189
- 2. Test events: entry[0].changes[0].value
190
- """
191
- try:
192
- entry = data.get("entry", [])[0]
193
-
194
- # Try real event format first (messaging)
195
- messaging_list = entry.get("messaging", [])
196
- if messaging_list:
197
- messaging = messaging_list[0]
198
-
199
- # Try to get regular message first
200
- message = messaging.get("message", {})
201
-
202
- # Skip echo messages (messages sent by our bot)
203
- if message.get("is_echo"):
204
- print("⏭️ Skipping echo message (sent by our bot)")
205
- return None
206
-
207
- # If no message, try message_edit event
208
- if not message:
209
- message_edit = messaging.get("message_edit", {})
210
- if message_edit:
211
- # For message_edit, text is not included in webhook
212
- print(f"⚠️ Received message_edit event (mid: {message_edit.get('mid')})")
213
- print(f" Text is not available in message_edit webhooks")
214
- print(f" User needs to send NEW message, not edit existing one")
215
- return None # Skip message_edit for now
216
-
217
- if not message or not message.get("mid"):
218
- return None
219
-
220
- return {
221
- "sender_id": messaging.get("sender", {}).get("id"),
222
- "message_id": message.get("mid"),
223
- "text": message.get("text", ""),
224
- "timestamp": messaging.get("timestamp")
225
- }
226
-
227
- # Try test event format (changes)
228
- changes_list = entry.get("changes", [])
229
- if changes_list:
230
- change = changes_list[0]
231
- value = change.get("value", {})
232
- message = value.get("message", {})
233
-
234
- if not message or not message.get("mid"):
235
- return None
236
-
237
- print("📝 Test event received (using 'changes' format)")
238
- return {
239
- "sender_id": value.get("sender", {}).get("id"),
240
- "message_id": message.get("mid"),
241
- "text": message.get("text", ""),
242
- "timestamp": value.get("timestamp")
243
- }
244
-
245
- print("⚠️ Unknown Instagram webhook format")
246
- return None
247
-
248
- except (IndexError, KeyError) as e:
249
- print(f"⚠️ Instagram payload parsing error: {e}")
250
- import traceback
251
- traceback.print_exc()
252
  return None
253
 
254
 
255
- async def process_meta_message(
256
  tenant_id: UUID,
257
- channel: str,
258
  message_data: dict
259
  ):
260
  """
261
- Background task: Process incoming Meta message.
262
- Creates its own database session to avoid lifecycle issues.
263
-
264
- **ANTI-SPAM DEBOUNCING:**
265
- - Waits 4 seconds before processing
266
- - Checks if user sent newer messages during wait
267
- - Only processes if this is still the latest message (prevents spam)
268
-
269
- Steps:
270
- 1. Save user message to DB
271
- 2. Wait 4 seconds (debouncing)
272
- 3. Check for newer messages
273
- 4. Generate and send AI response (only if no newer messages)
274
  """
275
  from app.core.database import async_session_maker
276
  import asyncio
@@ -279,10 +127,9 @@ async def process_meta_message(
279
  text = message_data["text"]
280
 
281
  if not text:
282
- print("⚠️ Empty message, skipping")
283
  return
284
 
285
- print(f"🔄 Processing {channel} message from {sender_id}")
286
 
287
  # STEP 1: Save user message and get IDs
288
  user_message_id = None
@@ -294,13 +141,12 @@ async def process_meta_message(
294
  # Get tenant
295
  tenant = await session.get(Tenant, tenant_id)
296
  if not tenant:
297
- print(f"❌ Tenant {tenant_id} not found")
298
  return
299
 
300
  # Find or create Lead
301
  stmt = select(Lead).where(
302
  Lead.tenant_id == tenant.id,
303
- Lead.telegram_id == sender_id # Reuse this field for now
304
  )
305
  result = await session.execute(stmt)
306
  lead = result.scalar_one_or_none()
@@ -308,14 +154,13 @@ async def process_meta_message(
308
  if not lead:
309
  lead = Lead(
310
  tenant_id=tenant.id,
311
- name=f"{channel.capitalize()} User {sender_id[:8]}",
312
  telegram_id=sender_id,
313
  status="NEW",
314
  processing_status="idle"
315
  )
316
  session.add(lead)
317
  await session.flush()
318
- print(f"✅ New lead created: {lead.id}")
319
 
320
  lead_id = lead.id
321
 
@@ -332,13 +177,12 @@ async def process_meta_message(
332
  conversation = Conversation(
333
  tenant_id=tenant.id,
334
  lead_id=lead.id,
335
- channel=channel,
336
  is_active=True,
337
  started_at=datetime.utcnow()
338
  )
339
  session.add(conversation)
340
  await session.flush()
341
- print(f"✅ New conversation created: {conversation.id}")
342
 
343
  conversation_id = conversation.id
344
 
@@ -355,18 +199,15 @@ async def process_meta_message(
355
  lead.last_message_at = datetime.utcnow()
356
  lead.last_activity_at = datetime.utcnow()
357
  lead.first_message_at = lead.first_message_at or datetime.utcnow()
358
- lead.processing_status = "analyzing" # Use 'analyzing' instead of 'waiting'
359
  session.add(lead)
360
 
361
  await session.commit()
362
  await session.refresh(user_message)
363
  user_message_id = user_message.id
364
- print(f"💬 User message saved: {user_message_id}")
365
 
366
  except Exception as e:
367
- print(f"❌ Error saving message: {e}")
368
- import traceback
369
- traceback.print_exc()
370
  return
371
 
372
  # STEP 2: Debouncing delay (4 seconds)
@@ -384,9 +225,7 @@ async def process_meta_message(
384
  latest_user_message = result.scalar_one_or_none()
385
 
386
  if latest_user_message and latest_user_message.id != user_message_id:
387
- # User sent a newer message during debounce period
388
- print(f"⏭️ Debouncing: Skipping old message {user_message_id}")
389
- print(f" Latest message: {latest_user_message.id}")
390
 
391
  # Reset status to idle
392
  lead = await session.get(Lead, lead_id)
@@ -394,23 +233,19 @@ async def process_meta_message(
394
  lead.processing_status = "idle"
395
  session.add(lead)
396
  await session.commit()
397
- return # Abort - let newer message's task handle the reply
398
 
399
  except Exception as e:
400
- print(f"❌ Error checking for newer messages: {e}")
401
- import traceback
402
- traceback.print_exc()
403
  return
404
 
405
- # STEP 4: Generate AI response (only if still the latest message)
406
  async with async_session_maker() as session:
407
  try:
408
- # Get tenant, lead, conversation
409
  tenant = await session.get(Tenant, tenant_id)
410
  lead = await session.get(Lead, lead_id)
411
 
412
  if not tenant or not lead:
413
- print(f"❌ Tenant or lead not found")
414
  return
415
 
416
  # Set generating status
@@ -425,8 +260,6 @@ async def process_meta_message(
425
  result = await session.execute(stmt)
426
  messages = list(result.scalars().all())
427
 
428
- print(f"🤖 Generating AI response ({len(messages)} messages in history)")
429
-
430
  # Get AI Core
431
  ai_core = get_ai_core()
432
 
@@ -456,24 +289,19 @@ async def process_meta_message(
456
  session.add(lead)
457
 
458
  await session.commit()
459
- await session.refresh(ai_message)
460
 
461
- print(f"🤖 AI response generated: {ai_message.id}")
462
-
463
- # Send response back to user
464
- await send_meta_message(
465
- tenant=tenant,
466
- channel=channel,
467
- recipient_id=sender_id,
468
- message_text=response["text"]
469
  )
470
 
471
- print(f"✅ {channel.capitalize()} message processing complete")
472
 
473
  except Exception as e:
474
- print(f"❌ Error processing {channel} message: {e}")
475
- import traceback
476
- traceback.print_exc()
477
 
478
  # Set error status
479
  try:
@@ -484,78 +312,3 @@ async def process_meta_message(
484
  await session.commit()
485
  except:
486
  pass
487
-
488
-
489
- async def send_meta_message(
490
- tenant: Tenant,
491
- channel: str,
492
- recipient_id: str,
493
- message_text: str
494
- ) -> bool:
495
- """
496
- Send message via Meta API (WhatsApp or Instagram).
497
-
498
- Returns:
499
- bool: True if successful, False otherwise
500
- """
501
- try:
502
- config_field = f"{channel}_config"
503
- config = getattr(tenant, config_field)
504
-
505
- if not config or not isinstance(config, dict):
506
- print(f"❌ {channel} not configured")
507
- return False
508
-
509
- access_token = config.get("access_token")
510
-
511
- if channel == "whatsapp":
512
- phone_number_id = config.get("phone_number_id")
513
- if not phone_number_id or not access_token:
514
- print("❌ WhatsApp credentials incomplete")
515
- return False
516
-
517
- url = f"https://graph.facebook.com/v17.0/{phone_number_id}/messages"
518
- payload = {
519
- "messaging_product": "whatsapp",
520
- "to": recipient_id,
521
- "type": "text",
522
- "text": {"body": message_text}
523
- }
524
-
525
- else: # instagram
526
- page_id = config.get("page_id")
527
- if not page_id or not access_token:
528
- print("❌ Instagram credentials incomplete")
529
- return False
530
-
531
- # Instagram uses /{ig-user-id}/messages
532
- # page_id is actually the IG user ID for Instagram Business Account
533
- url = f"https://graph.facebook.com/v18.0/{page_id}/messages"
534
- payload = {
535
- "recipient": {"id": recipient_id},
536
- "message": {"text": message_text}
537
- }
538
-
539
- headers = {
540
- "Authorization": f"Bearer {access_token}",
541
- "Content-Type": "application/json"
542
- }
543
-
544
- print(f"📤 Sending {channel} message to {recipient_id}")
545
-
546
- async with httpx.AsyncClient() as client:
547
- response = await client.post(url, json=payload, headers=headers, timeout=10.0)
548
-
549
- if response.status_code == 200:
550
- print(f"✅ {channel.capitalize()} message sent successfully")
551
- return True
552
- else:
553
- print(f"❌ {channel.capitalize()} API error: {response.status_code}")
554
- print(f" Response: {response.text}")
555
- return False
556
-
557
- except Exception as e:
558
- print(f"❌ Error sending {channel} message: {e}")
559
- import traceback
560
- traceback.print_exc()
561
- return False
 
1
  """
2
+ Evolution API Webhook Handler.
3
+ Handles incoming WhatsApp messages from Evolution API.
4
  """
5
 
6
+ from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, Depends
7
  from sqlalchemy.ext.asyncio import AsyncSession
8
  from sqlalchemy import select
9
  from uuid import UUID
 
14
  from app.models.tenant import Tenant
15
  from app.models.lead import Lead, Message, Conversation
16
  from app.services.ai_core import get_ai_core
17
+ from app.core.logging import get_logger
18
 
19
+ logger = get_logger(__name__)
20
+ router = APIRouter(prefix="/webhook/evolution", tags=["Evolution Webhooks"])
21
 
 
22
 
23
+ @router.post("/{tenant_id}")
24
+ async def handle_evolution_webhook(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  tenant_id: UUID,
26
  request: Request,
27
  background_tasks: BackgroundTasks,
 
29
  ):
30
  """
31
  Webhook Message Handler (POST).
32
+ Receives incoming messages from Evolution API (WhatsApp).
 
 
33
  """
34
 
35
  # 1. Parse incoming webhook data
 
38
  except Exception as e:
39
  raise HTTPException(status_code=400, detail=f"Invalid JSON: {str(e)}")
40
 
41
+ # logger.info(f"📩 Evolution Webhook Received for Tenant {tenant_id}", data=data)
 
 
42
 
43
+ # 2. Get tenant
 
 
 
 
44
  tenant = await session.get(Tenant, tenant_id)
45
  if not tenant:
46
  raise HTTPException(status_code=404, detail="Tenant not found")
47
 
48
+ # 3. Extract message
49
  try:
50
+ message_data = extract_evolution_message(data)
 
 
 
51
 
52
  if not message_data:
53
  # No message to process (could be status update, etc.)
54
  return {"status": "ok", "message": "No message to process"}
55
 
56
  except Exception as e:
57
+ logger.error(f"❌ Error extracting message: {e}")
58
  raise HTTPException(status_code=400, detail=f"Failed to parse message: {str(e)}")
59
 
60
+ # 4. Process message in background
61
  background_tasks.add_task(
62
+ process_evolution_message,
63
  tenant_id=tenant.id,
 
64
  message_data=message_data
65
  )
66
 
67
  return {"status": "ok"}
68
 
69
 
70
+ def extract_evolution_message(data: dict) -> dict | None:
71
  """
72
+ Extract message from Evolution API webhook payload.
 
 
73
  """
74
  try:
75
+ # Check event type
76
+ event_type = data.get("type")
77
+ if event_type != "messages.upsert":
78
+ return None
79
+
80
+ message_data = data.get("data", {})
81
+ key = message_data.get("key", {})
82
 
83
+ # Skip messages sent by me (fromMe=true)
84
+ if key.get("fromMe"):
85
  return None
86
+
87
+ # Get sender
88
+ remote_jid = key.get("remoteJid", "")
89
+ sender_id = remote_jid.split("@")[0] if "@" in remote_jid else remote_jid
90
 
91
+ # Get message content
92
+ message_content = message_data.get("message", {})
93
 
94
+ # Text message
95
+ text = ""
96
+ if "conversation" in message_content:
97
+ text = message_content["conversation"]
98
+ elif "extendedTextMessage" in message_content:
99
+ text = message_content["extendedTextMessage"].get("text", "")
100
+
101
+ if not text:
102
+ return None
103
+
104
  return {
105
+ "sender_id": sender_id,
106
+ "message_id": key.get("id"),
107
+ "text": text,
108
+ "timestamp": message_data.get("messageTimestamp")
109
  }
110
 
111
  except (IndexError, KeyError) as e:
112
+ logger.error(f"⚠️ Evolution payload parsing error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  return None
114
 
115
 
116
+ async def process_evolution_message(
117
  tenant_id: UUID,
 
118
  message_data: dict
119
  ):
120
  """
121
+ Background task: Process incoming WhatsApp message.
 
 
 
 
 
 
 
 
 
 
 
 
122
  """
123
  from app.core.database import async_session_maker
124
  import asyncio
 
127
  text = message_data["text"]
128
 
129
  if not text:
 
130
  return
131
 
132
+ logger.info(f"🔄 Processing WhatsApp message from {sender_id}")
133
 
134
  # STEP 1: Save user message and get IDs
135
  user_message_id = None
 
141
  # Get tenant
142
  tenant = await session.get(Tenant, tenant_id)
143
  if not tenant:
 
144
  return
145
 
146
  # Find or create Lead
147
  stmt = select(Lead).where(
148
  Lead.tenant_id == tenant.id,
149
+ Lead.telegram_id == sender_id # Reuse this field for now, maybe rename later
150
  )
151
  result = await session.execute(stmt)
152
  lead = result.scalar_one_or_none()
 
154
  if not lead:
155
  lead = Lead(
156
  tenant_id=tenant.id,
157
+ name=f"WhatsApp User {sender_id[-4:]}",
158
  telegram_id=sender_id,
159
  status="NEW",
160
  processing_status="idle"
161
  )
162
  session.add(lead)
163
  await session.flush()
 
164
 
165
  lead_id = lead.id
166
 
 
177
  conversation = Conversation(
178
  tenant_id=tenant.id,
179
  lead_id=lead.id,
180
+ channel="whatsapp",
181
  is_active=True,
182
  started_at=datetime.utcnow()
183
  )
184
  session.add(conversation)
185
  await session.flush()
 
186
 
187
  conversation_id = conversation.id
188
 
 
199
  lead.last_message_at = datetime.utcnow()
200
  lead.last_activity_at = datetime.utcnow()
201
  lead.first_message_at = lead.first_message_at or datetime.utcnow()
202
+ lead.processing_status = "analyzing"
203
  session.add(lead)
204
 
205
  await session.commit()
206
  await session.refresh(user_message)
207
  user_message_id = user_message.id
 
208
 
209
  except Exception as e:
210
+ logger.error(f"❌ Error saving message: {e}", exc_info=True)
 
 
211
  return
212
 
213
  # STEP 2: Debouncing delay (4 seconds)
 
225
  latest_user_message = result.scalar_one_or_none()
226
 
227
  if latest_user_message and latest_user_message.id != user_message_id:
228
+ logger.info(f"⏭️ Debouncing: Skipping old message {user_message_id}")
 
 
229
 
230
  # Reset status to idle
231
  lead = await session.get(Lead, lead_id)
 
233
  lead.processing_status = "idle"
234
  session.add(lead)
235
  await session.commit()
236
+ return
237
 
238
  except Exception as e:
239
+ logger.error(f"❌ Error checking for newer messages: {e}", exc_info=True)
 
 
240
  return
241
 
242
+ # STEP 4: Generate AI response
243
  async with async_session_maker() as session:
244
  try:
 
245
  tenant = await session.get(Tenant, tenant_id)
246
  lead = await session.get(Lead, lead_id)
247
 
248
  if not tenant or not lead:
 
249
  return
250
 
251
  # Set generating status
 
260
  result = await session.execute(stmt)
261
  messages = list(result.scalars().all())
262
 
 
 
263
  # Get AI Core
264
  ai_core = get_ai_core()
265
 
 
289
  session.add(lead)
290
 
291
  await session.commit()
 
292
 
293
+ # Send response back to user via Evolution API
294
+ from app.services.whatsapp_qr import whatsapp_qr_service
295
+ await whatsapp_qr_service.send_message(
296
+ tenant_id=str(tenant.id),
297
+ phone=sender_id,
298
+ text=response["text"]
 
 
299
  )
300
 
301
+ logger.info(f"✅ WhatsApp message processing complete")
302
 
303
  except Exception as e:
304
+ logger.error(f"❌ Error processing WhatsApp message: {e}", exc_info=True)
 
 
305
 
306
  # Set error status
307
  try:
 
312
  await session.commit()
313
  except:
314
  pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, admin, team, oauth
11
  import asyncio
12
  import sys
13
  from slowapi import Limiter, _rate_limit_exceeded_handler
@@ -160,7 +160,8 @@ app.add_middleware(RequestIDMiddleware)
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") # Telegram webhook
163
- app.include_router(meta_webhooks.router, prefix="/api/v1") # Meta webhooks (WhatsApp & Instagram)
 
164
  app.include_router(leads.router, prefix="/api/v1")
165
  app.include_router(knowledge.router, prefix="/api/v1")
166
  app.include_router(channels.router, prefix="/api/v1")
@@ -173,7 +174,7 @@ app.include_router(ai_training.router, prefix="/api/v1") # AI Training & Learni
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
  app.include_router(team.router, prefix="/api/v1") # Team Management (owner only)
176
- app.include_router(oauth.router, prefix="/api/v1") # OAuth (Instagram & WhatsApp)
177
 
178
 
179
  @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, billing, ai_training, crm, admin, team, evolution_webhook
11
  import asyncio
12
  import sys
13
  from slowapi import Limiter, _rate_limit_exceeded_handler
 
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") # Telegram webhook
163
+ app.include_router(evolution_webhook.router, prefix="/api/v1") # Evolution API (WhatsApp)
164
+ # app.include_router(linkedin_webhook.router, prefix="/api/v1") # LinkedIn webhook (TODO: Implement)
165
  app.include_router(leads.router, prefix="/api/v1")
166
  app.include_router(knowledge.router, prefix="/api/v1")
167
  app.include_router(channels.router, prefix="/api/v1")
 
174
  app.include_router(crm.router, prefix="/api/v1") # CRM Integration
175
  app.include_router(admin.router, prefix="/api/v1") # Admin Panel (superuser only)
176
  app.include_router(team.router, prefix="/api/v1") # Team Management (owner only)
177
+ # app.include_router(oauth.router, prefix="/api/v1") # OAuth removed
178
 
179
 
180
  @app.on_event("startup")
backend/app/models/tenant.py CHANGED
@@ -59,7 +59,7 @@ class Tenant(SQLModel, table=True):
59
  webhook_url: Optional[str] = None
60
 
61
  # Multi-Channel Support
62
- whatsapp_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # QR code based
63
  linkedin_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # LinkedIn messaging
64
 
65
  # AI Brain Settings (from migrations)
 
59
  webhook_url: Optional[str] = None
60
 
61
  # Multi-Channel Support
62
+ whatsapp_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # Evolution API (QR code)
63
  linkedin_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # LinkedIn messaging
64
 
65
  # AI Brain Settings (from migrations)
backend/app/services/linkedin_service.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LinkedIn Service.
3
+ Handles interactions with LinkedIn API (Messaging, Profile).
4
+ """
5
+ import httpx
6
+ from typing import Optional, Dict, Any
7
+ from app.core.logging import get_logger
8
+
9
+ logger = get_logger(__name__)
10
+
11
+ class LinkedInService:
12
+ """LinkedIn API Service"""
13
+
14
+ BASE_URL = "https://api.linkedin.com/v2"
15
+
16
+ async def get_organization_info(self, access_token: str, organization_id: str) -> Optional[Dict[str, Any]]:
17
+ """Get organization info to verify access"""
18
+ try:
19
+ async with httpx.AsyncClient() as client:
20
+ response = await client.get(
21
+ f"{self.BASE_URL}/organizations/{organization_id}",
22
+ headers={
23
+ "Authorization": f"Bearer {access_token}",
24
+ "X-Restli-Protocol-Version": "2.0.0"
25
+ }
26
+ )
27
+
28
+ if response.status_code == 200:
29
+ return response.json()
30
+ else:
31
+ logger.error(f"LinkedIn API error: {response.text}")
32
+ return None
33
+
34
+ except Exception as e:
35
+ logger.error(f"LinkedIn service error: {str(e)}")
36
+ return None
37
+
38
+ async def send_message(self, access_token: str, organization_id: str, recipient_urn: str, text: str) -> bool:
39
+ """
40
+ Send message via LinkedIn Messaging API.
41
+ Note: This requires specific permissions (w_member_social, etc.) and might vary based on API version.
42
+ """
43
+ try:
44
+ # This is a simplified example. LinkedIn Messaging API is complex and requires URNs.
45
+ # Real implementation depends on whether it's a personal profile or company page.
46
+
47
+ payload = {
48
+ "recipients": [recipient_urn],
49
+ "subject": "Message from MicroFunnel",
50
+ "body": text,
51
+ "messageType": "MEMBER_TO_MEMBER" # or ORGANIZATION_TO_MEMBER
52
+ }
53
+
54
+ # Placeholder for actual API call
55
+ logger.info(f"Sending LinkedIn message to {recipient_urn}: {text}")
56
+ return True
57
+
58
+ except Exception as e:
59
+ logger.error(f"LinkedIn send message error: {str(e)}")
60
+ return False
61
+
62
+ linkedin_service = LinkedInService()
backend/app/services/whatsapp_qr.py CHANGED
@@ -217,5 +217,60 @@ class WhatsAppQRSession:
217
  del self.sessions[tenant_id]
218
 
219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  # Глобальный экземпляр
221
  whatsapp_qr_service = WhatsAppQRSession()
 
217
  del self.sessions[tenant_id]
218
 
219
 
220
+ async def send_message(self, tenant_id: str, phone: str, text: str) -> bool:
221
+ """
222
+ Отправка сообщения через Evolution API
223
+
224
+ Args:
225
+ tenant_id: ID тенанта
226
+ phone: Номер телефона получателя
227
+ text: Текст сообщения
228
+
229
+ Returns:
230
+ True если успешно
231
+ """
232
+ try:
233
+ if tenant_id not in self.sessions:
234
+ # Try to reconstruct session if instance exists (stateless mode)
235
+ self.sessions[tenant_id] = {
236
+ 'instance_name': f"tenant_{tenant_id}",
237
+ 'status': 'unknown'
238
+ }
239
+
240
+ instance_name = self.sessions[tenant_id]['instance_name']
241
+
242
+ async with httpx.AsyncClient(timeout=10.0) as client:
243
+ url = f"{self.evolution_url}/message/sendText/{instance_name}"
244
+
245
+ payload = {
246
+ "number": phone,
247
+ "options": {
248
+ "delay": 1200,
249
+ "presence": "composing",
250
+ "linkPreview": False
251
+ },
252
+ "textMessage": {
253
+ "text": text
254
+ }
255
+ }
256
+
257
+ response = await client.post(
258
+ url,
259
+ json=payload,
260
+ headers=self._get_headers()
261
+ )
262
+
263
+ if response.status_code == 201:
264
+ logger.info(f"Message sent to {phone} via {instance_name}")
265
+ return True
266
+ else:
267
+ logger.error(f"Failed to send message: {response.text}")
268
+ return False
269
+
270
+ except Exception as e:
271
+ logger.error(f"Send message error: {str(e)}")
272
+ return False
273
+
274
+
275
  # Глобальный экземпляр
276
  whatsapp_qr_service = WhatsAppQRSession()
backend/tests/test_evolution_webhook.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import pytest
3
+ from fastapi.testclient import TestClient
4
+ from unittest.mock import patch, MagicMock
5
+ from app.main import app
6
+
7
+ client = TestClient(app)
8
+
9
+ # Mock data
10
+ MOCK_TEXT_MESSAGE = {
11
+ "event": "messages.upsert",
12
+ "instance": "instance_name",
13
+ "data": {
14
+ "key": {
15
+ "remoteJid": "1234567890@s.whatsapp.net",
16
+ "fromMe": False,
17
+ "id": "MESSAGE_ID"
18
+ },
19
+ "pushName": "Test User",
20
+ "message": {
21
+ "conversation": "Hello world"
22
+ },
23
+ "messageType": "conversation"
24
+ },
25
+ "sender": "1234567890@s.whatsapp.net"
26
+ }
27
+
28
+ MOCK_EXTENDED_MESSAGE = {
29
+ "event": "messages.upsert",
30
+ "instance": "instance_name",
31
+ "data": {
32
+ "key": {
33
+ "remoteJid": "1234567890@s.whatsapp.net",
34
+ "fromMe": False,
35
+ "id": "MESSAGE_ID"
36
+ },
37
+ "pushName": "Test User",
38
+ "message": {
39
+ "extendedTextMessage": {
40
+ "text": "Hello extended"
41
+ }
42
+ },
43
+ "messageType": "extendedTextMessage"
44
+ },
45
+ "sender": "1234567890@s.whatsapp.net"
46
+ }
47
+
48
+ @pytest.fixture
49
+ def mock_process_message():
50
+ with patch("app.api.evolution_webhook.process_meta_message") as mock:
51
+ yield mock
52
+
53
+ def test_evolution_webhook_text_message(mock_process_message):
54
+ """Test processing of a simple text message."""
55
+ # Mock the Tenant query to return a tenant with matching instance/config if needed
56
+ # For now, assuming the webhook handler extracts tenant_id from URL or similar
57
+ # In the implementation, the webhook URL is /api/v1/webhook/evolution/{tenant_id}
58
+
59
+ tenant_id = "test-tenant-id"
60
+
61
+ response = client.post(
62
+ f"/api/v1/webhook/evolution/{tenant_id}",
63
+ json=MOCK_TEXT_MESSAGE,
64
+ headers={"apikey": "test-api-key"} # Assuming some auth or just open for now based on implementation
65
+ )
66
+
67
+ assert response.status_code == 200
68
+ assert response.json() == {"status": "ok"}
69
+
70
+ # Verify process_meta_message was called with correct arguments
71
+ mock_process_message.assert_called_once()
72
+ call_args = mock_process_message.call_args
73
+ assert call_args[0][0] == tenant_id
74
+ assert call_args[0][1] == "1234567890" # Phone number extracted
75
+ assert call_args[0][2] == "Hello world" # Text extracted
76
+ assert call_args[0][3] == "Test User" # Name extracted
77
+ assert call_args[0][4] == "whatsapp" # Channel
78
+
79
+ def test_evolution_webhook_extended_message(mock_process_message):
80
+ """Test processing of an extended text message."""
81
+ tenant_id = "test-tenant-id"
82
+
83
+ response = client.post(
84
+ f"/api/v1/webhook/evolution/{tenant_id}",
85
+ json=MOCK_EXTENDED_MESSAGE
86
+ )
87
+
88
+ assert response.status_code == 200
89
+
90
+ mock_process_message.assert_called_once()
91
+ call_args = mock_process_message.call_args
92
+ assert call_args[0][2] == "Hello extended"
93
+
94
+ def test_evolution_webhook_from_me(mock_process_message):
95
+ """Test that messages from me are ignored."""
96
+ tenant_id = "test-tenant-id"
97
+
98
+ payload = MOCK_TEXT_MESSAGE.copy()
99
+ payload["data"]["key"]["fromMe"] = True
100
+
101
+ response = client.post(
102
+ f"/api/v1/webhook/evolution/{tenant_id}",
103
+ json=payload
104
+ )
105
+
106
+ assert response.status_code == 200
107
+ mock_process_message.assert_not_called()
108
+
109
+ def test_evolution_webhook_invalid_event(mock_process_message):
110
+ """Test that non-message events are ignored."""
111
+ tenant_id = "test-tenant-id"
112
+
113
+ payload = MOCK_TEXT_MESSAGE.copy()
114
+ payload["event"] = "presence.update"
115
+
116
+ response = client.post(
117
+ f"/api/v1/webhook/evolution/{tenant_id}",
118
+ json=payload
119
+ )
120
+
121
+ assert response.status_code == 200
122
+ mock_process_message.assert_not_called()
frontend/app/channels/page.tsx CHANGED
@@ -5,7 +5,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
5
  import { useAuth } from '@/contexts/AuthContext'
6
  import { useToast } from '@/contexts/ToastContext'
7
  import { channelsApi } from '@/lib/api'
8
- import { Send, CheckCircle, XCircle, AlertCircle, Loader2, ExternalLink, Copy, Check } from 'lucide-react'
9
 
10
  type Channel = 'telegram' | 'whatsapp' | 'linkedin'
11
 
@@ -24,25 +24,17 @@ interface TelegramStatus {
24
 
25
  export default function ChannelsPage() {
26
  const [activeTab, setActiveTab] = useState<Channel>('telegram')
27
- const [copiedUrl, setCopiedUrl] = useState(false)
28
  const toast = useToast()
29
-
30
  // Telegram state
31
  const [botToken, setBotToken] = useState('')
32
  const [showToken, setShowToken] = useState(false)
33
-
34
- // WhatsApp state
35
- const [waAccessToken, setWaAccessToken] = useState('')
36
- const [waPhoneNumberId, setWaPhoneNumberId] = useState('')
37
- const [waVerifyToken] = useState('microfunnel-verify-token')
38
- const [waTokenValid, setWaTokenValid] = useState<boolean | null>(null)
39
- const [waTokenValidating, setWaTokenValidating] = useState(false)
40
-
41
  // LinkedIn state
42
  const [liAccessToken, setLiAccessToken] = useState('')
43
  const [liOrgId, setLiOrgId] = useState('')
44
  const [liVerifyToken] = useState('microfunnel-verify-token')
45
-
46
  const queryClient = useQueryClient()
47
  const { user, isLoading: authLoading } = useAuth()
48
 
@@ -53,15 +45,15 @@ export default function ChannelsPage() {
53
  enabled: !!user,
54
  refetchInterval: 10000,
55
  })
56
-
57
  // Get WhatsApp status
58
  const { data: whatsappStatus, isLoading: whatsappLoading } = useQuery({
59
  queryKey: ['whatsapp-status', user?.tenant_id],
60
  queryFn: channelsApi.getWhatsAppStatus,
61
  enabled: !!user,
62
- refetchInterval: 15000,
63
  })
64
-
65
  // Get LinkedIn status
66
  const { data: linkedinStatus, isLoading: linkedinLoading } = useQuery({
67
  queryKey: ['linkedin-status', user?.tenant_id],
@@ -82,18 +74,18 @@ export default function ChannelsPage() {
82
  toast.error('Ошибка подключения', error.message)
83
  },
84
  })
85
-
86
- // Connect WhatsApp mutation
87
- const connectWhatsAppMutation = useMutation({
88
- mutationFn: () => channelsApi.connectWhatsApp({
89
- access_token: waAccessToken,
90
- phone_number_id: waPhoneNumberId,
91
- verify_token: waVerifyToken,
92
  }),
93
  onSuccess: (data) => {
94
- queryClient.invalidateQueries({ queryKey: ['whatsapp-status', user?.tenant_id] })
95
- setWaAccessToken('')
96
- setWaPhoneNumberId('')
97
  toast.success('Успех!', data.message)
98
  },
99
  onError: (error: Error) => {
@@ -112,7 +104,7 @@ export default function ChannelsPage() {
112
  toast.error('Ошибка', error.message)
113
  },
114
  })
115
-
116
  const disconnectWhatsAppMutation = useMutation({
117
  mutationFn: channelsApi.disconnectWhatsApp,
118
  onSuccess: (data) => {
@@ -124,6 +116,17 @@ export default function ChannelsPage() {
124
  },
125
  })
126
 
 
 
 
 
 
 
 
 
 
 
 
127
  // Handlers
128
  const handleConnectTelegram = () => {
129
  if (!botToken.trim()) {
@@ -132,76 +135,13 @@ export default function ChannelsPage() {
132
  }
133
  connectTelegramMutation.mutate(botToken.trim())
134
  }
135
-
136
- const handleConnectWhatsApp = () => {
137
- if (!waAccessToken.trim() || !waPhoneNumberId.trim()) {
138
  toast.warning('Внимание', 'Заполните все обязательные поля')
139
  return
140
  }
141
- connectWhatsAppMutation.mutate()
142
- }
143
-
144
- // Validate WhatsApp token
145
- const validateWhatsAppToken = async (token: string) => {
146
- if (!token.trim()) {
147
- setWaTokenValid(null)
148
- return
149
- }
150
-
151
- setWaTokenValidating(true)
152
- try {
153
- // Test token by fetching account info
154
- const response = await fetch(
155
- `https://graph.facebook.com/v18.0/me?access_token=${token}`
156
- )
157
-
158
- if (response.ok) {
159
- const data = await response.json()
160
- console.log('✅ WhatsApp token valid:', data)
161
- setWaTokenValid(true)
162
- } else {
163
- console.error('❌ WhatsApp token invalid')
164
- setWaTokenValid(false)
165
- }
166
- } catch (error) {
167
- console.error('❌ Token validation error:', error)
168
- setWaTokenValid(false)
169
- } finally {
170
- setWaTokenValidating(false)
171
- }
172
- }
173
-
174
- // Debounced token validation
175
- useEffect(() => {
176
- const timer = setTimeout(() => {
177
- if (waAccessToken.trim()) {
178
- validateWhatsAppToken(waAccessToken)
179
- }
180
- }, 1000)
181
- return () => clearTimeout(timer)
182
- }, [waAccessToken])
183
-
184
- const copyToClipboard = (text: string) => {
185
- navigator.clipboard.writeText(text)
186
- setCopiedUrl(true)
187
- setTimeout(() => setCopiedUrl(false), 2000)
188
- }
189
-
190
- const getWebhookUrl = (channel: 'whatsapp' | 'linkedin') => {
191
- if (!user) return ''
192
- // Get base URL from environment or use ngrok for development
193
- // PRODUCTION: Use Railway backend URL
194
- // DEVELOPMENT: Set NEXT_PUBLIC_WEBHOOK_URL to your ngrok URL
195
- let baseUrl = process.env.NEXT_PUBLIC_WEBHOOK_URL || 'https://web-production-81733.up.railway.app'
196
-
197
- // Remove trailing /api/v1 if exists (avoid duplication)
198
- baseUrl = baseUrl.replace(/\/api\/v1\/?$/, '')
199
-
200
- if (channel === 'whatsapp') {
201
- return `${baseUrl}/api/v1/webhook/meta/whatsapp/${user.tenant_id}`
202
- } else {
203
- return `${baseUrl}/api/v1/webhook/linkedin/${user.tenant_id}`
204
- }
205
  }
206
 
207
  if (authLoading || !user) {
@@ -211,10 +151,11 @@ export default function ChannelsPage() {
211
  </div>
212
  )
213
  }
214
-
215
  const tabs = [
216
  { id: 'telegram' as Channel, label: 'Telegram', icon: Send, status: telegramStatus?.connected },
217
- { id: 'whatsapp' as Channel, label: 'WhatsApp (QR)', icon: Send, status: whatsappStatus?.connected },
 
218
  ]
219
 
220
  return (
@@ -227,7 +168,7 @@ export default function ChannelsPage() {
227
  Подключите мессенджеры для автоматизации продаж через ИИ
228
  </p>
229
  </div>
230
-
231
  {/* Tabs */}
232
  <div className="bg-white rounded-2xl shadow-lg border border-slate-200 overflow-hidden">
233
  <div className="flex border-b border-slate-200">
@@ -235,11 +176,10 @@ export default function ChannelsPage() {
235
  <button
236
  key={tab.id}
237
  onClick={() => setActiveTab(tab.id)}
238
- className={`flex-1 px-6 py-4 font-semibold text-sm transition-all relative ${
239
- activeTab === tab.id
240
  ? 'text-indigo-600 bg-indigo-50'
241
  : 'text-slate-600 hover:bg-slate-50'
242
- }`}
243
  >
244
  <div className="flex items-center justify-center gap-2">
245
  <tab.icon className="w-4 h-4" />
@@ -275,7 +215,7 @@ export default function ChannelsPage() {
275
  isProcessing={connectTelegramMutation.isPending || disconnectTelegramMutation.isPending}
276
  />
277
  )}
278
-
279
  {/* WhatsApp Tab */}
280
  {activeTab === 'whatsapp' && (
281
  <WhatsAppQRTab
@@ -290,6 +230,25 @@ export default function ChannelsPage() {
290
  tenantId={user.tenant_id}
291
  />
292
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  </div>
294
  </div>
295
  </div>
@@ -310,7 +269,7 @@ function TelegramTab({
310
  isProcessing,
311
  }: any) {
312
  const isConnected = status?.connected || false
313
-
314
  return (
315
  <div className="space-y-6">
316
  {/* Status Badge */}
@@ -338,7 +297,7 @@ function TelegramTab({
338
  </div>
339
  )}
340
  </div>
341
-
342
  {isConnected && status?.bot_info ? (
343
  <div className="space-y-4">
344
  <div className="p-6 bg-emerald-50 border border-emerald-200 rounded-xl">
@@ -374,7 +333,7 @@ function TelegramTab({
374
  Найдите официального бота @BotFather в Telegram и начните с ним диалог.
375
  </p>
376
  </div>
377
-
378
  {/* Step 2 */}
379
  <div className="space-y-3">
380
  <div className="flex items-center gap-3">
@@ -387,7 +346,7 @@ function TelegramTab({
387
  Отправьте команду <code className="bg-slate-100 px-2 py-1 rounded font-mono text-xs">/newbot</code> и следуйте инструкциям BotFather.
388
  </p>
389
  </div>
390
-
391
  {/* Step 3 */}
392
  <div className="space-y-3">
393
  <div className="flex items-center gap-3">
@@ -458,9 +417,26 @@ function WhatsAppQRTab({
458
  const [qrCode, setQrCode] = useState<string | null>(null)
459
  const [isConnecting, setIsConnecting] = useState(false)
460
  const toast = useToast()
461
-
462
  const isConnected = status?.connected || false
463
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464
  return (
465
  <div className="space-y-6">
466
  {/* Status Badge */}
@@ -471,7 +447,7 @@ function WhatsAppQRTab({
471
  </div>
472
  <div>
473
  <h3 className="font-bold text-slate-900">WhatsApp Business (QR)</h3>
474
- <p className="text-sm text-slate-600">Подключение через QR-код (серый API)</p>
475
  </div>
476
  </div>
477
  {loading ? (
@@ -488,7 +464,7 @@ function WhatsAppQRTab({
488
  </div>
489
  )}
490
  </div>
491
-
492
  {isConnected ? (
493
  <div className="space-y-4">
494
  <div className="p-6 bg-emerald-50 border border-emerald-200 rounded-xl">
@@ -497,8 +473,8 @@ function WhatsAppQRTab({
497
  <h4 className="font-bold text-emerald-900">WhatsApp подключён</h4>
498
  </div>
499
  <div className="space-y-2 text-sm">
500
- <p><span className="font-semibold">Статус:</span> Активное подключение</p>
501
- <p><span className="font-semibold">Tenant ID:</span> {tenantId}</p>
502
  </div>
503
  </div>
504
  <button
@@ -520,26 +496,18 @@ function WhatsAppQRTab({
520
  <div className="flex-1">
521
  <h3 className="text-lg font-bold text-slate-900 mb-2">Подключение WhatsApp через QR-код</h3>
522
  <p className="text-sm text-slate-600 mb-4">
523
- Простой способ подключения без Meta Business API. Отсканируйте QR-код из приложения WhatsApp.
524
  </p>
525
- <div className="p-4 bg-yellow-50 border border-yellow-300 rounded-lg mb-4">
526
- <p className="text-sm text-yellow-900 font-semibold mb-2">⚠️ Важно:</p>
527
- <ul className="text-sm text-yellow-900 space-y-1 list-disc list-inside">
528
- <li>Это "серый" API - не официальный метод</li>
529
- <li>Используйте на свой риск</li>
530
- <li>Для продакшена рекомендуется WhatsApp Business API</li>
531
- </ul>
532
- </div>
533
  </div>
534
  </div>
535
  </div>
536
-
537
  {/* QR код */}
538
  <div className="p-8 bg-white border-2 border-slate-300 rounded-2xl text-center">
539
  {qrCode ? (
540
  <div className="space-y-4">
541
- <div className="w-64 h-64 mx-auto bg-slate-100 rounded-xl flex items-center justify-center">
542
- <img src={qrCode} alt="QR Code" className="max-w-full max-h-full" />
543
  </div>
544
  <p className="text-sm text-slate-600">
545
  Отсканируйте этот QR-код в WhatsApp → Настройки → Linked Devices
@@ -551,10 +519,7 @@ function WhatsAppQRTab({
551
  <p className="text-slate-400 text-sm">Здесь появится QR-код</p>
552
  </div>
553
  <button
554
- onClick={() => {
555
- setIsConnecting(true)
556
- toast.info('Разработка', 'WhatsApp QR подключение в разработке')
557
- }}
558
  disabled={isConnecting}
559
  className="px-8 py-4 bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-white rounded-xl disabled:opacity-50 font-bold text-lg flex items-center justify-center gap-3 shadow-xl transition-all mx-auto"
560
  >
@@ -570,13 +535,10 @@ function WhatsAppQRTab({
570
  </>
571
  )}
572
  </button>
573
- <p className="text-xs text-slate-500">
574
- ⚠️ Функция в разработке. Скоро будет доступна.
575
- </p>
576
  </div>
577
  )}
578
  </div>
579
-
580
  {/* Инструкция */}
581
  <div className="p-6 bg-blue-50 border-2 border-blue-200 rounded-2xl">
582
  <h4 className="font-bold text-blue-900 mb-3">📚 Как это работает:</h4>
@@ -594,65 +556,31 @@ function WhatsAppQRTab({
594
  )
595
  }
596
 
597
- // Meta Channel Tab Component (WhatsApp/Instagram)
598
- function MetaChannelTab({
599
- channel,
600
  status,
601
  loading,
602
  accessToken,
603
  setAccessToken,
604
- identifierId,
605
- setIdentifierId,
606
- verifyToken,
607
  onConnect,
608
  onDisconnect,
609
  isProcessing,
610
- webhookUrl,
611
- copyToClipboard,
612
- copiedUrl,
613
- tokenValid,
614
- tokenValidating,
615
  }: any) {
616
  const isConnected = status?.connected || false
617
-
618
- const configs = {
619
- whatsapp: {
620
- title: 'WhatsApp Business',
621
- identifierLabel: 'Phone Number ID',
622
- identifierPlaceholder: '123456789012345',
623
- identifierHelp: 'WhatsApp → API Setup → Phone Number ID',
624
- icon: '📱',
625
- bgColor: 'bg-emerald-50',
626
- textColor: 'text-emerald-600',
627
- borderColor: 'border-emerald-200',
628
- product: 'WhatsApp Business API',
629
- },
630
- instagram: {
631
- title: 'Instagram Direct',
632
- identifierLabel: 'Page ID',
633
- identifierPlaceholder: '987654321098765',
634
- identifierHelp: 'Instagram → Settings → About → Page ID',
635
- icon: '📸',
636
- bgColor: 'bg-purple-50',
637
- textColor: 'text-purple-600',
638
- borderColor: 'border-purple-200',
639
- product: 'Instagram Messaging API',
640
- },
641
- }
642
-
643
- const config = configs[channel as 'whatsapp' | 'instagram']
644
-
645
  return (
646
  <div className="space-y-6">
647
  {/* Status Badge */}
648
  <div className="flex items-center justify-between p-4 bg-slate-50 rounded-xl">
649
  <div className="flex items-center gap-3">
650
- <div className={`w-12 h-12 ${config.bgColor} rounded-xl flex items-center justify-center text-2xl`}>
651
- {config.icon}
652
  </div>
653
  <div>
654
- <h3 className="font-bold text-slate-900">{config.title}</h3>
655
- <p className="text-sm text-slate-600">Автоматизация через Meta Cloud API</p>
656
  </div>
657
  </div>
658
  {loading ? (
@@ -669,22 +597,16 @@ function MetaChannelTab({
669
  </div>
670
  )}
671
  </div>
672
-
673
  {isConnected ? (
674
  <div className="space-y-4">
675
- <div className={`p-6 ${config.bgColor} ${config.borderColor} border rounded-xl`}>
676
  <div className="flex items-center gap-2 mb-4">
677
- <CheckCircle className={`w-5 h-5 ${config.textColor}`} />
678
- <h4 className={`font-bold ${config.textColor}`}>Канал подключен</h4>
679
  </div>
680
  <div className="space-y-2 text-sm">
681
- <p><span className="font-semibold">Webhook:</span> {status.webhook_url}</p>
682
- {status.config?.phone_number_id && (
683
- <p><span className="font-semibold">Phone Number ID:</span> {status.config.phone_number_id}</p>
684
- )}
685
- {status.config?.page_id && (
686
- <p><span className="font-semibold">Page ID:</span> {status.config.page_id}</p>
687
- )}
688
  </div>
689
  </div>
690
  <button
@@ -692,187 +614,136 @@ function MetaChannelTab({
692
  disabled={isProcessing}
693
  className="w-full px-6 py-3 bg-red-50 text-red-700 rounded-xl hover:bg-red-100 disabled:opacity-50 font-semibold border border-red-200 transition"
694
  >
695
- Отключить {config.title}
696
  </button>
697
  </div>
698
  ) : (
699
  <div className="space-y-6">
700
- {/* OAUTH ONE-CLICK CONNECT */}
701
- <div className="p-6 bg-gradient-to-br from-emerald-50 to-teal-50 border-2 border-emerald-200 rounded-2xl">
702
- <div className="flex items-start gap-4">
703
- <div className="w-12 h-12 bg-emerald-600 rounded-xl flex items-center justify-center flex-shrink-0">
704
- <span className="text-2xl">⚡</span>
705
- </div>
706
- <div className="flex-1">
707
- <h3 className="text-lg font-bold text-slate-900 mb-2">Подключение в один клик (OAuth)</h3>
708
- <p className="text-sm text-slate-600 mb-4">
709
- Самый простой способ! Нажмите кнопку ниже и авторизуйтесь через Meta.
710
- Все настройки применятся автоматически.
711
- </p>
712
- <a
713
- href={`${process.env.NEXT_PUBLIC_API_URL || 'https://web-production-81733.up.railway.app/api/v1'}/oauth/meta/connect?channel=${channel}`}
714
- className="inline-flex items-center gap-2 px-6 py-3 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold text-sm transition-all shadow-lg hover:shadow-xl transform hover:-translate-y-0.5"
715
- >
716
- <span>🔐</span>
717
- Подключить {config.title} через OAuth
718
- <ExternalLink className="w-4 h-4" />
719
- </a>
720
- <p className="mt-3 text-xs text-slate-500">
721
- ✅ Не нужно копировать токены вручную<br />
722
- ✅ Безопасная авторизация через Meta<br />
723
- ✅ Webhook настраивается автоматически
724
- </p>
725
- </div>
726
- </div>
727
- </div>
728
-
729
- {/* DIVIDER */}
730
- <div className="flex items-center gap-4">
731
- <div className="flex-1 h-px bg-slate-300"></div>
732
- <span className="text-sm font-semibold text-slate-500">или настроить вручную</span>
733
- <div className="flex-1 h-px bg-slate-300"></div>
734
- </div>
735
-
736
- {/* УПРОЩЁННЫЕ ИНСТРУКЦИИ */}
737
- <div className="p-6 bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200 rounded-2xl">
738
- <div className="flex items-start gap-4">
739
- <div className="w-12 h-12 bg-blue-600 rounded-xl flex items-center justify-center flex-shrink-0">
740
- <span className="text-2xl">🎓</span>
741
- </div>
742
- <div className="flex-1">
743
- <h3 className="text-lg font-bold text-slate-900 mb-2">Ручная настройка за 3 шага</h3>
744
- <p className="text-sm text-slate-600 mb-4">
745
- Следуйте простым инструкциям ниже. Настройка займёт ~5 минут.
746
- </p>
747
- <a
748
- href={channel === 'whatsapp'
749
- ? 'https://www.youtube.com/results?search_query=whatsapp+business+api+setup+tutorial'
750
- : 'https://www.youtube.com/results?search_query=instagram+messaging+api+setup+tutorial'
751
- }
752
- target="_blank"
753
- rel="noopener noreferrer"
754
- className="inline-flex items-center gap-2 px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg font-semibold text-sm transition-colors"
755
- >
756
- <span>▶</span>
757
- Посмотреть видео-инструкцию на YouTube
758
- <ExternalLink className="w-4 h-4" />
759
- </a>
760
- </div>
761
- </div>
762
- </div>
763
-
764
- {/* Step 1: Meta App Setup */}
765
- <div className="border-l-4 border-indigo-500 pl-6 space-y-3">
766
- <div className="flex items-center gap-3">
767
- <div className="w-10 h-10 bg-indigo-600 text-white rounded-full flex items-center justify-center font-bold text-lg shadow-lg">
768
- 1️⃣
769
- </div>
770
- <h4 className="font-bold text-lg text-slate-900">Создайте приложение Meta</h4>
771
- </div>
772
- <div className="ml-13 space-y-3">
773
- <ol className="list-decimal list-inside space-y-2 text-sm text-slate-700">
774
- <li>
775
- Откройте{' '}
776
- <a
777
- href="https://developers.facebook.com/apps/create/"
778
- target="_blank"
779
- rel="noopener noreferrer"
780
- className="text-indigo-600 hover:text-indigo-700 font-bold underline inline-flex items-center gap-1"
781
- >
782
- Meta Developers
783
- <ExternalLink className="w-3 h-3" />
784
- </a>
785
- </li>
786
- <li>Нажмите <strong>"Create App"</strong> → выберите <strong>"Business"</strong></li>
787
- <li>Добавьте продукт: <strong className={config.textColor}>{config.product}</strong></li>
788
- <li>Завершите настройку приложения</li>
789
- </ol>
790
- </div>
791
- </div>
792
-
793
- {/* Step 2: Get Credentials */}
794
- <div className="border-l-4 border-purple-500 pl-6 space-y-3">
795
- <div className="flex items-center gap-3">
796
- <div className="w-10 h-10 bg-purple-600 text-white rounded-full flex items-center justify-center font-bold text-lg shadow-lg">
797
- 2️⃣
798
- </div>
799
- <h4 className="font-bold text-lg text-slate-900">Скопируйте Access Token и ID</h4>
800
  </div>
801
- <div className="ml-13 space-y-4">
802
- {/* Access Token */}
803
- <div className="p-4 bg-white border-2 border-slate-200 rounded-xl">
804
- <div className="flex items-center justify-between mb-3">
805
- <label className="block text-sm font-bold text-slate-900">
806
- 📝 Access Token <span className="text-red-500">*</span>
807
- </label>
808
- <a
809
- href={`https://developers.facebook.com/apps`}
810
- target="_blank"
811
- rel="noopener noreferrer"
812
- className="text-xs text-indigo-600 hover:text-indigo-700 font-semibold inline-flex items-center gap-1"
813
- >
814
- Найти в Meta Developers
815
- <ExternalLink className="w-3 h-3" />
816
- </a>
817
- </div>
818
- <input
819
- type="password"
820
- value={accessToken}
821
- onChange={(e) => setAccessToken(e.target.value)}
822
- placeholder="EAAG... (вставьте токен из Meta Developers)"
823
- className="w-full px-4 py-3 border-2 border-slate-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 font-mono text-sm"
824
- disabled={isProcessing}
825
- />
826
- <p className="mt-2 text-xs text-slate-500">
827
- 💡 <strong>Где найти:</strong> Meta Developers → Ваше приложение → {config.product} → "Access Token"
828
- </p>
829
- {/* Token Validation */}
830
- {accessToken && (
831
- <div className="mt-3 flex items-center gap-2">
832
- {tokenValidating ? (
833
- <>
834
- <Loader2 className="w-4 h-4 animate-spin text-slate-400" />
835
- <span className="text-xs text-slate-500">Проверяем токен...</span>
836
- </>
837
- ) : tokenValid === true ? (
838
- <>
839
- <CheckCircle className="w-5 h-5 text-emerald-600" />
840
- <span className="text-sm text-emerald-600 font-bold">✓ Токен работает!</span>
841
- </>
842
- ) : tokenValid === false ? (
843
- <>
844
- <XCircle className="w-5 h-5 text-red-600" />
845
- <span className="text-sm text-red-600 font-bold">✗ Неверный токен</span>
846
- </>
847
- ) : null}
848
- </div>
849
- )}
850
- </div>
851
-
852
- {/* Identifier (Phone Number ID / Page ID) */}
853
- <div className="p-4 bg-white border-2 border-slate-200 rounded-xl">
854
- <div className="flex items-center justify-between mb-3">
855
- <label className="block text-sm font-bold text-slate-900">
856
- {config.icon} {config.identifierLabel} <span className="text-red-500">*</span>
857
- </label>
858
- </div>
859
- <input
860
- type="text"
861
- value={identifierId}
862
- onChange={(e) => setIdentifierId(e.target.value)}
863
- placeholder={`${config.identifierPlaceholder} (числовой ID)`}
864
- className="w-full px-4 py-3 border-2 border-slate-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 font-mono text-sm"
865
- disabled={isProcessing}
866
- />
867
- <p className="mt-2 text-xs text-slate-500">
868
- 💡 <strong>Где найти:</strong> {config.identifierHelp}
869
- </p>
870
- </div>
871
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
872
  </div>
873
-
874
- {/* Step 3: Webhook Setup */}
875
- <div className="border-l-4 border-emerald-500 pl-6 space-y-3">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
876
  <div className="flex items-center gap-3">
877
  <div className="w-10 h-10 bg-emerald-600 text-white rounded-full flex items-center justify-center font-bold text-lg shadow-lg">
878
  3️⃣
@@ -978,9 +849,9 @@ function MetaChannelTab({
978
  </div>
979
  )}
980
  </div>
981
- </div>
982
- </div>
983
  )}
984
- </div>
985
  )
986
  }
 
5
  import { useAuth } from '@/contexts/AuthContext'
6
  import { useToast } from '@/contexts/ToastContext'
7
  import { channelsApi } from '@/lib/api'
8
+ import { Send, CheckCircle, XCircle, AlertCircle, Loader2, ExternalLink, Copy, Check, Linkedin, QrCode } from 'lucide-react'
9
 
10
  type Channel = 'telegram' | 'whatsapp' | 'linkedin'
11
 
 
24
 
25
  export default function ChannelsPage() {
26
  const [activeTab, setActiveTab] = useState<Channel>('telegram')
 
27
  const toast = useToast()
28
+
29
  // Telegram state
30
  const [botToken, setBotToken] = useState('')
31
  const [showToken, setShowToken] = useState(false)
32
+
 
 
 
 
 
 
 
33
  // LinkedIn state
34
  const [liAccessToken, setLiAccessToken] = useState('')
35
  const [liOrgId, setLiOrgId] = useState('')
36
  const [liVerifyToken] = useState('microfunnel-verify-token')
37
+
38
  const queryClient = useQueryClient()
39
  const { user, isLoading: authLoading } = useAuth()
40
 
 
45
  enabled: !!user,
46
  refetchInterval: 10000,
47
  })
48
+
49
  // Get WhatsApp status
50
  const { data: whatsappStatus, isLoading: whatsappLoading } = useQuery({
51
  queryKey: ['whatsapp-status', user?.tenant_id],
52
  queryFn: channelsApi.getWhatsAppStatus,
53
  enabled: !!user,
54
+ refetchInterval: 5000,
55
  })
56
+
57
  // Get LinkedIn status
58
  const { data: linkedinStatus, isLoading: linkedinLoading } = useQuery({
59
  queryKey: ['linkedin-status', user?.tenant_id],
 
74
  toast.error('Ошибка подключения', error.message)
75
  },
76
  })
77
+
78
+ // Connect LinkedIn mutation
79
+ const connectLinkedInMutation = useMutation({
80
+ mutationFn: () => channelsApi.connectLinkedIn({
81
+ access_token: liAccessToken,
82
+ organization_id: liOrgId,
83
+ verify_token: liVerifyToken,
84
  }),
85
  onSuccess: (data) => {
86
+ queryClient.invalidateQueries({ queryKey: ['linkedin-status', user?.tenant_id] })
87
+ setLiAccessToken('')
88
+ setLiOrgId('')
89
  toast.success('Успех!', data.message)
90
  },
91
  onError: (error: Error) => {
 
104
  toast.error('Ошибка', error.message)
105
  },
106
  })
107
+
108
  const disconnectWhatsAppMutation = useMutation({
109
  mutationFn: channelsApi.disconnectWhatsApp,
110
  onSuccess: (data) => {
 
116
  },
117
  })
118
 
119
+ const disconnectLinkedInMutation = useMutation({
120
+ mutationFn: channelsApi.disconnectLinkedIn,
121
+ onSuccess: (data) => {
122
+ queryClient.invalidateQueries({ queryKey: ['linkedin-status', user?.tenant_id] })
123
+ toast.info('Отключено', data.message)
124
+ },
125
+ onError: (error: Error) => {
126
+ toast.error('Ошибка', error.message)
127
+ },
128
+ })
129
+
130
  // Handlers
131
  const handleConnectTelegram = () => {
132
  if (!botToken.trim()) {
 
135
  }
136
  connectTelegramMutation.mutate(botToken.trim())
137
  }
138
+
139
+ const handleConnectLinkedIn = () => {
140
+ if (!liAccessToken.trim() || !liOrgId.trim()) {
141
  toast.warning('Внимание', 'Заполните все обязательные поля')
142
  return
143
  }
144
+ connectLinkedInMutation.mutate()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  }
146
 
147
  if (authLoading || !user) {
 
151
  </div>
152
  )
153
  }
154
+
155
  const tabs = [
156
  { id: 'telegram' as Channel, label: 'Telegram', icon: Send, status: telegramStatus?.connected },
157
+ { id: 'whatsapp' as Channel, label: 'WhatsApp', icon: QrCode, status: whatsappStatus?.connected },
158
+ { id: 'linkedin' as Channel, label: 'LinkedIn', icon: Linkedin, status: linkedinStatus?.connected },
159
  ]
160
 
161
  return (
 
168
  Подключите мессенджеры для автоматизации продаж через ИИ
169
  </p>
170
  </div>
171
+
172
  {/* Tabs */}
173
  <div className="bg-white rounded-2xl shadow-lg border border-slate-200 overflow-hidden">
174
  <div className="flex border-b border-slate-200">
 
176
  <button
177
  key={tab.id}
178
  onClick={() => setActiveTab(tab.id)}
179
+ className={`flex-1 px-6 py-4 font-semibold text-sm transition-all relative ${activeTab === tab.id
 
180
  ? 'text-indigo-600 bg-indigo-50'
181
  : 'text-slate-600 hover:bg-slate-50'
182
+ }`}
183
  >
184
  <div className="flex items-center justify-center gap-2">
185
  <tab.icon className="w-4 h-4" />
 
215
  isProcessing={connectTelegramMutation.isPending || disconnectTelegramMutation.isPending}
216
  />
217
  )}
218
+
219
  {/* WhatsApp Tab */}
220
  {activeTab === 'whatsapp' && (
221
  <WhatsAppQRTab
 
230
  tenantId={user.tenant_id}
231
  />
232
  )}
233
+
234
+ {/* LinkedIn Tab */}
235
+ {activeTab === 'linkedin' && (
236
+ <LinkedInTab
237
+ status={linkedinStatus}
238
+ loading={linkedinLoading}
239
+ accessToken={liAccessToken}
240
+ setAccessToken={setLiAccessToken}
241
+ orgId={liOrgId}
242
+ setOrgId={setLiOrgId}
243
+ onConnect={handleConnectLinkedIn}
244
+ onDisconnect={() => {
245
+ if (confirm('Вы уверены, что хотите отключить LinkedIn?')) {
246
+ disconnectLinkedInMutation.mutate()
247
+ }
248
+ }}
249
+ isProcessing={connectLinkedInMutation.isPending || disconnectLinkedInMutation.isPending}
250
+ />
251
+ )}
252
  </div>
253
  </div>
254
  </div>
 
269
  isProcessing,
270
  }: any) {
271
  const isConnected = status?.connected || false
272
+
273
  return (
274
  <div className="space-y-6">
275
  {/* Status Badge */}
 
297
  </div>
298
  )}
299
  </div>
300
+
301
  {isConnected && status?.bot_info ? (
302
  <div className="space-y-4">
303
  <div className="p-6 bg-emerald-50 border border-emerald-200 rounded-xl">
 
333
  Найдите официального бота @BotFather в Telegram и начните с ним диалог.
334
  </p>
335
  </div>
336
+
337
  {/* Step 2 */}
338
  <div className="space-y-3">
339
  <div className="flex items-center gap-3">
 
346
  Отправьте команду <code className="bg-slate-100 px-2 py-1 rounded font-mono text-xs">/newbot</code> и следуйте инструкциям BotFather.
347
  </p>
348
  </div>
349
+
350
  {/* Step 3 */}
351
  <div className="space-y-3">
352
  <div className="flex items-center gap-3">
 
417
  const [qrCode, setQrCode] = useState<string | null>(null)
418
  const [isConnecting, setIsConnecting] = useState(false)
419
  const toast = useToast()
420
+
421
  const isConnected = status?.connected || false
422
+
423
+ const handleGenerateQR = async () => {
424
+ setIsConnecting(true)
425
+ try {
426
+ const data = await channelsApi.generateWhatsAppQR()
427
+ if (data.qr_code) {
428
+ setQrCode(data.qr_code)
429
+ } else {
430
+ toast.error('Ошибка', 'Не удалось получить QR код')
431
+ }
432
+ } catch (error) {
433
+ console.error(error)
434
+ toast.error('Ошибка', 'Не удалось сгенерировать QR код')
435
+ } finally {
436
+ setIsConnecting(false)
437
+ }
438
+ }
439
+
440
  return (
441
  <div className="space-y-6">
442
  {/* Status Badge */}
 
447
  </div>
448
  <div>
449
  <h3 className="font-bold text-slate-900">WhatsApp Business (QR)</h3>
450
+ <p className="text-sm text-slate-600">Подключение через Evolution API</p>
451
  </div>
452
  </div>
453
  {loading ? (
 
464
  </div>
465
  )}
466
  </div>
467
+
468
  {isConnected ? (
469
  <div className="space-y-4">
470
  <div className="p-6 bg-emerald-50 border border-emerald-200 rounded-xl">
 
473
  <h4 className="font-bold text-emerald-900">WhatsApp подключён</h4>
474
  </div>
475
  <div className="space-y-2 text-sm">
476
+ <p><span className="font-semibold">Статус:</span> {status.status}</p>
477
+ {status.phone && <p><span className="font-semibold">Номер:</span> {status.phone}</p>}
478
  </div>
479
  </div>
480
  <button
 
496
  <div className="flex-1">
497
  <h3 className="text-lg font-bold text-slate-900 mb-2">Подключение WhatsApp через QR-код</h3>
498
  <p className="text-sm text-slate-600 mb-4">
499
+ Простой способ подключения. Отсканируйте QR-код из приложения WhatsApp.
500
  </p>
 
 
 
 
 
 
 
 
501
  </div>
502
  </div>
503
  </div>
504
+
505
  {/* QR код */}
506
  <div className="p-8 bg-white border-2 border-slate-300 rounded-2xl text-center">
507
  {qrCode ? (
508
  <div className="space-y-4">
509
+ <div className="w-64 h-64 mx-auto bg-slate-100 rounded-xl flex items-center justify-center overflow-hidden">
510
+ <img src={qrCode} alt="QR Code" className="w-full h-full object-contain" />
511
  </div>
512
  <p className="text-sm text-slate-600">
513
  Отсканируйте этот QR-код в WhatsApp → Настройки → Linked Devices
 
519
  <p className="text-slate-400 text-sm">Здесь появится QR-код</p>
520
  </div>
521
  <button
522
+ onClick={handleGenerateQR}
 
 
 
523
  disabled={isConnecting}
524
  className="px-8 py-4 bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-white rounded-xl disabled:opacity-50 font-bold text-lg flex items-center justify-center gap-3 shadow-xl transition-all mx-auto"
525
  >
 
535
  </>
536
  )}
537
  </button>
 
 
 
538
  </div>
539
  )}
540
  </div>
541
+
542
  {/* Инструкция */}
543
  <div className="p-6 bg-blue-50 border-2 border-blue-200 rounded-2xl">
544
  <h4 className="font-bold text-blue-900 mb-3">📚 Как это работает:</h4>
 
556
  )
557
  }
558
 
559
+ // LinkedIn Tab Component
560
+ function LinkedInTab({
 
561
  status,
562
  loading,
563
  accessToken,
564
  setAccessToken,
565
+ orgId,
566
+ setOrgId,
 
567
  onConnect,
568
  onDisconnect,
569
  isProcessing,
 
 
 
 
 
570
  }: any) {
571
  const isConnected = status?.connected || false
572
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
573
  return (
574
  <div className="space-y-6">
575
  {/* Status Badge */}
576
  <div className="flex items-center justify-between p-4 bg-slate-50 rounded-xl">
577
  <div className="flex items-center gap-3">
578
+ <div className="w-12 h-12 bg-blue-50 rounded-xl flex items-center justify-center">
579
+ <Linkedin className="w-6 h-6 text-blue-600" />
580
  </div>
581
  <div>
582
+ <h3 className="font-bold text-slate-900">LinkedIn</h3>
583
+ <p className="text-sm text-slate-600">Автоматизация через LinkedIn API</p>
584
  </div>
585
  </div>
586
  {loading ? (
 
597
  </div>
598
  )}
599
  </div>
600
+
601
  {isConnected ? (
602
  <div className="space-y-4">
603
+ <div className="p-6 bg-blue-50 border border-blue-200 rounded-xl">
604
  <div className="flex items-center gap-2 mb-4">
605
+ <CheckCircle className="w-5 h-5 text-blue-600" />
606
+ <h4 className="font-bold text-blue-900">LinkedIn подключён</h4>
607
  </div>
608
  <div className="space-y-2 text-sm">
609
+ <p><span className="font-semibold">Организация:</span> {status.config?.org_name || status.config?.organization_id}</p>
 
 
 
 
 
 
610
  </div>
611
  </div>
612
  <button
 
614
  disabled={isProcessing}
615
  className="w-full px-6 py-3 bg-red-50 text-red-700 rounded-xl hover:bg-red-100 disabled:opacity-50 font-semibold border border-red-200 transition"
616
  >
617
+ Отключить LinkedIn
618
  </button>
619
  </div>
620
  ) : (
621
  <div className="space-y-6">
622
+ <div className="space-y-4">
623
+ <div>
624
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
625
+ Access Token
626
+ </label>
627
+ <input
628
+ type="password"
629
+ value={accessToken}
630
+ onChange={(e) => setAccessToken(e.target.value)}
631
+ placeholder="LinkedIn Access Token"
632
+ className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent"
633
+ disabled={isProcessing}
634
+ />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635
  </div>
636
+ <div>
637
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
638
+ Organization ID
639
+ </label>
640
+ <input
641
+ type="text"
642
+ value={orgId}
643
+ onChange={(e) => setOrgId(e.target.value)}
644
+ placeholder="12345678"
645
+ className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent"
646
+ disabled={isProcessing}
647
+ />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
648
  </div>
649
+ <button
650
+ onClick={onConnect}
651
+ disabled={isProcessing || !accessToken.trim() || !orgId.trim()}
652
+ className="w-full px-6 py-3 bg-blue-600 text-white rounded-xl hover:bg-blue-700 disabled:opacity-50 font-semibold flex items-center justify-center gap-2 shadow-lg"
653
+ >
654
+ {isProcessing ? (
655
+ <>
656
+ <Loader2 className="w-5 h-5 animate-spin" />
657
+ Подключение...
658
+ </>
659
+ ) : (
660
+ <>
661
+ <Linkedin className="w-5 h-5" />
662
+ Подключить LinkedIn
663
+ </>
664
+ )}
665
+ </button>
666
  </div>
667
+ </div>
668
+ )}
669
+ </div>
670
+ )
671
+ }
672
+ <div className="ml-13 space-y-4">
673
+ {/* Access Token */}
674
+ <div className="p-4 bg-white border-2 border-slate-200 rounded-xl">
675
+ <div className="flex items-center justify-between mb-3">
676
+ <label className="block text-sm font-bold text-slate-900">
677
+ 📝 Access Token <span className="text-red-500">*</span>
678
+ </label>
679
+ <a
680
+ href={`https://developers.facebook.com/apps`}
681
+ target="_blank"
682
+ rel="noopener noreferrer"
683
+ className="text-xs text-indigo-600 hover:text-indigo-700 font-semibold inline-flex items-center gap-1"
684
+ >
685
+ Найти в Meta Developers
686
+ <ExternalLink className="w-3 h-3" />
687
+ </a>
688
+ </div>
689
+ <input
690
+ type="password"
691
+ value={accessToken}
692
+ onChange={(e) => setAccessToken(e.target.value)}
693
+ placeholder="EAAG... (вставьте токен из Meta Developers)"
694
+ className="w-full px-4 py-3 border-2 border-slate-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 font-mono text-sm"
695
+ disabled={isProcessing}
696
+ />
697
+ <p className="mt-2 text-xs text-slate-500">
698
+ 💡 <strong>Где найти:</strong> Meta Developers → Ваше приложение → {config.product} → "Access Token"
699
+ </p>
700
+ {/* Token Validation */}
701
+ {accessToken && (
702
+ <div className="mt-3 flex items-center gap-2">
703
+ {tokenValidating ? (
704
+ <>
705
+ <Loader2 className="w-4 h-4 animate-spin text-slate-400" />
706
+ <span className="text-xs text-slate-500">Проверяем токен...</span>
707
+ </>
708
+ ) : tokenValid === true ? (
709
+ <>
710
+ <CheckCircle className="w-5 h-5 text-emerald-600" />
711
+ <span className="text-sm text-emerald-600 font-bold">✓ Токен работает!</span>
712
+ </>
713
+ ) : tokenValid === false ? (
714
+ <>
715
+ <XCircle className="w-5 h-5 text-red-600" />
716
+ <span className="text-sm text-red-600 font-bold">✗ Неверный токен</span>
717
+ </>
718
+ ) : null}
719
+ </div>
720
+ )}
721
+ </div>
722
+
723
+ {/* Identifier (Phone Number ID / Page ID) */}
724
+ <div className="p-4 bg-white border-2 border-slate-200 rounded-xl">
725
+ <div className="flex items-center justify-between mb-3">
726
+ <label className="block text-sm font-bold text-slate-900">
727
+ {config.icon} {config.identifierLabel} <span className="text-red-500">*</span>
728
+ </label>
729
+ </div>
730
+ <input
731
+ type="text"
732
+ value={identifierId}
733
+ onChange={(e) => setIdentifierId(e.target.value)}
734
+ placeholder={`${config.identifierPlaceholder} (числовой ID)`}
735
+ className="w-full px-4 py-3 border-2 border-slate-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 font-mono text-sm"
736
+ disabled={isProcessing}
737
+ />
738
+ <p className="mt-2 text-xs text-slate-500">
739
+ 💡 <strong>Где найти:</strong> {config.identifierHelp}
740
+ </p>
741
+ </div>
742
+ </div>
743
+ </div >
744
+
745
+ {/* Step 3: Webhook Setup */ }
746
+ < div className = "border-l-4 border-emerald-500 pl-6 space-y-3" >
747
  <div className="flex items-center gap-3">
748
  <div className="w-10 h-10 bg-emerald-600 text-white rounded-full flex items-center justify-center font-bold text-lg shadow-lg">
749
  3️⃣
 
849
  </div>
850
  )}
851
  </div>
852
+ </div >
853
+ </div >
854
  )}
855
+ </div >
856
  )
857
  }
frontend/app/globals.css CHANGED
@@ -115,5 +115,31 @@ body {
115
 
116
  /* Premium transitions */
117
  * {
 
118
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
 
119
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
  /* Premium transitions */
117
  * {
118
+ transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter;
119
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
120
+ transition-duration: 150ms;
121
  }
122
+
123
+ /* Glassmorphism Utilities */
124
+ .glass {
125
+ background: rgba(255, 255, 255, 0.7);
126
+ backdrop-filter: blur(10px);
127
+ -webkit-backdrop-filter: blur(10px);
128
+ border: 1px solid rgba(255, 255, 255, 0.18);
129
+ }
130
+
131
+ .glass-dark {
132
+ background: rgba(15, 23, 42, 0.7);
133
+ backdrop-filter: blur(10px);
134
+ -webkit-backdrop-filter: blur(10px);
135
+ border: 1px solid rgba(255, 255, 255, 0.05);
136
+ }
137
+
138
+ /* Gradient Text */
139
+ .text-gradient {
140
+ background-clip: text;
141
+ -webkit-background-clip: text;
142
+ -webkit-text-fill-color: transparent;
143
+ background-image: linear-gradient(to right, var(--accent-primary), var(--accent-secondary));
144
+ }
145
+
frontend/app/knowledge/page.tsx CHANGED
@@ -4,15 +4,15 @@ import { useState, useCallback } from 'react'
4
  import { useDropzone } from 'react-dropzone'
5
  import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
6
  import { knowledgeApi } from '@/lib/api'
7
- import { Upload, FileText, Trash2, Search, Sparkles, BookOpen, AlertCircle, CheckCircle2, Loader2 } from 'lucide-react'
8
  import { cn } from '@/lib/utils'
9
  import { useAuth } from '@/contexts/AuthContext'
10
  import { useToast } from '@/contexts/ToastContext'
 
11
 
12
  export default function KnowledgePage() {
13
- const [uploadStatus, setUploadStatus] = useState<string>('')
14
  const [searchQuery, setSearchQuery] = useState('')
15
- const [uploadedFiles, setUploadedFiles] = useState<string[]>([]) // Track uploaded files
16
  const queryClient = useQueryClient()
17
  const { user, isLoading: authLoading } = useAuth()
18
  const toast = useToast()
@@ -39,7 +39,7 @@ export default function KnowledgePage() {
39
  toast.success('Успех!', `Файл "${file.name}" успешно загружен и изучен AI`)
40
  setUploadedFiles(prev => [...prev, file.name])
41
  setTimeout(() => {
42
- setUploadedFiles([])
43
  }, 3000)
44
  },
45
  onError: (error: Error) => {
@@ -47,23 +47,21 @@ export default function KnowledgePage() {
47
  },
48
  })
49
 
50
- const addTextMutation = useMutation({
51
- mutationFn: (content: string) => {
52
- if (!user) throw new Error('User not authenticated')
53
- return knowledgeApi.addKnowledge({
54
- content,
55
- source_type: 'manual',
56
- category: 'general'
57
- })
58
  },
59
  onSuccess: () => {
60
  queryClient.invalidateQueries({ queryKey: ['knowledge', user?.tenant_id] })
61
- },
 
62
  })
63
 
64
  const onDrop = useCallback((acceptedFiles: File[]) => {
65
  if (acceptedFiles.length === 0) return
66
-
67
  acceptedFiles.forEach((file) => {
68
  uploadMutation.mutate(file)
69
  })
@@ -79,199 +77,290 @@ export default function KnowledgePage() {
79
 
80
  if (authLoading || !user) {
81
  return (
82
- <div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-slate-50 via-indigo-50/30 to-purple-50/20">
83
- <div className="text-center">
84
- <div className="animate-spin rounded-full h-16 w-16 border-b-4 border-indigo-600 mx-auto mb-4"></div>
85
- <p className="text-lg font-semibold text-slate-700">Загрузка...</p>
86
- </div>
87
  </div>
88
  )
89
  }
90
 
91
  return (
92
- <div className="min-h-screen bg-gradient-to-br from-slate-50 via-indigo-50/30 to-purple-50/20">
93
- {/* Header */}
94
- <div className="bg-white border-b-2 border-indigo-100 shadow-sm">
95
- <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
96
- <div className="flex items-center gap-4">
97
- <div className="p-3 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-xl shadow-lg">
98
- <BookOpen className="w-8 h-8 text-white" />
99
- </div>
100
- <div>
101
- <h1 className="text-3xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
102
- База Знаний
103
- </h1>
104
- <p className="text-sm text-slate-600 mt-1 flex items-center gap-2">
105
- <Sparkles className="w-4 h-4 text-indigo-500" />
106
- Загрузка файлов и управление знаниями AI
107
- </p>
108
- </div>
109
  </div>
110
- </div>
111
- </div>
112
-
113
- {/* Main Content */}
114
- <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">
115
 
116
- {/* Upload Zone */}
117
- <div className="bg-white rounded-2xl shadow-lg border-2 border-indigo-100 p-6">
118
- <h2 className="text-lg font-bold text-slate-900 mb-4 flex items-center gap-2">
119
- <Upload className="w-5 h-5 text-indigo-600" />
120
- Загрузить файлы
121
- </h2>
122
- <div
123
- {...getRootProps()}
124
- className={cn(
125
- "border-2 border-dashed rounded-xl p-12 text-center cursor-pointer transition-all duration-300",
126
- isDragActive
127
- ? "border-indigo-500 bg-gradient-to-br from-indigo-50 to-purple-50 shadow-xl scale-[1.02]"
128
- : "border-slate-300 hover:border-indigo-400 bg-gradient-to-br from-slate-50 to-white hover:shadow-lg",
129
- uploadMutation.isPending && "opacity-50 cursor-wait"
130
- )}
131
  >
132
- <input {...getInputProps()} />
133
- <div className="flex flex-col items-center gap-3">
134
- {uploadMutation.isPending ? (
135
- <>
136
- <Loader2 className="w-16 h-16 text-indigo-600 animate-spin" />
137
- <p className="text-indigo-700 font-bold text-lg">Обработка файла...</p>
138
- <p className="text-sm text-indigo-600">AI анализирует содержимое</p>
139
- </>
140
- ) : isDragActive ? (
141
- <>
142
- <Upload className="w-16 h-16 text-indigo-600 animate-bounce" />
143
- <p className="text-indigo-700 font-bold text-lg">Отпустите файлы здесь...</p>
144
- </>
145
- ) : (
146
- <>
147
- <div className="p-4 bg-gradient-to-br from-indigo-100 to-purple-100 rounded-2xl mb-2">
148
- <Upload className="w-12 h-12 text-indigo-600" />
149
- </div>
150
- <p className="text-slate-900 font-bold text-lg mb-1">
151
- Перетащите PDF или TXT файлы сюда
152
- </p>
153
- <p className="text-sm text-slate-500">или кликните для выбора файлов</p>
154
- <div className="mt-4 flex items-center gap-4 text-xs text-slate-500">
155
- <div className="flex items-center gap-1">
156
- <CheckCircle2 className="w-4 h-4 text-emerald-600" />
157
- <span>PDF документы</span>
158
  </div>
159
- <div className="flex items-center gap-1">
160
- <CheckCircle2 className="w-4 h-4 text-emerald-600" />
161
- <span>TXT файлы</span>
162
  </div>
163
- </div>
164
- </>
165
- )}
166
- </div>
167
- </div>
168
- </div>
169
-
170
- {/* Search */}
171
- <div className="bg-white rounded-2xl shadow-lg border-2 border-indigo-100 p-6">
172
- <h2 className="text-lg font-bold text-slate-900 mb-4 flex items-center gap-2">
173
- <Search className="w-5 h-5 text-indigo-600" />
174
- Поиск в базе знаний
175
- </h2>
176
- <div className="relative">
177
- <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
178
- <input
179
- type="text"
180
- placeholder="Поиск..."
181
- value={searchQuery}
182
- onChange={(e) => setSearchQuery(e.target.value)}
183
- className="w-full pl-12 pr-4 py-3 border-2 border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-white text-sm shadow-sm transition-all"
184
- />
185
- </div>
186
-
187
- {searchQuery.length > 2 && (
188
- <div className="mt-4">
189
- <h3 className="font-bold text-slate-900 mb-3 text-sm flex items-center gap-2">
190
- <Sparkles className="w-4 h-4 text-indigo-600" />
191
- Результаты поиска ({searchResults?.count || 0})
192
- </h3>
193
- {isSearching ? (
194
- <div className="flex items-center justify-center py-8">
195
- <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
196
- </div>
197
- ) : searchResults?.results?.length > 0 ? (
198
- <div className="space-y-3">
199
- {searchResults.results.map((result: any, idx: number) => (
200
- <div key={idx} className="border-l-4 border-indigo-500 pl-4 py-3 bg-gradient-to-r from-indigo-50 to-purple-50 rounded-r-xl hover:shadow-md transition-shadow">
201
- <p className="text-sm text-slate-700 leading-relaxed">{result.content}</p>
202
- <p className="text-xs text-indigo-600 mt-2 font-semibold">
203
- Схожесть: {(result.similarity * 100).toFixed(1)}% • {result.category}
204
  </p>
 
 
 
 
 
 
 
 
 
 
 
205
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  ))}
207
  </div>
208
- ) : (
209
- <div className="text-center py-8">
210
- <AlertCircle className="w-12 h-12 mx-auto text-slate-300 mb-2" />
211
- <p className="text-slate-500 text-sm">Ничего не найдено</p>
212
- </div>
213
  )}
214
- </div>
215
- )}
216
- </div>
217
 
218
- {/* Knowledge List */}
219
- <div className="bg-white rounded-2xl shadow-lg border-2 border-indigo-100">
220
- <div className="p-6 border-b-2 border-slate-100">
221
- <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
222
- <FileText className="w-5 h-5 text-indigo-600" />
223
- Записи знаний ({knowledgeData?.count || 0})
224
- </h2>
225
- </div>
226
-
227
- <div className="p-6">
228
- {knowledgeLoading ? (
229
- <div className="flex items-center justify-center py-12">
230
- <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  </div>
232
- ) : knowledgeData?.entries?.length > 0 ? (
233
- <div className="space-y-3">
234
- {knowledgeData.entries.map((entry: any) => (
235
- <div key={entry.id} className="border-2 border-slate-200 rounded-xl p-4 hover:shadow-lg hover:border-indigo-300 transition-all duration-200 bg-gradient-to-br from-white to-slate-50">
236
- <div className="flex items-start justify-between">
237
- <div className="flex-1">
238
- <div className="flex items-center gap-2 mb-2">
239
- <div className="p-1.5 bg-indigo-100 rounded-lg">
240
- <FileText className="w-4 h-4 text-indigo-600" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  </div>
242
- <span className="text-xs font-bold text-indigo-600 uppercase tracking-wide">
243
- {entry.category || 'Без категории'}
244
- </span>
245
- {entry.tags && (
246
- <span className="text-xs text-slate-500">• {entry.tags}</span>
247
- )}
248
  </div>
249
- <p className="text-sm text-slate-700 leading-relaxed mb-2">{entry.content}</p>
250
- <p className="text-xs text-slate-500 font-medium flex items-center gap-2">
251
- <span className="px-2 py-0.5 bg-slate-100 rounded">{entry.source_type}</span>
252
- <span>•</span>
253
- <span>{new Date(entry.created_at).toLocaleDateString('ru-RU')}</span>
254
- </p>
255
  </div>
256
- <button className="text-red-600 hover:text-white hover:bg-red-600 p-2 rounded-lg transition-all ml-4">
257
- <Trash2 className="w-4 h-4" />
258
- </button>
 
 
 
259
  </div>
 
 
260
  </div>
261
- ))}
262
  </div>
263
- ) : (
264
- <div className="text-center py-16">
265
- <div className="w-16 h-16 bg-gradient-to-br from-slate-100 to-slate-200 rounded-2xl flex items-center justify-center mx-auto mb-4">
266
- <FileText className="w-8 h-8 text-slate-400" />
267
- </div>
268
- <h3 className="font-bold text-slate-900 mb-2">Нет записей</h3>
269
- <p className="text-sm text-slate-500">Загрузите файлы для начала работы!</p>
270
- </div>
271
- )}
272
  </div>
273
  </div>
274
- </div>
275
  </div>
276
  )
277
  }
 
4
  import { useDropzone } from 'react-dropzone'
5
  import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
6
  import { knowledgeApi } from '@/lib/api'
7
+ import { Upload, FileText, Trash2, Search, Sparkles, BookOpen, AlertCircle, CheckCircle2, Loader2, X } from 'lucide-react'
8
  import { cn } from '@/lib/utils'
9
  import { useAuth } from '@/contexts/AuthContext'
10
  import { useToast } from '@/contexts/ToastContext'
11
+ import { motion, AnimatePresence } from 'framer-motion'
12
 
13
  export default function KnowledgePage() {
 
14
  const [searchQuery, setSearchQuery] = useState('')
15
+ const [uploadedFiles, setUploadedFiles] = useState<string[]>([])
16
  const queryClient = useQueryClient()
17
  const { user, isLoading: authLoading } = useAuth()
18
  const toast = useToast()
 
39
  toast.success('Успех!', `Файл "${file.name}" успешно загружен и изучен AI`)
40
  setUploadedFiles(prev => [...prev, file.name])
41
  setTimeout(() => {
42
+ setUploadedFiles(prev => prev.filter(f => f !== file.name))
43
  }, 3000)
44
  },
45
  onError: (error: Error) => {
 
47
  },
48
  })
49
 
50
+ const deleteMutation = useMutation({
51
+ mutationFn: async (id: string) => {
52
+ // Implement delete API call here if available
53
+ // await knowledgeApi.delete(id)
54
+ return Promise.resolve()
 
 
 
55
  },
56
  onSuccess: () => {
57
  queryClient.invalidateQueries({ queryKey: ['knowledge', user?.tenant_id] })
58
+ toast.success('Удалено', 'Запись удалена из базы знаний')
59
+ }
60
  })
61
 
62
  const onDrop = useCallback((acceptedFiles: File[]) => {
63
  if (acceptedFiles.length === 0) return
64
+
65
  acceptedFiles.forEach((file) => {
66
  uploadMutation.mutate(file)
67
  })
 
77
 
78
  if (authLoading || !user) {
79
  return (
80
+ <div className="flex items-center justify-center min-h-screen bg-slate-50">
81
+ <Loader2 className="w-12 h-12 animate-spin text-indigo-600" />
 
 
 
82
  </div>
83
  )
84
  }
85
 
86
  return (
87
+ <div className="min-h-screen bg-slate-50/50 p-8">
88
+ <div className="max-w-5xl mx-auto space-y-8">
89
+ {/* Header */}
90
+ <motion.div
91
+ initial={{ opacity: 0, y: -20 }}
92
+ animate={{ opacity: 1, y: 0 }}
93
+ className="flex items-center justify-between"
94
+ >
95
+ <div>
96
+ <h1 className="text-3xl font-bold text-slate-900 mb-2 tracking-tight flex items-center gap-3">
97
+ База Знаний
98
+ </h1>
99
+ <p className="text-slate-600">
100
+ Загрузка файлов и управление знаниями AI для ответов клиентам
101
+ </p>
 
 
102
  </div>
103
+ <div className="w-12 h-12 bg-indigo-50 rounded-2xl flex items-center justify-center">
104
+ <BookOpen className="w-6 h-6 text-indigo-600" />
105
+ </div>
106
+ </motion.div>
 
107
 
108
+ {/* Upload Zone */}
109
+ <motion.div
110
+ initial={{ opacity: 0, y: 20 }}
111
+ animate={{ opacity: 1, y: 0 }}
112
+ transition={{ delay: 0.1 }}
113
+ className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8"
 
 
 
 
 
 
 
 
 
114
  >
115
+ <h2 className="text-lg font-bold text-slate-900 mb-6 flex items-center gap-2">
116
+ <Upload className="w-5 h-5 text-indigo-600" />
117
+ Загрузить файлы
118
+ </h2>
119
+ <div
120
+ {...getRootProps()}
121
+ className={cn(
122
+ "border-2 border-dashed rounded-xl p-12 text-center cursor-pointer transition-all duration-300 relative overflow-hidden",
123
+ isDragActive
124
+ ? "border-indigo-500 bg-indigo-50/50 scale-[1.01]"
125
+ : "border-slate-200 hover:border-indigo-400 hover:bg-slate-50",
126
+ uploadMutation.isPending && "opacity-75 cursor-wait"
127
+ )}
128
+ >
129
+ <input {...getInputProps()} />
130
+ <div className="flex flex-col items-center gap-4 relative z-10">
131
+ {uploadMutation.isPending ? (
132
+ <>
133
+ <div className="p-4 bg-indigo-50 rounded-full">
134
+ <Loader2 className="w-8 h-8 text-indigo-600 animate-spin" />
 
 
 
 
 
 
135
  </div>
136
+ <div>
137
+ <p className="text-indigo-900 font-bold text-lg">Обработка файла...</p>
138
+ <p className="text-sm text-indigo-600">AI анализирует содержимое</p>
139
  </div>
140
+ </>
141
+ ) : isDragActive ? (
142
+ <>
143
+ <div className="p-4 bg-indigo-100 rounded-full animate-bounce">
144
+ <Upload className="w-8 h-8 text-indigo-600" />
145
+ </div>
146
+ <p className="text-indigo-900 font-bold text-lg">Отпустите файлы здесь...</p>
147
+ </>
148
+ ) : (
149
+ <>
150
+ <div className="p-4 bg-slate-100 rounded-full group-hover:bg-indigo-50 transition-colors">
151
+ <Upload className="w-8 h-8 text-slate-400 group-hover:text-indigo-600 transition-colors" />
152
+ </div>
153
+ <div>
154
+ <p className="text-slate-900 font-bold text-lg mb-1">
155
+ Перетащите PDF или TXT файлы сюда
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  </p>
157
+ <p className="text-sm text-slate-500">или кликните для выбора файлов</p>
158
+ </div>
159
+ <div className="flex items-center gap-4 text-xs font-medium text-slate-400 mt-2">
160
+ <span className="flex items-center gap-1.5 bg-slate-50 px-2 py-1 rounded-md border border-slate-100">
161
+ <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
162
+ PDF документы
163
+ </span>
164
+ <span className="flex items-center gap-1.5 bg-slate-50 px-2 py-1 rounded-md border border-slate-100">
165
+ <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
166
+ TXT файлы
167
+ </span>
168
  </div>
169
+ </>
170
+ )}
171
+ </div>
172
+ </div>
173
+
174
+ {/* Uploaded Files List */}
175
+ <AnimatePresence>
176
+ {uploadedFiles.length > 0 && (
177
+ <div className="mt-6 space-y-2">
178
+ {uploadedFiles.map((fileName, idx) => (
179
+ <motion.div
180
+ key={`${fileName}-${idx}`}
181
+ initial={{ opacity: 0, x: -20 }}
182
+ animate={{ opacity: 1, x: 0 }}
183
+ exit={{ opacity: 0, x: 20 }}
184
+ className="flex items-center gap-3 p-3 bg-emerald-50 border border-emerald-100 rounded-xl text-emerald-700"
185
+ >
186
+ <CheckCircle2 className="w-5 h-5 text-emerald-500 flex-shrink-0" />
187
+ <span className="text-sm font-medium truncate flex-1">{fileName}</span>
188
+ <span className="text-xs font-bold bg-white/50 px-2 py-1 rounded-md">Загружено</span>
189
+ </motion.div>
190
  ))}
191
  </div>
 
 
 
 
 
192
  )}
193
+ </AnimatePresence>
194
+ </motion.div>
 
195
 
196
+ {/* Search & Results */}
197
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
198
+ {/* Search Column */}
199
+ <motion.div
200
+ initial={{ opacity: 0, y: 20 }}
201
+ animate={{ opacity: 1, y: 0 }}
202
+ transition={{ delay: 0.2 }}
203
+ className="lg:col-span-2 space-y-6"
204
+ >
205
+ <div className="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
206
+ <h2 className="text-lg font-bold text-slate-900 mb-4 flex items-center gap-2">
207
+ <Search className="w-5 h-5 text-indigo-600" />
208
+ Поиск в базе знаний
209
+ </h2>
210
+ <div className="relative">
211
+ <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
212
+ <input
213
+ type="text"
214
+ placeholder="Введите вопрос или ключевые слова..."
215
+ value={searchQuery}
216
+ onChange={(e) => setSearchQuery(e.target.value)}
217
+ className="w-full pl-12 pr-10 py-4 bg-slate-50 border-2 border-slate-200 rounded-xl focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500 transition-all font-medium text-slate-900 placeholder:text-slate-400"
218
+ />
219
+ {searchQuery && (
220
+ <button
221
+ onClick={() => setSearchQuery('')}
222
+ className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
223
+ >
224
+ <X className="w-4 h-4" />
225
+ </button>
226
+ )}
227
+ </div>
228
+
229
+ <AnimatePresence mode="wait">
230
+ {searchQuery.length > 2 && (
231
+ <motion.div
232
+ initial={{ opacity: 0, height: 0 }}
233
+ animate={{ opacity: 1, height: 'auto' }}
234
+ exit={{ opacity: 0, height: 0 }}
235
+ className="mt-6"
236
+ >
237
+ <div className="flex items-center justify-between mb-4">
238
+ <h3 className="font-bold text-slate-900 text-sm flex items-center gap-2">
239
+ <Sparkles className="w-4 h-4 text-indigo-600" />
240
+ Результаты поиска
241
+ </h3>
242
+ <span className="text-xs font-medium text-slate-500 bg-slate-100 px-2 py-1 rounded-md">
243
+ {searchResults?.count || 0} найдено
244
+ </span>
245
+ </div>
246
+
247
+ {isSearching ? (
248
+ <div className="flex flex-col items-center justify-center py-12 text-slate-400">
249
+ <Loader2 className="w-8 h-8 animate-spin mb-2" />
250
+ <span className="text-sm">Ищем ответы...</span>
251
+ </div>
252
+ ) : searchResults?.results?.length > 0 ? (
253
+ <div className="space-y-4">
254
+ {searchResults.results.map((result: any, idx: number) => (
255
+ <motion.div
256
+ key={idx}
257
+ initial={{ opacity: 0, y: 10 }}
258
+ animate={{ opacity: 1, y: 0 }}
259
+ transition={{ delay: idx * 0.05 }}
260
+ className="group p-4 bg-white border border-slate-200 rounded-xl hover:border-indigo-300 hover:shadow-md transition-all relative overflow-hidden"
261
+ >
262
+ <div className="absolute left-0 top-0 bottom-0 w-1 bg-indigo-500 opacity-0 group-hover:opacity-100 transition-opacity" />
263
+ <p className="text-sm text-slate-700 leading-relaxed mb-3">{result.content}</p>
264
+ <div className="flex items-center justify-between text-xs">
265
+ <span className="font-bold text-indigo-600 bg-indigo-50 px-2 py-1 rounded-md">
266
+ {((result.similarity || 0) * 100).toFixed(0)}% совпадение
267
+ </span>
268
+ <span className="text-slate-400 font-medium uppercase tracking-wide">
269
+ {result.category || 'Общее'}
270
+ </span>
271
+ </div>
272
+ </motion.div>
273
+ ))}
274
+ </div>
275
+ ) : (
276
+ <div className="text-center py-12 bg-slate-50 rounded-xl border border-dashed border-slate-200">
277
+ <AlertCircle className="w-10 h-10 mx-auto text-slate-300 mb-3" />
278
+ <p className="text-slate-900 font-medium">Ничего не найдено</p>
279
+ <p className="text-sm text-slate-500">Попробуйте изменить запрос</p>
280
+ </div>
281
+ )}
282
+ </motion.div>
283
+ )}
284
+ </AnimatePresence>
285
  </div>
286
+ </motion.div>
287
+
288
+ {/* Files List Column */}
289
+ <motion.div
290
+ initial={{ opacity: 0, y: 20 }}
291
+ animate={{ opacity: 1, y: 0 }}
292
+ transition={{ delay: 0.3 }}
293
+ className="bg-white rounded-2xl shadow-sm border border-slate-200 flex flex-col h-[600px]"
294
+ >
295
+ <div className="p-6 border-b border-slate-100 flex items-center justify-between bg-slate-50/50 rounded-t-2xl">
296
+ <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
297
+ <FileText className="w-5 h-5 text-indigo-600" />
298
+ Файлы
299
+ </h2>
300
+ <span className="text-xs font-bold bg-white border border-slate-200 px-2 py-1 rounded-md text-slate-600">
301
+ {knowledgeData?.count || 0}
302
+ </span>
303
+ </div>
304
+
305
+ <div className="flex-1 overflow-y-auto p-4 space-y-3 custom-scrollbar">
306
+ {knowledgeLoading ? (
307
+ <div className="flex items-center justify-center h-full text-slate-400">
308
+ <Loader2 className="w-8 h-8 animate-spin" />
309
+ </div>
310
+ ) : knowledgeData?.entries?.length > 0 ? (
311
+ knowledgeData.entries.map((entry: any) => (
312
+ <motion.div
313
+ key={entry.id}
314
+ layout
315
+ initial={{ opacity: 0 }}
316
+ animate={{ opacity: 1 }}
317
+ className="group p-4 bg-white border border-slate-200 rounded-xl hover:border-indigo-300 hover:shadow-sm transition-all"
318
+ >
319
+ <div className="flex items-start gap-3">
320
+ <div className="p-2 bg-indigo-50 text-indigo-600 rounded-lg flex-shrink-0 group-hover:bg-indigo-100 transition-colors">
321
+ <FileText className="w-5 h-5" />
322
+ </div>
323
+ <div className="flex-1 min-w-0">
324
+ <div className="flex items-center gap-2 mb-1">
325
+ <span className="text-xs font-bold text-indigo-600 uppercase tracking-wide bg-indigo-50 px-1.5 py-0.5 rounded">
326
+ {entry.category || 'DOC'}
327
+ </span>
328
+ <span className="text-[10px] text-slate-400">
329
+ {new Date(entry.created_at).toLocaleDateString()}
330
+ </span>
331
+ </div>
332
+ <p className="text-sm text-slate-700 line-clamp-2 leading-relaxed mb-2">
333
+ {entry.content}
334
+ </p>
335
+ <div className="flex items-center justify-between">
336
+ <span className="text-xs text-slate-500 font-medium bg-slate-50 px-2 py-1 rounded border border-slate-100">
337
+ {entry.source_type}
338
+ </span>
339
+ <button
340
+ onClick={() => deleteMutation.mutate(entry.id)}
341
+ className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
342
+ title="Удалить"
343
+ >
344
+ <Trash2 className="w-4 h-4" />
345
+ </button>
346
  </div>
 
 
 
 
 
 
347
  </div>
 
 
 
 
 
 
348
  </div>
349
+ </motion.div>
350
+ ))
351
+ ) : (
352
+ <div className="flex flex-col items-center justify-center h-full text-center p-8">
353
+ <div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mb-4">
354
+ <FileText className="w-8 h-8 text-slate-300" />
355
  </div>
356
+ <h3 className="font-bold text-slate-900 mb-1">Пусто</h3>
357
+ <p className="text-sm text-slate-500">Загрузите файлы, чтобы наполнить базу знаний</p>
358
  </div>
359
+ )}
360
  </div>
361
+ </motion.div>
 
 
 
 
 
 
 
 
362
  </div>
363
  </div>
 
364
  </div>
365
  )
366
  }
frontend/app/page.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
frontend/app/settings/billing/page.tsx CHANGED
@@ -3,7 +3,9 @@
3
  import { useState, useEffect } from 'react'
4
  import { useAuth } from '@/contexts/AuthContext'
5
  import { billingApi } from '@/lib/api'
6
- import { Check, Loader2, Zap, TrendingUp, Crown, Sparkles } from 'lucide-react'
 
 
7
 
8
  export default function BillingPage() {
9
  const { user } = useAuth()
@@ -24,7 +26,7 @@ export default function BillingPage() {
24
  billingApi.getTenantInfo(),
25
  billingApi.calculateOverage()
26
  ])
27
-
28
  setCurrentPlan(tenantData.subscription_plan || 'start')
29
  setSubscriptionStatus(tenantData.subscription_status || 'trial')
30
  setUsageData(overageData)
@@ -48,10 +50,10 @@ export default function BillingPage() {
48
  setIsUpgrading(planId)
49
 
50
  try {
51
- const endpoint = isTrialConversion
52
- ? billingApi.convertTrial
53
  : billingApi.upgradeSubscription
54
-
55
  const data = await endpoint(planId)
56
 
57
  if (data.success) {
@@ -114,43 +116,71 @@ export default function BillingPage() {
114
 
115
  if (isLoading) {
116
  return (
117
- <div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-slate-50 to-slate-100">
118
- <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
119
  </div>
120
  )
121
  }
122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  return (
124
- <div className="min-h-screen bg-gradient-to-br from-slate-50 via-slate-100 to-indigo-50 p-8">
125
  <div className="max-w-7xl mx-auto">
126
  {/* Header */}
127
- <div className="text-center mb-12">
128
- <h1 className="text-5xl font-bold text-slate-900 mb-4 tracking-tight">
 
 
 
 
129
  Выберите свой план
130
  </h1>
131
- <p className="text-xl text-slate-600 max-w-2xl mx-auto">
132
  Масштабируйте свой бизнес с AI-автоматизацией продаж. Все планы включают 14 дней бесплатно.
133
  </p>
134
  {subscriptionStatus === 'active' && (
135
- <div className="mt-4 inline-flex items-center gap-2 px-4 py-2 bg-emerald-50 border border-emerald-200 rounded-full">
 
 
 
 
136
  <Check className="w-4 h-4 text-emerald-600" />
137
  <span className="text-sm text-emerald-700 font-semibold">
138
  Текущий план: {currentPlan.toUpperCase()}
139
  </span>
140
- </div>
141
  )}
142
- </div>
143
 
144
  {/* Pricing Cards */}
145
- <div className="grid grid-cols-1 md:grid-cols-3 gap-8 mb-12">
 
 
 
 
 
146
  {/* START Plan */}
147
- <div className="bg-white rounded-3xl shadow-lg border-2 border-slate-200 overflow-hidden hover:shadow-2xl transition-all duration-300 hover:-translate-y-1">
148
  <div className="p-8">
149
  <div className="inline-flex items-center gap-2 px-3 py-1 bg-slate-100 rounded-full mb-4">
150
  <Zap className="w-4 h-4 text-slate-600" />
151
  <span className="text-xs font-bold text-slate-700 uppercase tracking-wide">Starter</span>
152
  </div>
153
-
154
  <div className="mb-6">
155
  <div className="flex items-baseline gap-2">
156
  <span className="text-5xl font-bold text-slate-900">$99</span>
@@ -159,23 +189,20 @@ export default function BillingPage() {
159
  <p className="text-sm text-slate-500 mt-2">Для малого бизнеса</p>
160
  </div>
161
 
162
- <ul className="space-y-3 mb-8">
163
- <li className="flex items-start gap-3">
164
- <Check className="w-5 h-5 text-emerald-500 flex-shrink-0 mt-0.5" />
165
- <span className="text-sm text-slate-700">До 1,000 лидов/месяц</span>
166
- </li>
167
- <li className="flex items-start gap-3">
168
- <Check className="w-5 h-5 text-emerald-500 flex-shrink-0 mt-0.5" />
169
- <span className="text-sm text-slate-700">1 канал (Telegram/WhatsApp/Instagram)</span>
170
- </li>
171
- <li className="flex items-start gap-3">
172
- <Check className="w-5 h-5 text-emerald-500 flex-shrink-0 mt-0.5" />
173
- <span className="text-sm text-slate-700">Базовая AI-квалификация</span>
174
- </li>
175
- <li className="flex items-start gap-3">
176
- <Check className="w-5 h-5 text-emerald-500 flex-shrink-0 mt-0.5" />
177
- <span className="text-sm text-slate-700">Email поддержка</span>
178
- </li>
179
  </ul>
180
 
181
  {currentPlan === 'start' ? (
@@ -189,18 +216,18 @@ export default function BillingPage() {
189
  <button
190
  onClick={() => handleDowngrade('START', 'Starter')}
191
  disabled={isUpgrading !== null}
192
- className="w-full py-3 px-6 border-2 border-slate-300 text-slate-700 rounded-xl font-semibold hover:bg-slate-50 transition-colors disabled:opacity-50"
193
  >
194
  Понизить до Starter
195
  </button>
196
  )}
197
  </div>
198
- </div>
199
 
200
  {/* GROWTH Plan - Popular */}
201
- <div className="bg-white rounded-3xl shadow-2xl border-2 border-indigo-500 overflow-hidden relative transform hover:scale-105 transition-all duration-300">
202
  {/* Popular Badge */}
203
- <div className="absolute top-0 right-0 bg-gradient-to-r from-indigo-600 to-purple-600 text-white px-6 py-1.5 rounded-bl-2xl">
204
  <span className="text-xs font-bold uppercase tracking-wide">Популярный</span>
205
  </div>
206
 
@@ -209,7 +236,7 @@ export default function BillingPage() {
209
  <TrendingUp className="w-4 h-4 text-indigo-600" />
210
  <span className="text-xs font-bold text-indigo-700 uppercase tracking-wide">Growth</span>
211
  </div>
212
-
213
  <div className="mb-6">
214
  <div className="flex items-baseline gap-2">
215
  <span className="text-5xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">$199</span>
@@ -218,33 +245,27 @@ export default function BillingPage() {
218
  <p className="text-sm text-slate-500 mt-2">Для растущих команд</p>
219
  </div>
220
 
221
- <ul className="space-y-3 mb-8">
222
- <li className="flex items-start gap-3">
223
- <Check className="w-5 h-5 text-indigo-500 flex-shrink-0 mt-0.5" />
224
- <span className="text-sm text-slate-700 font-medium">До 10,000 лидов/месяц</span>
225
- </li>
226
- <li className="flex items-start gap-3">
227
- <Check className="w-5 h-5 text-indigo-500 flex-shrink-0 mt-0.5" />
228
- <span className="text-sm text-slate-700 font-medium">Все каналы (Telegram + WhatsApp + Instagram)</span>
229
- </li>
230
- <li className="flex items-start gap-3">
231
- <Check className="w-5 h-5 text-indigo-500 flex-shrink-0 mt-0.5" />
232
- <span className="text-sm text-slate-700 font-medium">Продвинутая AI-квалификация</span>
233
- </li>
234
- <li className="flex items-start gap-3">
235
- <Check className="w-5 h-5 text-indigo-500 flex-shrink-0 mt-0.5" />
236
- <span className="text-sm text-slate-700 font-medium">Приоритетная поддержка</span>
237
- </li>
238
- <li className="flex items-start gap-3">
239
- <Check className="w-5 h-5 text-indigo-500 flex-shrink-0 mt-0.5" />
240
- <span className="text-sm text-slate-700 font-medium">Аналитика и отчеты</span>
241
- </li>
242
  </ul>
243
 
244
  {currentPlan === 'growth' ? (
245
  <button
246
  disabled
247
- className="w-full py-3 px-6 bg-gradient-to-r from-indigo-100 to-purple-100 text-indigo-700 rounded-xl font-semibold cursor-not-allowed"
248
  >
249
  Текущий план
250
  </button>
@@ -252,7 +273,7 @@ export default function BillingPage() {
252
  <button
253
  onClick={() => handleUpgrade('GROWTH', 'Growth', 199)}
254
  disabled={isUpgrading !== null}
255
- className="w-full py-3 px-6 bg-gradient-to-r from-indigo-600 to-purple-600 text-white rounded-xl font-semibold hover:from-indigo-500 hover:to-purple-500 shadow-lg hover:shadow-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
256
  >
257
  {isUpgrading === 'GROWTH' ? (
258
  <>
@@ -267,49 +288,43 @@ export default function BillingPage() {
267
  </button>
268
  )}
269
  </div>
270
- </div>
271
 
272
  {/* SCALE Plan */}
273
- <div className="bg-gradient-to-br from-slate-900 to-indigo-900 rounded-3xl shadow-2xl overflow-hidden relative hover:shadow-3xl transition-all duration-300 hover:-translate-y-1">
274
- <div className="p-8">
275
- <div className="inline-flex items-center gap-2 px-3 py-1 bg-white/10 backdrop-blur rounded-full mb-4">
276
- <Crown className="w-4 h-4 text-yellow-400" />
 
 
 
277
  <span className="text-xs font-bold text-white uppercase tracking-wide">Scale</span>
278
  </div>
279
-
280
  <div className="mb-6">
281
  <div className="flex items-baseline gap-2">
282
  <span className="text-5xl font-bold text-white">$499</span>
283
- <span className="text-indigo-200">/месяц</span>
284
  </div>
285
- <p className="text-sm text-indigo-300 mt-2">Для агентств</p>
286
  </div>
287
 
288
- <ul className="space-y-3 mb-8">
289
- <li className="flex items-start gap-3">
290
- <Check className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
291
- <span className="text-sm text-white font-medium">Безлимитные лиды</span>
292
- </li>
293
- <li className="flex items-start gap-3">
294
- <Check className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
295
- <span className="text-sm text-white font-medium">Все каналы + API доступ</span>
296
- </li>
297
- <li className="flex items-start gap-3">
298
- <Check className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
299
- <span className="text-sm text-white font-medium">Персонализированный AI</span>
300
- </li>
301
- <li className="flex items-start gap-3">
302
- <Check className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
303
- <span className="text-sm text-white font-medium">Выделенный менеджер</span>
304
- </li>
305
- <li className="flex items-start gap-3">
306
- <Check className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
307
- <span className="text-sm text-white font-medium">White-label опции</span>
308
- </li>
309
- <li className="flex items-start gap-3">
310
- <Check className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
311
- <span className="text-sm text-white font-medium">SLA 99.9%</span>
312
- </li>
313
  </ul>
314
 
315
  {currentPlan === 'scale' ? (
@@ -338,175 +353,215 @@ export default function BillingPage() {
338
  </button>
339
  )}
340
  </div>
341
- </div>
342
- </div>
343
 
344
  {/* Feature Comparison */}
345
- <div className="bg-white rounded-2xl shadow-lg border border-slate-200 p-8">
 
 
 
 
 
346
  <h2 className="text-2xl font-bold text-slate-900 mb-6 flex items-center gap-2">
347
  <Sparkles className="w-6 h-6 text-indigo-600" />
348
  Сравнение функций
349
  </h2>
350
-
351
  <div className="overflow-x-auto">
352
  <table className="w-full">
353
  <thead>
354
- <tr className="border-b border-slate-200">
355
- <th className="text-left py-3 px-4 text-sm font-semibold text-slate-700">Функция</th>
356
- <th className="text-center py-3 px-4 text-sm font-semibold text-slate-700">Starter</th>
357
- <th className="text-center py-3 px-4 text-sm font-semibold text-indigo-700">Growth</th>
358
- <th className="text-center py-3 px-4 text-sm font-semibold text-slate-700">Scale</th>
359
  </tr>
360
  </thead>
361
- <tbody className="divide-y divide-slate-100">
362
- <tr>
363
- <td className="py-3 px-4 text-sm text-slate-700">Лиды в месяц</td>
364
- <td className="py-3 px-4 text-sm text-center text-slate-600">1,000</td>
365
- <td className="py-3 px-4 text-sm text-center text-indigo-600 font-semibold">10,000</td>
366
- <td className="py-3 px-4 text-sm text-center text-slate-600">Безлимит</td>
367
- </tr>
368
- <tr>
369
- <td className="py-3 px-4 text-sm text-slate-700">Каналы</td>
370
- <td className="py-3 px-4 text-sm text-center text-slate-600">1</td>
371
- <td className="py-3 px-4 text-sm text-center text-indigo-600 font-semibold">Все</td>
372
- <td className="py-3 px-4 text-sm text-center text-slate-600">Все + API</td>
373
- </tr>
374
- <tr>
375
- <td className="py-3 px-4 text-sm text-slate-700">AI-ассистент</td>
376
- <td className="py-3 px-4 text-center"><Check className="w-5 h-5 text-emerald-500 mx-auto" /></td>
377
- <td className="py-3 px-4 text-center"><Check className="w-5 h-5 text-indigo-500 mx-auto" /></td>
378
- <td className="py-3 px-4 text-center"><Check className="w-5 h-5 text-emerald-500 mx-auto" /></td>
379
- </tr>
380
- <tr>
381
- <td className="py-3 px-4 text-sm text-slate-700">Поддержка</td>
382
- <td className="py-3 px-4 text-sm text-center text-slate-600">Email</td>
383
- <td className="py-3 px-4 text-sm text-center text-indigo-600 font-semibold">Приоритет</td>
384
- <td className="py-3 px-4 text-sm text-center text-slate-600">24/7 менеджер</td>
385
- </tr>
386
  </tbody>
387
  </table>
388
  </div>
389
- </div>
390
 
391
  {/* Usage & Overage Section */}
392
- {usageData && subscriptionStatus === 'active' && (
393
- <div className="bg-white rounded-2xl shadow-lg border border-slate-200 p-8 mb-8">
394
- <h2 className="text-2xl font-bold text-slate-900 mb-6">Использование за месяц</h2>
395
-
396
- <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
397
- <div className="bg-gradient-to-br from-indigo-50 to-purple-50 rounded-xl p-6 border border-indigo-100">
398
- <p className="text-sm text-slate-600 mb-2">Лидов использовано</p>
399
- <p className="text-3xl font-bold text-indigo-600">{usageData.leads_used.toLocaleString()}</p>
400
- <p className="text-xs text-slate-500 mt-1">из {usageData.plan_limit.toLocaleString()} включено</p>
401
- </div>
402
-
403
- {usageData.overage_count > 0 && (
404
- <>
405
- <div className="bg-gradient-to-br from-amber-50 to-orange-50 rounded-xl p-6 border border-amber-200">
406
- <p className="text-sm text-slate-600 mb-2">Превышение лимита</p>
407
- <p className="text-3xl font-bold text-amber-600">{usageData.overage_count.toLocaleString()}</p>
408
- <p className="text-xs text-slate-500 mt-1">дополнительных лидов</p>
409
- </div>
 
410
 
411
- <div className="bg-gradient-to-br from-rose-50 to-pink-50 rounded-xl p-6 border border-rose-200">
412
- <p className="text-sm text-slate-600 mb-2">Доплата за превышение</p>
413
- <p className="text-3xl font-bold text-rose-600">${usageData.overage_cost}</p>
414
- <p className="text-xs text-slate-500 mt-1">будет списано при продлении</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
415
  </div>
416
- </>
417
- )}
418
 
419
- {usageData.overage_count === 0 && (
420
- <div className="bg-gradient-to-br from-emerald-50 to-teal-50 rounded-xl p-6 border border-emerald-200">
421
- <p className="text-sm text-slate-600 mb-2">Статус</p>
422
- <p className="text-3xl font-bold text-emerald-600">✅ ОК</p>
423
- <p className="text-xs text-slate-500 mt-1">В пределах лимита</p>
 
424
  </div>
425
  )}
426
- </div>
427
-
428
- {usageData.overage_count > 0 && (
429
- <div className="mt-6 p-4 bg-amber-50 border border-amber-200 rounded-lg">
430
- <p className="text-sm text-amber-800">
431
- <strong>ℹ️ Внимание:</strong> Вы превысили лимит плана. Дополнительные лиды будут включены в следующий платёж. Рассмотрите апгрейд до GROWTH или SCALE для большего лимита.
432
- </p>
433
- </div>
434
- )}
435
- </div>
436
- )}
437
 
438
  {/* Cancel Subscription Button */}
439
  {subscriptionStatus === 'active' && (
440
- <div className="bg-white rounded-2xl shadow-lg border border-slate-200 p-8 mb-8">
441
- <h2 className="text-2xl font-bold text-slate-900 mb-4">Управление подпиской</h2>
442
- <p className="text-slate-600 mb-4">
443
- Если вы хотите отменить подписку, доступ сохранится до конца оплаченного периода.
444
- </p>
445
- <button
446
- onClick={() => setShowCancelModal(true)}
447
- className="px-6 py-3 bg-red-50 text-red-600 border border-red-200 rounded-xl font-semibold hover:bg-red-100 transition-colors"
448
- >
449
- Отменить подписку
450
- </button>
451
- </div>
 
 
 
 
 
 
 
 
 
452
  )}
453
 
454
  {/* Cancel Modal */}
455
- {showCancelModal && (
456
- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
457
- <div className="bg-white rounded-2xl p-8 max-w-md w-full">
458
- <h3 className="text-2xl font-bold text-slate-900 mb-4">Отмена подписки</h3>
459
- <p className="text-slate-600 mb-6">
460
- Мы хотим стать лучше. Пожалуйста, укажите причину отмены:
461
- </p>
462
-
463
- <select
464
- id="cancel-reason"
465
- className="w-full mb-4 px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
 
 
466
  >
467
- <option value="">Выберите причину...</option>
468
- <option value="too_expensive">Слишком дорого</option>
469
- <option value="not_using">Не использую</option>
470
- <option value="missing_features">Нехватает функций</option>
471
- <option value="technical_issues">Технические проблемы</option>
472
- <option value="found_alternative">Нашёл альтернативу</option>
473
- <option value="other">Другое</option>
474
- </select>
475
-
476
- <textarea
477
- id="cancel-feedback"
478
- placeholder="Дополнительные комментарии (опционально)"
479
- className="w-full mb-6 px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 resize-none"
480
- rows={3}
481
- />
482
-
483
- <div className="flex gap-3">
484
- <button
485
- onClick={() => setShowCancelModal(false)}
486
- className="flex-1 px-6 py-3 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200 transition-colors"
487
- >
488
- Отмена
489
- </button>
490
- <button
491
- onClick={() => {
492
- const reason = (document.getElementById('cancel-reason') as HTMLSelectElement)?.value || 'not_specified'
493
- const feedback = (document.getElementById('cancel-feedback') as HTMLTextAreaElement)?.value || ''
494
- handleCancel(reason, feedback)
495
- }}
496
- className="flex-1 px-6 py-3 bg-red-600 text-white rounded-xl font-semibold hover:bg-red-700 transition-colors"
497
  >
498
- Подтвердить отмену
499
- </button>
500
- </div>
501
- </div>
502
- </div>
503
- )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504
 
505
  {/* Trust Section */}
506
- <div className="text-center mt-12 text-sm text-slate-600">
507
- <p className="mb-2">🔒 Безопасная оплата • Отмена в любое время • Гарантия возврата 30 дней</p>
508
- <p className="text-xs text-slate-500">Все цены указаны в USD. Автоматическое продление подписки.</p>
509
- </div>
 
 
 
 
 
 
 
 
510
  </div>
511
  </div>
512
  )
 
3
  import { useState, useEffect } from 'react'
4
  import { useAuth } from '@/contexts/AuthContext'
5
  import { billingApi } from '@/lib/api'
6
+ import { Check, Loader2, Zap, TrendingUp, Crown, Sparkles, AlertCircle, CreditCard, ShieldCheck } from 'lucide-react'
7
+ import { motion, AnimatePresence } from 'framer-motion'
8
+ import { cn } from '@/lib/utils'
9
 
10
  export default function BillingPage() {
11
  const { user } = useAuth()
 
26
  billingApi.getTenantInfo(),
27
  billingApi.calculateOverage()
28
  ])
29
+
30
  setCurrentPlan(tenantData.subscription_plan || 'start')
31
  setSubscriptionStatus(tenantData.subscription_status || 'trial')
32
  setUsageData(overageData)
 
50
  setIsUpgrading(planId)
51
 
52
  try {
53
+ const endpoint = isTrialConversion
54
+ ? billingApi.convertTrial
55
  : billingApi.upgradeSubscription
56
+
57
  const data = await endpoint(planId)
58
 
59
  if (data.success) {
 
116
 
117
  if (isLoading) {
118
  return (
119
+ <div className="flex items-center justify-center min-h-screen bg-slate-50">
120
+ <Loader2 className="w-12 h-12 animate-spin text-indigo-600" />
121
  </div>
122
  )
123
  }
124
 
125
+ const container = {
126
+ hidden: { opacity: 0 },
127
+ show: {
128
+ opacity: 1,
129
+ transition: {
130
+ staggerChildren: 0.1
131
+ }
132
+ }
133
+ }
134
+
135
+ const item = {
136
+ hidden: { opacity: 0, y: 20 },
137
+ show: { opacity: 1, y: 0 }
138
+ }
139
+
140
  return (
141
+ <div className="min-h-screen bg-slate-50/50 p-8">
142
  <div className="max-w-7xl mx-auto">
143
  {/* Header */}
144
+ <motion.div
145
+ initial={{ opacity: 0, y: -20 }}
146
+ animate={{ opacity: 1, y: 0 }}
147
+ className="text-center mb-12"
148
+ >
149
+ <h1 className="text-4xl font-bold text-slate-900 mb-4 tracking-tight">
150
  Выберите свой план
151
  </h1>
152
+ <p className="text-lg text-slate-600 max-w-2xl mx-auto">
153
  Масштабируйте свой бизнес с AI-автоматизацией продаж. Все планы включают 14 дней бесплатно.
154
  </p>
155
  {subscriptionStatus === 'active' && (
156
+ <motion.div
157
+ initial={{ opacity: 0, scale: 0.9 }}
158
+ animate={{ opacity: 1, scale: 1 }}
159
+ className="mt-6 inline-flex items-center gap-2 px-4 py-2 bg-emerald-50 border border-emerald-200 rounded-full shadow-sm"
160
+ >
161
  <Check className="w-4 h-4 text-emerald-600" />
162
  <span className="text-sm text-emerald-700 font-semibold">
163
  Текущий план: {currentPlan.toUpperCase()}
164
  </span>
165
+ </motion.div>
166
  )}
167
+ </motion.div>
168
 
169
  {/* Pricing Cards */}
170
+ <motion.div
171
+ variants={container}
172
+ initial="hidden"
173
+ animate="show"
174
+ className="grid grid-cols-1 md:grid-cols-3 gap-8 mb-12"
175
+ >
176
  {/* START Plan */}
177
+ <motion.div variants={item} className="bg-white rounded-3xl shadow-sm border border-slate-200 overflow-hidden hover:shadow-xl transition-all duration-300 hover:-translate-y-1 relative group">
178
  <div className="p-8">
179
  <div className="inline-flex items-center gap-2 px-3 py-1 bg-slate-100 rounded-full mb-4">
180
  <Zap className="w-4 h-4 text-slate-600" />
181
  <span className="text-xs font-bold text-slate-700 uppercase tracking-wide">Starter</span>
182
  </div>
183
+
184
  <div className="mb-6">
185
  <div className="flex items-baseline gap-2">
186
  <span className="text-5xl font-bold text-slate-900">$99</span>
 
189
  <p className="text-sm text-slate-500 mt-2">Для малого бизнеса</p>
190
  </div>
191
 
192
+ <ul className="space-y-4 mb-8">
193
+ {[
194
+ 'До 1,000 лидов/месяц',
195
+ '1 канал (Telegram/WhatsApp/Instagram)',
196
+ 'Базовая AI-квалификация',
197
+ 'Email поддержка'
198
+ ].map((feature, i) => (
199
+ <li key={i} className="flex items-start gap-3">
200
+ <div className="p-0.5 bg-emerald-100 rounded-full mt-0.5">
201
+ <Check className="w-3 h-3 text-emerald-600" />
202
+ </div>
203
+ <span className="text-sm text-slate-700">{feature}</span>
204
+ </li>
205
+ ))}
 
 
 
206
  </ul>
207
 
208
  {currentPlan === 'start' ? (
 
216
  <button
217
  onClick={() => handleDowngrade('START', 'Starter')}
218
  disabled={isUpgrading !== null}
219
+ className="w-full py-3 px-6 border-2 border-slate-200 text-slate-700 rounded-xl font-semibold hover:bg-slate-50 hover:border-slate-300 transition-all disabled:opacity-50"
220
  >
221
  Понизить до Starter
222
  </button>
223
  )}
224
  </div>
225
+ </motion.div>
226
 
227
  {/* GROWTH Plan - Popular */}
228
+ <motion.div variants={item} className="bg-white rounded-3xl shadow-xl border-2 border-indigo-500 overflow-hidden relative transform hover:scale-105 transition-all duration-300 z-10">
229
  {/* Popular Badge */}
230
+ <div className="absolute top-0 right-0 bg-gradient-to-r from-indigo-600 to-purple-600 text-white px-6 py-1.5 rounded-bl-2xl shadow-md">
231
  <span className="text-xs font-bold uppercase tracking-wide">Популярный</span>
232
  </div>
233
 
 
236
  <TrendingUp className="w-4 h-4 text-indigo-600" />
237
  <span className="text-xs font-bold text-indigo-700 uppercase tracking-wide">Growth</span>
238
  </div>
239
+
240
  <div className="mb-6">
241
  <div className="flex items-baseline gap-2">
242
  <span className="text-5xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">$199</span>
 
245
  <p className="text-sm text-slate-500 mt-2">Для растущих команд</p>
246
  </div>
247
 
248
+ <ul className="space-y-4 mb-8">
249
+ {[
250
+ 'До 10,000 лидов/месяц',
251
+ 'Все каналы (Telegram + WhatsApp + Instagram)',
252
+ 'Продвинутая AI-квалификация',
253
+ 'Приоритетная поддержка',
254
+ 'Аналитика и отчеты'
255
+ ].map((feature, i) => (
256
+ <li key={i} className="flex items-start gap-3">
257
+ <div className="p-0.5 bg-indigo-100 rounded-full mt-0.5">
258
+ <Check className="w-3 h-3 text-indigo-600" />
259
+ </div>
260
+ <span className="text-sm text-slate-700 font-medium">{feature}</span>
261
+ </li>
262
+ ))}
 
 
 
 
 
 
263
  </ul>
264
 
265
  {currentPlan === 'growth' ? (
266
  <button
267
  disabled
268
+ className="w-full py-3 px-6 bg-gradient-to-r from-indigo-50 to-purple-50 text-indigo-700 rounded-xl font-semibold cursor-not-allowed"
269
  >
270
  Текущий план
271
  </button>
 
273
  <button
274
  onClick={() => handleUpgrade('GROWTH', 'Growth', 199)}
275
  disabled={isUpgrading !== null}
276
+ className="w-full py-3 px-6 bg-gradient-to-r from-indigo-600 to-purple-600 text-white rounded-xl font-semibold hover:from-indigo-500 hover:to-purple-500 shadow-lg hover:shadow-indigo-500/25 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
277
  >
278
  {isUpgrading === 'GROWTH' ? (
279
  <>
 
288
  </button>
289
  )}
290
  </div>
291
+ </motion.div>
292
 
293
  {/* SCALE Plan */}
294
+ <motion.div variants={item} className="bg-slate-900 rounded-3xl shadow-xl overflow-hidden relative hover:shadow-2xl transition-all duration-300 hover:-translate-y-1 group">
295
+ <div className="absolute inset-0 bg-gradient-to-br from-slate-800 to-slate-900" />
296
+ <div className="absolute inset-0 bg-[url('/grid.svg')] opacity-10" />
297
+
298
+ <div className="p-8 relative">
299
+ <div className="inline-flex items-center gap-2 px-3 py-1 bg-white/10 backdrop-blur rounded-full mb-4 border border-white/10">
300
+ <Crown className="w-4 h-4 text-amber-400" />
301
  <span className="text-xs font-bold text-white uppercase tracking-wide">Scale</span>
302
  </div>
303
+
304
  <div className="mb-6">
305
  <div className="flex items-baseline gap-2">
306
  <span className="text-5xl font-bold text-white">$499</span>
307
+ <span className="text-slate-400">/месяц</span>
308
  </div>
309
+ <p className="text-sm text-slate-400 mt-2">Для агентств</p>
310
  </div>
311
 
312
+ <ul className="space-y-4 mb-8">
313
+ {[
314
+ 'Безлимитные лиды',
315
+ 'Все каналы + API доступ',
316
+ 'Персонализированный AI',
317
+ 'Выделенный менеджер',
318
+ 'White-label опции',
319
+ 'SLA 99.9%'
320
+ ].map((feature, i) => (
321
+ <li key={i} className="flex items-start gap-3">
322
+ <div className="p-0.5 bg-amber-500/20 rounded-full mt-0.5">
323
+ <Check className="w-3 h-3 text-amber-400" />
324
+ </div>
325
+ <span className="text-sm text-slate-300 font-medium">{feature}</span>
326
+ </li>
327
+ ))}
 
 
 
 
 
 
 
 
 
328
  </ul>
329
 
330
  {currentPlan === 'scale' ? (
 
353
  </button>
354
  )}
355
  </div>
356
+ </motion.div>
357
+ </motion.div>
358
 
359
  {/* Feature Comparison */}
360
+ <motion.div
361
+ initial={{ opacity: 0, y: 20 }}
362
+ animate={{ opacity: 1, y: 0 }}
363
+ transition={{ delay: 0.4 }}
364
+ className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8 mb-12"
365
+ >
366
  <h2 className="text-2xl font-bold text-slate-900 mb-6 flex items-center gap-2">
367
  <Sparkles className="w-6 h-6 text-indigo-600" />
368
  Сравнение функций
369
  </h2>
370
+
371
  <div className="overflow-x-auto">
372
  <table className="w-full">
373
  <thead>
374
+ <tr className="border-b border-slate-100">
375
+ <th className="text-left py-4 px-4 text-sm font-semibold text-slate-900">Функция</th>
376
+ <th className="text-center py-4 px-4 text-sm font-semibold text-slate-700">Starter</th>
377
+ <th className="text-center py-4 px-4 text-sm font-semibold text-indigo-600">Growth</th>
378
+ <th className="text-center py-4 px-4 text-sm font-semibold text-slate-900">Scale</th>
379
  </tr>
380
  </thead>
381
+ <tbody className="divide-y divide-slate-50">
382
+ {[
383
+ { name: 'Лиды в месяц', start: '1,000', growth: '10,000', scale: 'Безлимит' },
384
+ { name: 'Каналы', start: '1', growth: 'Все', scale: 'Все + API' },
385
+ { name: 'AI-ассистент', start: true, growth: true, scale: true },
386
+ { name: 'Поддержка', start: 'Email', growth: 'Приоритет', scale: '24/7 менеджер' },
387
+ ].map((row, i) => (
388
+ <tr key={i} className="hover:bg-slate-50/50 transition-colors">
389
+ <td className="py-4 px-4 text-sm text-slate-700 font-medium">{row.name}</td>
390
+ <td className="py-4 px-4 text-sm text-center text-slate-600">
391
+ {row.start === true ? <Check className="w-5 h-5 text-emerald-500 mx-auto" /> : row.start}
392
+ </td>
393
+ <td className="py-4 px-4 text-sm text-center text-indigo-600 font-semibold bg-indigo-50/30">
394
+ {row.growth === true ? <Check className="w-5 h-5 text-indigo-600 mx-auto" /> : row.growth}
395
+ </td>
396
+ <td className="py-4 px-4 text-sm text-center text-slate-900 font-medium">
397
+ {row.scale === true ? <Check className="w-5 h-5 text-emerald-500 mx-auto" /> : row.scale}
398
+ </td>
399
+ </tr>
400
+ ))}
 
 
 
 
 
401
  </tbody>
402
  </table>
403
  </div>
404
+ </motion.div>
405
 
406
  {/* Usage & Overage Section */}
407
+ <AnimatePresence>
408
+ {usageData && subscriptionStatus === 'active' && (
409
+ <motion.div
410
+ initial={{ opacity: 0, height: 0 }}
411
+ animate={{ opacity: 1, height: 'auto' }}
412
+ exit={{ opacity: 0, height: 0 }}
413
+ className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8 mb-8 overflow-hidden"
414
+ >
415
+ <h2 className="text-2xl font-bold text-slate-900 mb-6 flex items-center gap-2">
416
+ <CreditCard className="w-6 h-6 text-indigo-600" />
417
+ Использование за месяц
418
+ </h2>
419
+
420
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
421
+ <div className="bg-gradient-to-br from-indigo-50 to-purple-50 rounded-xl p-6 border border-indigo-100">
422
+ <p className="text-sm text-slate-600 mb-2 font-medium">Лидов использовано</p>
423
+ <p className="text-3xl font-bold text-indigo-600">{usageData.leads_used.toLocaleString()}</p>
424
+ <p className="text-xs text-slate-500 mt-1">из {usageData.plan_limit.toLocaleString()} включено</p>
425
+ </div>
426
 
427
+ {usageData.overage_count > 0 && (
428
+ <>
429
+ <div className="bg-gradient-to-br from-amber-50 to-orange-50 rounded-xl p-6 border border-amber-200">
430
+ <p className="text-sm text-slate-600 mb-2 font-medium">Превышение лимита</p>
431
+ <p className="text-3xl font-bold text-amber-600">{usageData.overage_count.toLocaleString()}</p>
432
+ <p className="text-xs text-slate-500 mt-1">дополнительных лидов</p>
433
+ </div>
434
+
435
+ <div className="bg-gradient-to-br from-rose-50 to-pink-50 rounded-xl p-6 border border-rose-200">
436
+ <p className="text-sm text-slate-600 mb-2 font-medium">Доплата за превышение</p>
437
+ <p className="text-3xl font-bold text-rose-600">${usageData.overage_cost}</p>
438
+ <p className="text-xs text-slate-500 mt-1">будет списано при продлении</p>
439
+ </div>
440
+ </>
441
+ )}
442
+
443
+ {usageData.overage_count === 0 && (
444
+ <div className="bg-gradient-to-br from-emerald-50 to-teal-50 rounded-xl p-6 border border-emerald-200">
445
+ <p className="text-sm text-slate-600 mb-2 font-medium">Статус</p>
446
+ <p className="text-3xl font-bold text-emerald-600">✅ ОК</p>
447
+ <p className="text-xs text-slate-500 mt-1">В пределах лимита</p>
448
  </div>
449
+ )}
450
+ </div>
451
 
452
+ {usageData.overage_count > 0 && (
453
+ <div className="mt-6 p-4 bg-amber-50 border border-amber-200 rounded-xl flex items-start gap-3">
454
+ <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
455
+ <p className="text-sm text-amber-800">
456
+ <strong>Внимание:</strong> Вы превысили лимит плана. Дополнительные лиды будут включены в следующий платёж. Рассмотрите апгрейд до GROWTH или SCALE для большего лимита.
457
+ </p>
458
  </div>
459
  )}
460
+ </motion.div>
461
+ )}
462
+ </AnimatePresence>
 
 
 
 
 
 
 
 
463
 
464
  {/* Cancel Subscription Button */}
465
  {subscriptionStatus === 'active' && (
466
+ <motion.div
467
+ initial={{ opacity: 0 }}
468
+ animate={{ opacity: 1 }}
469
+ transition={{ delay: 0.5 }}
470
+ className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8 mb-8"
471
+ >
472
+ <div className="flex items-center justify-between flex-wrap gap-4">
473
+ <div>
474
+ <h2 className="text-xl font-bold text-slate-900 mb-1">Управление подпиской</h2>
475
+ <p className="text-slate-600 text-sm">
476
+ Если вы хотите отменить подписку, доступ сохранится до конца оплаченного периода.
477
+ </p>
478
+ </div>
479
+ <button
480
+ onClick={() => setShowCancelModal(true)}
481
+ className="px-6 py-3 bg-red-50 text-red-600 border border-red-200 rounded-xl font-semibold hover:bg-red-100 transition-colors text-sm"
482
+ >
483
+ Отменить подписку
484
+ </button>
485
+ </div>
486
+ </motion.div>
487
  )}
488
 
489
  {/* Cancel Modal */}
490
+ <AnimatePresence>
491
+ {showCancelModal && (
492
+ <motion.div
493
+ initial={{ opacity: 0 }}
494
+ animate={{ opacity: 1 }}
495
+ exit={{ opacity: 0 }}
496
+ className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
497
+ >
498
+ <motion.div
499
+ initial={{ scale: 0.95, opacity: 0 }}
500
+ animate={{ scale: 1, opacity: 1 }}
501
+ exit={{ scale: 0.95, opacity: 0 }}
502
+ className="bg-white rounded-2xl p-8 max-w-md w-full shadow-2xl"
503
  >
504
+ <h3 className="text-2xl font-bold text-slate-900 mb-4">Отмена подписки</h3>
505
+ <p className="text-slate-600 mb-6">
506
+ Мы хотим стать лучше. Пожалуйста, укажите причину отмены:
507
+ </p>
508
+
509
+ <select
510
+ id="cancel-reason"
511
+ className="w-full mb-4 px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-slate-50"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
512
  >
513
+ <option value="">Выберите причину...</option>
514
+ <option value="too_expensive">Слишком дорого</option>
515
+ <option value="not_using">Не использую</option>
516
+ <option value="missing_features">Нехватает функций</option>
517
+ <option value="technical_issues">Технические проблемы</option>
518
+ <option value="found_alternative">Нашёл альтернативу</option>
519
+ <option value="other">Другое</option>
520
+ </select>
521
+
522
+ <textarea
523
+ id="cancel-feedback"
524
+ placeholder="Дополнительные комментарии (опционально)"
525
+ className="w-full mb-6 px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 resize-none bg-slate-50"
526
+ rows={3}
527
+ />
528
+
529
+ <div className="flex gap-3">
530
+ <button
531
+ onClick={() => setShowCancelModal(false)}
532
+ className="flex-1 px-6 py-3 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200 transition-colors"
533
+ >
534
+ Отмена
535
+ </button>
536
+ <button
537
+ onClick={() => {
538
+ const reason = (document.getElementById('cancel-reason') as HTMLSelectElement)?.value || 'not_specified'
539
+ const feedback = (document.getElementById('cancel-feedback') as HTMLTextAreaElement)?.value || ''
540
+ handleCancel(reason, feedback)
541
+ }}
542
+ className="flex-1 px-6 py-3 bg-red-600 text-white rounded-xl font-semibold hover:bg-red-700 transition-colors shadow-lg shadow-red-200"
543
+ >
544
+ Подтвердить
545
+ </button>
546
+ </div>
547
+ </motion.div>
548
+ </motion.div>
549
+ )}
550
+ </AnimatePresence>
551
 
552
  {/* Trust Section */}
553
+ <motion.div
554
+ initial={{ opacity: 0 }}
555
+ animate={{ opacity: 1 }}
556
+ transition={{ delay: 0.6 }}
557
+ className="text-center mt-12 text-sm text-slate-500"
558
+ >
559
+ <div className="flex items-center justify-center gap-2 mb-2 text-slate-600 font-medium">
560
+ <ShieldCheck className="w-4 h-4" />
561
+ <span>Безопасная оплата • Отмена в любое время • Гарантия возврата 30 дней</span>
562
+ </div>
563
+ <p className="text-xs">Все цены указаны в USD. Автоматическое продление подписки.</p>
564
+ </motion.div>
565
  </div>
566
  </div>
567
  )
frontend/app/settings/brain/page.tsx CHANGED
@@ -2,7 +2,9 @@
2
 
3
  import { useState, useEffect } from 'react'
4
  import { useAuth } from '@/contexts/AuthContext'
5
- import { Brain, Plus, X, Save, Loader2, Sparkles, Target, TrendingUp, Zap, Shield, Users, BookOpen, Award, Ban, Calculator, DollarSign } from 'lucide-react'
 
 
6
 
7
  interface AISettings {
8
  business_description: string
@@ -16,7 +18,7 @@ interface AIPersona {
16
  sales_methodology: 'SPIN' | 'Sandler' | 'Challenger' | 'Consultative' | 'MEDDIC'
17
  custom_instructions: string
18
  banned_words: string[]
19
- manager_monthly_salary: number // NEW: For ROI calculation
20
  }
21
 
22
  const TONE_OPTIONS = [
@@ -65,7 +67,7 @@ export default function BrainSettingsPage() {
65
  const [saving, setSaving] = useState(false)
66
  const [newField, setNewField] = useState('')
67
  const [newBannedWord, setNewBannedWord] = useState('')
68
-
69
  const [settings, setSettings] = useState<AISettings>({
70
  business_description: '',
71
  selling_style: 'Consultative',
@@ -78,7 +80,7 @@ export default function BrainSettingsPage() {
78
  sales_methodology: 'Consultative',
79
  custom_instructions: '',
80
  banned_words: [],
81
- manager_monthly_salary: 1000 // Default $1000/month
82
  })
83
 
84
  useEffect(() => {
@@ -89,50 +91,35 @@ export default function BrainSettingsPage() {
89
 
90
  const fetchSettings = async () => {
91
  if (!user?.tenant_id) {
92
- console.log('No user or tenant_id, skipping fetch')
93
  setLoading(false)
94
  return
95
  }
96
 
97
  const apiUrl = process.env.NEXT_PUBLIC_API_URL
98
- console.log('🔍 NEXT_PUBLIC_API_URL:', apiUrl)
99
- console.log('🔍 window.location.protocol:', window.location.protocol)
100
-
101
  if (!apiUrl) {
102
- console.error('❌ NEXT_PUBLIC_API_URL is not defined. Please add it to .env.local and restart Next.js dev server.')
103
  setLoading(false)
104
  return
105
  }
106
-
107
  try {
108
  const token = localStorage.getItem('auth_token')
109
  if (!token) {
110
- console.error('❌ No auth token found in localStorage')
111
  setLoading(false)
112
  return
113
  }
114
 
115
  const fetchUrl = `${apiUrl}/api/v1/tenants/${user.tenant_id}`
116
- console.log('✅ Fetching tenant settings from:', fetchUrl)
117
- console.log('✅ Using token:', token.substring(0, 20) + '...')
118
- console.log('🔍 About to call fetch()...')
119
-
120
  const response = await fetch(fetchUrl, {
121
  headers: {
122
  'Authorization': `Bearer ${token}`
123
  }
124
  })
125
-
126
- console.log('✅ fetch() completed successfully')
127
- console.log('✅ Response status:', response.status)
128
-
129
  if (response.ok) {
130
  const data = await response.json()
131
- console.log('✅ Settings loaded successfully:', data)
132
  if (data.ai_settings) {
133
  setSettings(data.ai_settings)
134
  }
135
- // Load persona settings
136
  setPersona({
137
  tone_of_voice: data.tone_of_voice || 'Professional',
138
  sales_methodology: data.sales_methodology || 'Consultative',
@@ -140,22 +127,9 @@ export default function BrainSettingsPage() {
140
  banned_words: data.banned_words || [],
141
  manager_monthly_salary: data.manager_monthly_salary || 1000
142
  })
143
- } else {
144
- const errorText = await response.text()
145
- console.error('❌ Failed to fetch settings. Status:', response.status, 'Error:', errorText)
146
  }
147
  } catch (error) {
148
- console.error('❌ Failed to fetch AI settings (network error or CORS):', error)
149
- console.error('Error details:', {
150
- name: error instanceof Error ? error.name : 'Unknown',
151
- message: error instanceof Error ? error.message : String(error),
152
- stack: error instanceof Error ? error.stack : undefined
153
- })
154
- console.error('This might be because:')
155
- console.error('1. Backend is not running (check http://localhost:8000/health)')
156
- console.error('2. CORS policy blocking the request')
157
- console.error('3. Network connection issue')
158
- console.error('4. Mixed content (HTTPS frontend trying to access HTTP backend)')
159
  } finally {
160
  setLoading(false)
161
  }
@@ -169,7 +143,7 @@ export default function BrainSettingsPage() {
169
  alert('❌ API URL не настроен')
170
  return
171
  }
172
-
173
  setSaving(true)
174
  try {
175
  const token = localStorage.getItem('auth_token')
@@ -179,7 +153,6 @@ export default function BrainSettingsPage() {
179
  return
180
  }
181
 
182
- console.log('Saving AI settings...')
183
  const response = await fetch(`${apiUrl}/api/v1/tenants/${user.tenant_id}`, {
184
  method: 'PATCH',
185
  headers: {
@@ -191,13 +164,10 @@ export default function BrainSettingsPage() {
191
  ...persona
192
  })
193
  })
194
-
195
  if (response.ok) {
196
- console.log('Settings saved successfully')
197
  alert('✅ Настройки AI Brain сохранены!')
198
  } else {
199
- const errorText = await response.text()
200
- console.error('Failed to save settings:', response.status, errorText)
201
  alert(`❌ Ошибка сохранения настроек: ${response.status}`)
202
  }
203
  } catch (error) {
@@ -214,7 +184,7 @@ export default function BrainSettingsPage() {
214
  alert('Это поле уже добавлено')
215
  return
216
  }
217
-
218
  setSettings({
219
  ...settings,
220
  custom_fields: [...settings.custom_fields, newField.trim()]
@@ -235,7 +205,7 @@ export default function BrainSettingsPage() {
235
  alert('Это слово уже в списке')
236
  return
237
  }
238
-
239
  setPersona({
240
  ...persona,
241
  banned_words: [...persona.banned_words, newBannedWord.trim()]
@@ -252,298 +222,375 @@ export default function BrainSettingsPage() {
252
 
253
  if (loading) {
254
  return (
255
- <div className="flex items-center justify-center h-full">
256
- <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
257
  </div>
258
  )
259
  }
260
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  return (
262
- <div className="max-w-5xl mx-auto p-8">
263
- {/* Header */}
264
- <div className="mb-8">
265
- <div className="flex items-center gap-3 mb-2">
266
- <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center">
267
- <Brain className="w-6 h-6 text-white" />
 
 
 
 
268
  </div>
269
  <div>
270
- <h1 className="text-3xl font-bold text-slate-900">AI Brain - Advanced Settings</h1>
271
- <p className="text-slate-600">Когнитивная архитектура и персонализация AI менеджера</p>
 
 
 
 
272
  </div>
273
- </div>
274
- </div>
275
 
276
- <div className="space-y-6">
277
- {/* Tone of Voice */}
278
- <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm">
279
- <div className="flex items-center gap-2 mb-4">
280
- <Sparkles className="w-5 h-5 text-indigo-600" />
281
- <h2 className="text-lg font-bold text-slate-900">Тон голоса</h2>
282
- </div>
283
- <p className="text-sm text-slate-600 mb-4">
284
- Выберите стиль общения AI с клиентами
285
- </p>
286
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
287
- {TONE_OPTIONS.map((tone) => {
288
- const Icon = tone.icon
289
- return (
290
- <button
291
- key={tone.value}
292
- onClick={() => setPersona({ ...persona, tone_of_voice: tone.value as any })}
293
- className={`p-4 rounded-lg border-2 transition-all duration-200 text-left ${
294
- persona.tone_of_voice === tone.value
295
- ? 'border-indigo-600 bg-indigo-50'
296
- : 'border-gray-200 hover:border-indigo-300 bg-white'
297
- }`}
298
- >
299
- <div className="flex items-center gap-2 mb-1">
300
- <Icon className={`w-4 h-4 ${persona.tone_of_voice === tone.value ? 'text-indigo-600' : 'text-slate-600'}`} />
301
- <h3 className={`font-bold ${persona.tone_of_voice === tone.value ? 'text-indigo-900' : 'text-slate-900'}`}>
302
- {tone.label}
303
- </h3>
304
- </div>
305
- <p className="text-xs text-slate-600">{tone.description}</p>
306
- </button>
307
- )
308
- })}
309
- </div>
310
- </div>
311
 
312
- {/* Sales Methodology */}
313
- <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm">
314
- <div className="flex items-center gap-2 mb-4">
315
- <BookOpen className="w-5 h-5 text-purple-600" />
316
- <h2 className="text-lg font-bold text-slate-900">Методология продаж</h2>
317
- </div>
318
- <p className="text-sm text-slate-600 mb-4">
319
- Выберите фреймворк, который AI будет использовать в диалогах
320
- </p>
321
- <div className="space-y-3">
322
- {METHODOLOGY_OPTIONS.map((method) => {
323
- const Icon = method.icon
324
- return (
325
- <button
326
- key={method.value}
327
- onClick={() => setPersona({ ...persona, sales_methodology: method.value as any })}
328
- className={`w-full p-4 rounded-lg border-2 transition-all duration-200 text-left ${
329
- persona.sales_methodology === method.value
330
- ? 'border-purple-600 bg-purple-50'
331
- : 'border-gray-200 hover:border-purple-300 bg-white'
332
- }`}
333
- >
334
- <div className="flex items-start gap-3">
335
- <Icon className={`w-5 h-5 flex-shrink-0 mt-0.5 ${persona.sales_methodology === method.value ? 'text-purple-600' : 'text-slate-600'}`} />
336
- <div className="flex-1">
337
- <h3 className={`font-bold mb-1 ${persona.sales_methodology === method.value ? 'text-purple-900' : 'text-slate-900'}`}>
338
- {method.label}
339
  </h3>
340
- <p className="text-xs text-slate-600">{method.description}</p>
 
 
341
  </div>
342
- </div>
343
- </button>
344
- )
345
- })}
346
- </div>
347
- </div>
348
 
349
- {/* Business Description */}
350
- <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm">
351
- <div className="flex items-center gap-2 mb-4">
352
- <Target className="w-5 h-5 text-indigo-600" />
353
- <h2 className="text-lg font-bold text-slate-900">Описание бизнеса</h2>
354
- </div>
355
- <p className="text-sm text-slate-600 mb-3">
356
- Опишите ваш бизнес, что вы продаете, ключевые преимущества
357
- </p>
358
- <textarea
359
- value={settings.business_description}
360
- onChange={(e) => setSettings({ ...settings, business_description: e.target.value })}
361
- placeholder="Например: Мы продаём премиум CRM-системы для малого бизнеса. Наше главное преимущество — простота настройки и внедрения за 1 день."
362
- className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent resize-none text-sm"
363
- rows={4}
364
- />
365
- </div>
366
-
367
- {/* Ideal Customer Profile */}
368
- <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm">
369
- <div className="flex items-center gap-2 mb-4">
370
- <Users className="w-5 h-5 text-purple-600" />
371
- <h2 className="text-lg font-bold text-slate-900">Идеальный клиент (ICP)</h2>
372
- </div>
373
- <p className="text-sm text-slate-600 mb-3">
374
- Портрет вашего идеального клиента для квалификации
375
- </p>
376
- <textarea
377
- value={settings.ideal_customer_profile}
378
- onChange={(e) => setSettings({ ...settings, ideal_customer_profile: e.target.value })}
379
- placeholder="Например: Владелец бизнеса с 5-50 сотрудниками, доход от 10 млн руб/год, ищет решение для автоматизации продаж."
380
- className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent resize-none text-sm"
381
- rows={3}
382
- />
383
- </div>
384
-
385
- {/* Custom Qualification Fields */}
386
- <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm">
387
- <div className="flex items-center gap-2 mb-4">
388
- <Brain className="w-5 h-5 text-indigo-600" />
389
- <h2 className="text-lg font-bold text-slate-900">Поля квалификации</h2>
390
- </div>
391
- <p className="text-sm text-slate-600 mb-4">
392
- Какую информацию AI должен собирать о клиентах
393
- </p>
394
-
395
- <div className="flex flex-wrap gap-2 mb-4">
396
- {settings.custom_fields.map((field) => (
397
- <div
398
- key={field}
399
- className="inline-flex items-center gap-2 px-3 py-1.5 bg-indigo-100 text-indigo-900 rounded-full text-sm font-medium"
400
- >
401
- <span>{field}</span>
402
- <button
403
- onClick={() => removeCustomField(field)}
404
- className="hover:bg-indigo-200 rounded-full p-0.5 transition-colors"
405
- >
406
- <X className="w-3.5 h-3.5" />
407
- </button>
408
  </div>
409
- ))}
410
- </div>
 
 
 
411
 
412
- <div className="flex gap-2">
413
- <input
414
- type="text"
415
- value={newField}
416
- onChange={(e) => setNewField(e.target.value)}
417
- onKeyDown={(e) => e.key === 'Enter' && addCustomField()}
418
- placeholder="Например: Регион, Количество сотрудников..."
419
- className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent text-sm"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  />
421
- <button
422
- onClick={addCustomField}
423
- className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium flex items-center gap-2 transition-colors"
424
- >
425
- <Plus className="w-4 h-4" />
426
- Добавить
427
- </button>
428
- </div>
429
- </div>
430
 
431
- {/* Custom Instructions */}
432
- <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm">
433
- <div className="flex items-center gap-2 mb-4">
434
- <Award className="w-5 h-5 text-emerald-600" />
435
- <h2 className="text-lg font-bold text-slate-900">Правила поведения (Global Prompt)</h2>
436
- </div>
437
- <p className="text-sm text-slate-600 mb-3">
438
- Специальные инструкции для AI. Например: "Никогда не называй цену первым", "Всегда спрашивай про конкурентов"
439
- </p>
440
- <textarea
441
- value={persona.custom_instructions}
442
- onChange={(e) => setPersona({ ...persona, custom_instructions: e.target.value })}
443
- placeholder="Например:&#10;- Никогда не говори цену до выяснения бюджета&#10;- Всегда упоминай наше УТП: внедрение за 1 день&#10;- Если клиент сравнивает с конкурентами, подчеркни скорость"
444
- className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent resize-none text-sm font-mono"
445
- rows={5}
446
- />
447
- </div>
448
-
449
- {/* Banned Words */}
450
- <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm">
451
- <div className="flex items-center gap-2 mb-4">
452
- <Ban className="w-5 h-5 text-red-600" />
453
- <h2 className="text-lg font-bold text-slate-900">Запрещенные слова</h2>
454
- </div>
455
- <p className="text-sm text-slate-600 mb-4">
456
- Слова и фразы, которые AI никогда не должен использовать
457
- </p>
458
-
459
- <div className="flex flex-wrap gap-2 mb-4">
460
- {persona.banned_words.map((word) => (
461
- <div
462
- key={word}
463
- className="inline-flex items-center gap-2 px-3 py-1.5 bg-red-100 text-red-900 rounded-full text-sm font-medium"
464
- >
465
- <span>{word}</span>
466
- <button
467
- onClick={() => removeBannedWord(word)}
468
- className="hover:bg-red-200 rounded-full p-0.5 transition-colors"
469
  >
470
- <X className="w-3.5 h-3.5" />
471
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472
  </div>
473
- ))}
474
- </div>
 
 
 
475
 
476
- <div className="flex gap-2">
477
- <input
478
- type="text"
479
- value={newBannedWord}
480
- onChange={(e) => setNewBannedWord(e.target.value)}
481
- onKeyDown={(e) => e.key === 'Enter' && addBannedWord()}
482
- placeholder="Например: дешево, бесплатно, скидка..."
483
- className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-transparent text-sm"
484
  />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
485
  <button
486
- onClick={addBannedWord}
487
- className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg font-medium flex items-center gap-2 transition-colors"
 
488
  >
489
- <Plus className="w-4 h-4" />
490
- Добавить
 
 
 
 
 
 
 
 
 
491
  </button>
492
- </div>
493
- </div>
494
-
495
- {/* ROI Calculator Settings */}
496
- <div className="bg-gradient-to-br from-green-50 to-emerald-50 rounded-xl border border-green-200 p-6 shadow-sm">
497
- <div className="flex items-center gap-2 mb-4">
498
- <Calculator className="w-5 h-5 text-green-600" />
499
- <h2 className="text-lg font-bold text-slate-900">Настройки ROI (Калькулятор выгоды)</h2>
500
- </div>
501
- <p className="text-sm text-slate-600 mb-4">
502
- Настройте расчёт экономии от AI. Мы используем это, чтобы показать, сколько денег экономит вам AI.
503
- </p>
504
-
505
- <div>
506
- <label className="block text-sm font-medium text-slate-700 mb-2">
507
- <div className="flex items-center gap-2">
508
- <DollarSign className="w-4 h-4 text-green-600" />
509
- Средняя зарплата менеджера (USD/месяц)
510
- </div>
511
- </label>
512
- <input
513
- type="number"
514
- min="0"
515
- step="100"
516
- value={persona.manager_monthly_salary}
517
- onChange={(e) => setPersona({ ...persona, manager_monthly_salary: parseInt(e.target.value) || 1000 })}
518
- className="w-full md:w-64 px-4 py-2 border border-green-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent text-sm"
519
- placeholder="1000"
520
- />
521
- <p className="mt-2 text-xs text-slate-500">
522
- 💡 Мы рассчитываем почасовую ставку (зарплата / 160 часов) и экономию времени AI (3 мин на сообщение).
523
- </p>
524
- </div>
525
- </div>
526
-
527
- {/* Save Button */}
528
- <div className="flex justify-end pt-4">
529
- <button
530
- onClick={handleSave}
531
- disabled={saving}
532
- className="px-6 py-3 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white rounded-xl font-bold shadow-lg hover:shadow-xl transition-all duration-200 flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
533
- >
534
- {saving ? (
535
- <>
536
- <Loader2 className="w-5 h-5 animate-spin" />
537
- Сохранение...
538
- </>
539
- ) : (
540
- <>
541
- <Save className="w-5 h-5" />
542
- Сохранить настройки
543
- </>
544
- )}
545
- </button>
546
- </div>
547
  </div>
548
  </div>
549
  )
 
2
 
3
  import { useState, useEffect } from 'react'
4
  import { useAuth } from '@/contexts/AuthContext'
5
+ import { Brain, Plus, X, Save, Loader2, Sparkles, Target, TrendingUp, Zap, Shield, Users, BookOpen, Award, Ban, Calculator, DollarSign, CheckCircle2, AlertCircle } from 'lucide-react'
6
+ import { motion, AnimatePresence } from 'framer-motion'
7
+ import { cn } from '@/lib/utils'
8
 
9
  interface AISettings {
10
  business_description: string
 
18
  sales_methodology: 'SPIN' | 'Sandler' | 'Challenger' | 'Consultative' | 'MEDDIC'
19
  custom_instructions: string
20
  banned_words: string[]
21
+ manager_monthly_salary: number
22
  }
23
 
24
  const TONE_OPTIONS = [
 
67
  const [saving, setSaving] = useState(false)
68
  const [newField, setNewField] = useState('')
69
  const [newBannedWord, setNewBannedWord] = useState('')
70
+
71
  const [settings, setSettings] = useState<AISettings>({
72
  business_description: '',
73
  selling_style: 'Consultative',
 
80
  sales_methodology: 'Consultative',
81
  custom_instructions: '',
82
  banned_words: [],
83
+ manager_monthly_salary: 1000
84
  })
85
 
86
  useEffect(() => {
 
91
 
92
  const fetchSettings = async () => {
93
  if (!user?.tenant_id) {
 
94
  setLoading(false)
95
  return
96
  }
97
 
98
  const apiUrl = process.env.NEXT_PUBLIC_API_URL
 
 
 
99
  if (!apiUrl) {
 
100
  setLoading(false)
101
  return
102
  }
103
+
104
  try {
105
  const token = localStorage.getItem('auth_token')
106
  if (!token) {
 
107
  setLoading(false)
108
  return
109
  }
110
 
111
  const fetchUrl = `${apiUrl}/api/v1/tenants/${user.tenant_id}`
 
 
 
 
112
  const response = await fetch(fetchUrl, {
113
  headers: {
114
  'Authorization': `Bearer ${token}`
115
  }
116
  })
117
+
 
 
 
118
  if (response.ok) {
119
  const data = await response.json()
 
120
  if (data.ai_settings) {
121
  setSettings(data.ai_settings)
122
  }
 
123
  setPersona({
124
  tone_of_voice: data.tone_of_voice || 'Professional',
125
  sales_methodology: data.sales_methodology || 'Consultative',
 
127
  banned_words: data.banned_words || [],
128
  manager_monthly_salary: data.manager_monthly_salary || 1000
129
  })
 
 
 
130
  }
131
  } catch (error) {
132
+ console.error('Failed to fetch AI settings:', error)
 
 
 
 
 
 
 
 
 
 
133
  } finally {
134
  setLoading(false)
135
  }
 
143
  alert('❌ API URL не настроен')
144
  return
145
  }
146
+
147
  setSaving(true)
148
  try {
149
  const token = localStorage.getItem('auth_token')
 
153
  return
154
  }
155
 
 
156
  const response = await fetch(`${apiUrl}/api/v1/tenants/${user.tenant_id}`, {
157
  method: 'PATCH',
158
  headers: {
 
164
  ...persona
165
  })
166
  })
167
+
168
  if (response.ok) {
 
169
  alert('✅ Настройки AI Brain сохранены!')
170
  } else {
 
 
171
  alert(`❌ Ошибка сохранения настроек: ${response.status}`)
172
  }
173
  } catch (error) {
 
184
  alert('Это поле уже добавлено')
185
  return
186
  }
187
+
188
  setSettings({
189
  ...settings,
190
  custom_fields: [...settings.custom_fields, newField.trim()]
 
205
  alert('Это слово уже в списке')
206
  return
207
  }
208
+
209
  setPersona({
210
  ...persona,
211
  banned_words: [...persona.banned_words, newBannedWord.trim()]
 
222
 
223
  if (loading) {
224
  return (
225
+ <div className="flex items-center justify-center min-h-screen bg-slate-50">
226
+ <Loader2 className="w-12 h-12 animate-spin text-indigo-600" />
227
  </div>
228
  )
229
  }
230
 
231
+ const container = {
232
+ hidden: { opacity: 0 },
233
+ show: {
234
+ opacity: 1,
235
+ transition: {
236
+ staggerChildren: 0.1
237
+ }
238
+ }
239
+ }
240
+
241
+ const item = {
242
+ hidden: { opacity: 0, y: 20 },
243
+ show: { opacity: 1, y: 0 }
244
+ }
245
+
246
  return (
247
+ <div className="min-h-screen bg-slate-50/50 p-8">
248
+ <div className="max-w-5xl mx-auto">
249
+ {/* Header */}
250
+ <motion.div
251
+ initial={{ opacity: 0, y: -20 }}
252
+ animate={{ opacity: 1, y: 0 }}
253
+ className="flex items-center gap-4 mb-8"
254
+ >
255
+ <div className="p-3 bg-gradient-to-br from-indigo-600 to-purple-600 rounded-2xl shadow-lg shadow-indigo-200">
256
+ <Brain className="w-8 h-8 text-white" />
257
  </div>
258
  <div>
259
+ <h1 className="text-3xl font-bold text-slate-900 mb-1 tracking-tight">
260
+ Настройки AI Мозга
261
+ </h1>
262
+ <p className="text-slate-600">
263
+ Когнитивная архитектура и персонализация вашего цифрового сотрудника
264
+ </p>
265
  </div>
266
+ </motion.div>
 
267
 
268
+ <motion.div
269
+ variants={container}
270
+ initial="hidden"
271
+ animate="show"
272
+ className="space-y-6"
273
+ >
274
+ {/* Tone of Voice */}
275
+ <motion.div variants={item} className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8">
276
+ <div className="flex items-center gap-3 mb-6">
277
+ <div className="p-2 bg-indigo-50 rounded-xl text-indigo-600">
278
+ <Sparkles className="w-6 h-6" />
279
+ </div>
280
+ <div>
281
+ <h2 className="text-xl font-bold text-slate-900">Тон голоса</h2>
282
+ <p className="text-sm text-slate-500">Выберите стиль общения AI с клиентами</p>
283
+ </div>
284
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
 
286
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
287
+ {TONE_OPTIONS.map((tone) => {
288
+ const Icon = tone.icon
289
+ const isSelected = persona.tone_of_voice === tone.value
290
+ return (
291
+ <button
292
+ key={tone.value}
293
+ onClick={() => setPersona({ ...persona, tone_of_voice: tone.value as any })}
294
+ className={cn(
295
+ "p-4 rounded-xl border-2 transition-all duration-200 text-left relative overflow-hidden group",
296
+ isSelected
297
+ ? "border-indigo-600 bg-indigo-50/50 shadow-md"
298
+ : "border-slate-200 hover:border-indigo-300 bg-white hover:shadow-sm"
299
+ )}
300
+ >
301
+ <div className="flex items-center gap-3 mb-2 relative z-10">
302
+ <div className={cn(
303
+ "p-2 rounded-lg transition-colors",
304
+ isSelected ? "bg-indigo-100 text-indigo-600" : "bg-slate-100 text-slate-500 group-hover:bg-indigo-50 group-hover:text-indigo-600"
305
+ )}>
306
+ <Icon className="w-5 h-5" />
307
+ </div>
308
+ <h3 className={cn(
309
+ "font-bold text-lg",
310
+ isSelected ? "text-indigo-900" : "text-slate-900"
311
+ )}>
312
+ {tone.label}
313
  </h3>
314
+ {isSelected && (
315
+ <CheckCircle2 className="w-5 h-5 text-indigo-600 ml-auto" />
316
+ )}
317
  </div>
318
+ <p className="text-sm text-slate-600 pl-[52px] relative z-10">{tone.description}</p>
319
+ </button>
320
+ )
321
+ })}
322
+ </div>
323
+ </motion.div>
324
 
325
+ {/* Sales Methodology */}
326
+ <motion.div variants={item} className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8">
327
+ <div className="flex items-center gap-3 mb-6">
328
+ <div className="p-2 bg-purple-50 rounded-xl text-purple-600">
329
+ <BookOpen className="w-6 h-6" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
  </div>
331
+ <div>
332
+ <h2 className="text-xl font-bold text-slate-900">Методология продаж</h2>
333
+ <p className="text-sm text-slate-500">Выберите фреймворк, который AI будет использовать в диалогах</p>
334
+ </div>
335
+ </div>
336
 
337
+ <div className="space-y-3">
338
+ {METHODOLOGY_OPTIONS.map((method) => {
339
+ const Icon = method.icon
340
+ const isSelected = persona.sales_methodology === method.value
341
+ return (
342
+ <button
343
+ key={method.value}
344
+ onClick={() => setPersona({ ...persona, sales_methodology: method.value as any })}
345
+ className={cn(
346
+ "w-full p-4 rounded-xl border-2 transition-all duration-200 text-left group",
347
+ isSelected
348
+ ? "border-purple-600 bg-purple-50/30 shadow-md"
349
+ : "border-slate-200 hover:border-purple-300 bg-white hover:shadow-sm"
350
+ )}
351
+ >
352
+ <div className="flex items-start gap-4">
353
+ <div className={cn(
354
+ "p-2 rounded-lg mt-0.5 transition-colors",
355
+ isSelected ? "bg-purple-100 text-purple-600" : "bg-slate-100 text-slate-500 group-hover:bg-purple-50 group-hover:text-purple-600"
356
+ )}>
357
+ <Icon className="w-5 h-5" />
358
+ </div>
359
+ <div className="flex-1">
360
+ <div className="flex items-center justify-between mb-1">
361
+ <h3 className={cn(
362
+ "font-bold text-lg",
363
+ isSelected ? "text-purple-900" : "text-slate-900"
364
+ )}>
365
+ {method.label}
366
+ </h3>
367
+ {isSelected && (
368
+ <CheckCircle2 className="w-5 h-5 text-purple-600" />
369
+ )}
370
+ </div>
371
+ <p className="text-sm text-slate-600">{method.description}</p>
372
+ </div>
373
+ </div>
374
+ </button>
375
+ )
376
+ })}
377
+ </div>
378
+ </motion.div>
379
+
380
+ {/* Business Description */}
381
+ <motion.div variants={item} className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8">
382
+ <div className="flex items-center gap-3 mb-6">
383
+ <div className="p-2 bg-indigo-50 rounded-xl text-indigo-600">
384
+ <Target className="w-6 h-6" />
385
+ </div>
386
+ <div>
387
+ <h2 className="text-xl font-bold text-slate-900">Описание бизнеса</h2>
388
+ <p className="text-sm text-slate-500">Опишите ваш бизнес, что вы продаете, ключевые преимущества</p>
389
+ </div>
390
+ </div>
391
+
392
+ <textarea
393
+ value={settings.business_description}
394
+ onChange={(e) => setSettings({ ...settings, business_description: e.target.value })}
395
+ placeholder="Например: Мы продаём премиум CRM-системы для малого бизнеса. Наше главное преимущество — простота настройки и внедрения за 1 день."
396
+ className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition-all outline-none resize-none min-h-[120px]"
397
  />
398
+ </motion.div>
 
 
 
 
 
 
 
 
399
 
400
+ {/* Ideal Customer Profile */}
401
+ <motion.div variants={item} className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8">
402
+ <div className="flex items-center gap-3 mb-6">
403
+ <div className="p-2 bg-purple-50 rounded-xl text-purple-600">
404
+ <Users className="w-6 h-6" />
405
+ </div>
406
+ <div>
407
+ <h2 className="text-xl font-bold text-slate-900">Идеальный клиент (ICP)</h2>
408
+ <p className="text-sm text-slate-500">Портрет вашего идеального клиента для квалификации</p>
409
+ </div>
410
+ </div>
411
+
412
+ <textarea
413
+ value={settings.ideal_customer_profile}
414
+ onChange={(e) => setSettings({ ...settings, ideal_customer_profile: e.target.value })}
415
+ placeholder="Например: Владелец бизнеса с 5-50 сотрудниками, доход от 10 млн руб/год, ищет решение для автоматизации продаж."
416
+ className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition-all outline-none resize-none min-h-[100px]"
417
+ />
418
+ </motion.div>
419
+
420
+ {/* Custom Qualification Fields */}
421
+ <motion.div variants={item} className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8">
422
+ <div className="flex items-center gap-3 mb-6">
423
+ <div className="p-2 bg-indigo-50 rounded-xl text-indigo-600">
424
+ <Brain className="w-6 h-6" />
425
+ </div>
426
+ <div>
427
+ <h2 className="text-xl font-bold text-slate-900">Поля квалификации</h2>
428
+ <p className="text-sm text-slate-500">Какую информацию AI должен собирать о клиентах</p>
429
+ </div>
430
+ </div>
431
+
432
+ <div className="flex flex-wrap gap-2 mb-6">
433
+ {settings.custom_fields.map((field) => (
434
+ <div
435
+ key={field}
436
+ className="inline-flex items-center gap-2 px-3 py-1.5 bg-indigo-50 text-indigo-700 border border-indigo-100 rounded-lg text-sm font-medium"
 
437
  >
438
+ <span>{field}</span>
439
+ <button
440
+ onClick={() => removeCustomField(field)}
441
+ className="hover:bg-indigo-200 rounded-md p-0.5 transition-colors"
442
+ >
443
+ <X className="w-3.5 h-3.5" />
444
+ </button>
445
+ </div>
446
+ ))}
447
+ </div>
448
+
449
+ <div className="flex gap-3">
450
+ <input
451
+ type="text"
452
+ value={newField}
453
+ onChange={(e) => setNewField(e.target.value)}
454
+ onKeyDown={(e) => e.key === 'Enter' && addCustomField()}
455
+ placeholder="Например: Регион, Количество сотрудников..."
456
+ className="flex-1 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition-all outline-none"
457
+ />
458
+ <button
459
+ onClick={addCustomField}
460
+ className="px-6 py-3 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-bold shadow-lg hover:shadow-indigo-500/25 transition-all flex items-center gap-2"
461
+ >
462
+ <Plus className="w-5 h-5" />
463
+ Добавить
464
+ </button>
465
+ </div>
466
+ </motion.div>
467
+
468
+ {/* Custom Instructions */}
469
+ <motion.div variants={item} className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8">
470
+ <div className="flex items-center gap-3 mb-6">
471
+ <div className="p-2 bg-emerald-50 rounded-xl text-emerald-600">
472
+ <Award className="w-6 h-6" />
473
  </div>
474
+ <div>
475
+ <h2 className="text-xl font-bold text-slate-900">Правила поведения (Global Prompt)</h2>
476
+ <p className="text-sm text-slate-500">Специальные инструкции для AI</p>
477
+ </div>
478
+ </div>
479
 
480
+ <textarea
481
+ value={persona.custom_instructions}
482
+ onChange={(e) => setPersona({ ...persona, custom_instructions: e.target.value })}
483
+ placeholder="Например:&#10;- Никогда не говори цену до выяснения бюджета&#10;- Всегда упоминай наше УТП: внедрение за 1 день&#10;- Если клиент сравнивает с конкурентами, подчеркни скорость"
484
+ className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 transition-all outline-none resize-none min-h-[150px] font-mono text-sm"
 
 
 
485
  />
486
+ </motion.div>
487
+
488
+ {/* Banned Words */}
489
+ <motion.div variants={item} className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8">
490
+ <div className="flex items-center gap-3 mb-6">
491
+ <div className="p-2 bg-red-50 rounded-xl text-red-600">
492
+ <Ban className="w-6 h-6" />
493
+ </div>
494
+ <div>
495
+ <h2 className="text-xl font-bold text-slate-900">Запрещенные слова</h2>
496
+ <p className="text-sm text-slate-500">Слова и фразы, которые AI никогда не должен использовать</p>
497
+ </div>
498
+ </div>
499
+
500
+ <div className="flex flex-wrap gap-2 mb-6">
501
+ {persona.banned_words.map((word) => (
502
+ <div
503
+ key={word}
504
+ className="inline-flex items-center gap-2 px-3 py-1.5 bg-red-50 text-red-700 border border-red-100 rounded-lg text-sm font-medium"
505
+ >
506
+ <span>{word}</span>
507
+ <button
508
+ onClick={() => removeBannedWord(word)}
509
+ className="hover:bg-red-200 rounded-md p-0.5 transition-colors"
510
+ >
511
+ <X className="w-3.5 h-3.5" />
512
+ </button>
513
+ </div>
514
+ ))}
515
+ </div>
516
+
517
+ <div className="flex gap-3">
518
+ <input
519
+ type="text"
520
+ value={newBannedWord}
521
+ onChange={(e) => setNewBannedWord(e.target.value)}
522
+ onKeyDown={(e) => e.key === 'Enter' && addBannedWord()}
523
+ placeholder="Например: дешево, бесплатно, скидка..."
524
+ className="flex-1 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all outline-none"
525
+ />
526
+ <button
527
+ onClick={addBannedWord}
528
+ className="px-6 py-3 bg-red-600 hover:bg-red-700 text-white rounded-xl font-bold shadow-lg hover:shadow-red-500/25 transition-all flex items-center gap-2"
529
+ >
530
+ <Plus className="w-5 h-5" />
531
+ Добавить
532
+ </button>
533
+ </div>
534
+ </motion.div>
535
+
536
+ {/* ROI Calculator Settings */}
537
+ <motion.div variants={item} className="bg-gradient-to-br from-emerald-50 to-teal-50 rounded-2xl border border-emerald-100 p-8 shadow-sm">
538
+ <div className="flex items-center gap-3 mb-6">
539
+ <div className="p-2 bg-emerald-100 rounded-xl text-emerald-600">
540
+ <Calculator className="w-6 h-6" />
541
+ </div>
542
+ <div>
543
+ <h2 className="text-xl font-bold text-slate-900">Настройки ROI (Калькулятор выгоды)</h2>
544
+ <p className="text-sm text-slate-600">Настройте расчёт экономии от AI</p>
545
+ </div>
546
+ </div>
547
+
548
+ <div>
549
+ <label className="block text-sm font-bold text-slate-700 mb-2">
550
+ <div className="flex items-center gap-2">
551
+ <DollarSign className="w-4 h-4 text-emerald-600" />
552
+ Средняя зарплата менеджера (USD/месяц)
553
+ </div>
554
+ </label>
555
+ <input
556
+ type="number"
557
+ min="0"
558
+ step="100"
559
+ value={persona.manager_monthly_salary}
560
+ onChange={(e) => setPersona({ ...persona, manager_monthly_salary: parseInt(e.target.value) || 1000 })}
561
+ className="w-full md:w-64 px-4 py-3 bg-white border border-emerald-200 rounded-xl focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 transition-all outline-none font-semibold text-emerald-900"
562
+ placeholder="1000"
563
+ />
564
+ <div className="mt-3 flex items-start gap-2 text-xs text-emerald-700 bg-emerald-100/50 p-3 rounded-lg border border-emerald-100">
565
+ <AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
566
+ <p>
567
+ Мы рассчитываем почасовую ставку (зарплата / 160 часов) и экономию времени AI (3 мин на сообщение).
568
+ </p>
569
+ </div>
570
+ </div>
571
+ </motion.div>
572
+
573
+ {/* Save Button */}
574
+ <motion.div variants={item} className="flex justify-end pt-4 pb-12">
575
  <button
576
+ onClick={handleSave}
577
+ disabled={saving}
578
+ className="px-8 py-4 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 text-white rounded-xl font-bold shadow-xl hover:shadow-2xl hover:-translate-y-1 transition-all duration-300 flex items-center gap-3 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none"
579
  >
580
+ {saving ? (
581
+ <>
582
+ <Loader2 className="w-6 h-6 animate-spin" />
583
+ Сохранение...
584
+ </>
585
+ ) : (
586
+ <>
587
+ <Save className="w-6 h-6" />
588
+ Сохранить настройки
589
+ </>
590
+ )}
591
  </button>
592
+ </motion.div>
593
+ </motion.div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594
  </div>
595
  </div>
596
  )
frontend/app/settings/partner/page.tsx CHANGED
@@ -4,17 +4,21 @@ import { useState, useEffect } from 'react'
4
  import { useAuth } from '@/contexts/AuthContext'
5
  import { useToast } from '@/contexts/ToastContext'
6
  import { useRouter } from 'next/navigation'
7
- import {
8
- Crown,
9
- CheckCircle,
10
  DollarSign,
11
  Users,
12
  TrendingUp,
13
  Link2,
14
  Sparkles,
15
  AlertCircle,
16
- Loader2
 
 
17
  } from 'lucide-react'
 
 
18
 
19
  interface PartnerStatus {
20
  is_partner: boolean
@@ -94,8 +98,8 @@ export default function PartnerActivationPage() {
94
 
95
  if (loading) {
96
  return (
97
- <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center">
98
- <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
99
  </div>
100
  )
101
  }
@@ -106,169 +110,220 @@ export default function PartnerActivationPage() {
106
  return null
107
  }
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  return (
110
- <div className="min-h-screen bg-gradient-to-br from-slate-50 via-indigo-50/30 to-purple-50/20">
111
- {/* Header */}
112
- <div className="bg-white border-b-2 border-indigo-100 shadow-sm">
113
- <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
114
- <div className="flex items-center gap-4">
115
- <div className="p-3 bg-gradient-to-br from-purple-500 to-pink-600 rounded-xl shadow-lg">
116
- <Crown className="w-8 h-8 text-white" />
117
- </div>
118
- <div>
119
- <h1 className="text-3xl font-bold bg-gradient-to-r from-purple-600 to-pink-600 bg-clip-text text-transparent">
120
- Партнёрская программа
121
- </h1>
122
- <p className="text-sm text-slate-600 mt-1">Зарабатывайте 50% с каждого клиента</p>
123
- </div>
124
  </div>
125
- </div>
126
- </div>
 
 
 
 
 
127
 
128
- <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
129
- {/* Benefits */}
130
- <div className="bg-white rounded-2xl shadow-lg border-2 border-indigo-100 p-8 mb-8">
131
- <h2 className="text-2xl font-bold text-slate-900 mb-6 flex items-center gap-2">
132
- <Sparkles className="w-6 h-6 text-indigo-600" />
133
- Преимущества партнёрской программы
134
- </h2>
 
 
 
 
 
 
 
135
 
136
- <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
137
- <div className="flex items-start gap-4">
138
- <div className="p-3 bg-emerald-100 rounded-xl">
139
- <DollarSign className="w-6 h-6 text-emerald-600" />
140
- </div>
141
- <div>
142
- <h3 className="font-bold text-slate-900 mb-1">50% комиссия</h3>
143
- <p className="text-sm text-slate-600">Получайте половину от каждого платежа ваших клиентов</p>
144
- </div>
145
- </div>
146
 
147
- <div className="flex items-start gap-4">
148
- <div className="p-3 bg-indigo-100 rounded-xl">
149
- <TrendingUp className="w-6 h-6 text-indigo-600" />
150
- </div>
151
- <div>
152
- <h3 className="font-bold text-slate-900 mb-1">Пассивный доход</h3>
153
- <p className="text-sm text-slate-600">Заработок с продлений подписок каждый месяц</p>
154
- </div>
155
- </div>
156
 
157
- <div className="flex items-start gap-4">
158
- <div className="p-3 bg-purple-100 rounded-xl">
159
- <Users className="w-6 h-6 text-purple-600" />
160
- </div>
161
- <div>
162
- <h3 className="font-bold text-slate-900 mb-1">Личная панель</h3>
163
- <p className="text-sm text-slate-600">Отслеживайте клиентов и заработок в реальном времени</p>
164
- </div>
165
- </div>
166
 
167
- <div className="flex items-start gap-4">
168
- <div className="p-3 bg-blue-100 rounded-xl">
169
- <Link2 className="w-6 h-6 text-blue-600" />
170
- </div>
171
- <div>
172
- <h3 className="font-bold text-slate-900 mb-1">Реферальная ссылка</h3>
173
- <p className="text-sm text-slate-600">Уникальная ссылка для привлечения клиентов</p>
174
- </div>
175
- </div>
176
- </div>
177
-
178
- {/* Pricing Example */}
179
- <div className="bg-gradient-to-br from-indigo-50 to-purple-50 rounded-xl p-6 border-2 border-indigo-100">
180
- <h3 className="font-bold text-slate-900 mb-3 flex items-center gap-2">
181
- <TrendingUp className="w-5 h-5 text-indigo-600" />
182
- Пример заработка:
183
- </h3>
184
- <div className="space-y-2 text-sm">
185
- <div className="flex justify-between items-center">
186
- <span className="text-slate-700">1 клиент на Start ($99/мес)</span>
187
- <span className="font-bold text-emerald-600">+$49.50/мес</span>
188
- </div>
189
- <div className="flex justify-between items-center">
190
- <span className="text-slate-700">1 клиент на Growth ($199/мес)</span>
191
- <span className="font-bold text-emerald-600">+$99.50/мес</span>
192
- </div>
193
- <div className="flex justify-between items-center">
194
- <span className="text-slate-700">1 клиент на Unlimited ($500/мес)</span>
195
- <span className="font-bold text-emerald-600">+$250/мес</span>
196
- </div>
197
- <div className="pt-3 mt-3 border-t-2 border-indigo-200 flex justify-between items-center">
198
- <span className="font-bold text-slate-900">10 клиентов (смешано):</span>
199
- <span className="text-2xl font-bold text-indigo-600">~$1,500/мес</span>
200
- </div>
201
- </div>
202
- </div>
203
- </div>
204
 
205
- {/* Activation Card */}
206
- <div className="bg-white rounded-2xl shadow-lg border-2 border-purple-200 overflow-hidden">
207
- <div className="bg-gradient-to-r from-purple-600 to-pink-600 px-8 py-6 text-white">
208
- <h2 className="text-2xl font-bold mb-2">Активация партнёрской программы</h2>
209
- <p className="text-purple-100">Единоразовый платёж: <span className="text-3xl font-bold">$500</span></p>
210
- </div>
211
 
212
- <div className="p-8">
213
- <div className="mb-6">
214
- <label className="block text-sm font-bold text-slate-700 mb-2">
215
- Название компании
216
- </label>
217
- <input
218
- type="text"
219
- value={companyName}
220
- onChange={(e) => setCompanyName(e.target.value)}
221
- placeholder="Введите название вашей компании"
222
- className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 font-semibold"
223
- />
224
- <p className="text-xs text-slate-500 mt-2">
225
- Это название будет отображаться в вашей партнёрской панели
226
- </p>
227
- </div>
228
 
229
- <div className="bg-amber-50 border-2 border-amber-200 rounded-xl p-4 mb-6">
230
- <div className="flex items-start gap-3">
231
- <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
232
- <div className="text-sm text-amber-800">
233
- <p className="font-bold mb-1">Важно:</p>
234
- <ul className="list-disc list-inside space-y-1">
235
- <li>Единоразовый платёж $500 за доступ к партнёрской программе</li>
236
- <li>После активации получите реферальную ссылку</li>
237
- <li>Комиссия 50% начисляется автоматически</li>
238
- <li>Доступ к партнёрской панели навсегда</li>
239
- </ul>
 
 
 
 
 
 
240
  </div>
241
- </div>
242
- </div>
243
 
244
- <button
245
- onClick={handleActivate}
246
- disabled={activating || !companyName.trim()}
247
- className="w-full px-8 py-4 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-500 hover:to-pink-500 text-white font-bold rounded-xl transition-all shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-lg"
 
248
  >
249
- {activating ? (
250
- <>
251
- <Loader2 className="w-6 h-6 animate-spin" />
252
- Активация...
253
- </>
254
- ) : (
255
- <>
256
- <Crown className="w-6 h-6" />
257
- Активировать за $500
258
- </>
259
- )}
260
- </button>
261
 
262
- <div className="mt-6 flex items-center justify-center gap-4 text-sm text-slate-500">
263
- <div className="flex items-center gap-1">
264
- <CheckCircle className="w-4 h-4 text-emerald-600" />
265
- <span>Безопасный платёж</span>
266
- </div>
267
- <div className="flex items-center gap-1">
268
- <CheckCircle className="w-4 h-4 text-emerald-600" />
269
- <span>Мгновенная активация</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  </div>
271
- </div>
272
  </div>
273
  </div>
274
  </div>
 
4
  import { useAuth } from '@/contexts/AuthContext'
5
  import { useToast } from '@/contexts/ToastContext'
6
  import { useRouter } from 'next/navigation'
7
+ import {
8
+ Crown,
9
+ CheckCircle,
10
  DollarSign,
11
  Users,
12
  TrendingUp,
13
  Link2,
14
  Sparkles,
15
  AlertCircle,
16
+ Loader2,
17
+ ShieldCheck,
18
+ ArrowRight
19
  } from 'lucide-react'
20
+ import { motion, AnimatePresence } from 'framer-motion'
21
+ import { cn } from '@/lib/utils'
22
 
23
  interface PartnerStatus {
24
  is_partner: boolean
 
98
 
99
  if (loading) {
100
  return (
101
+ <div className="flex items-center justify-center min-h-screen bg-slate-50">
102
+ <Loader2 className="w-12 h-12 animate-spin text-indigo-600" />
103
  </div>
104
  )
105
  }
 
110
  return null
111
  }
112
 
113
+ const container = {
114
+ hidden: { opacity: 0 },
115
+ show: {
116
+ opacity: 1,
117
+ transition: {
118
+ staggerChildren: 0.1
119
+ }
120
+ }
121
+ }
122
+
123
+ const item = {
124
+ hidden: { opacity: 0, y: 20 },
125
+ show: { opacity: 1, y: 0 }
126
+ }
127
+
128
  return (
129
+ <div className="min-h-screen bg-slate-50/50 p-8">
130
+ <div className="max-w-7xl mx-auto">
131
+ {/* Header */}
132
+ <motion.div
133
+ initial={{ opacity: 0, y: -20 }}
134
+ animate={{ opacity: 1, y: 0 }}
135
+ className="flex items-center gap-4 mb-12"
136
+ >
137
+ <div className="p-3 bg-gradient-to-br from-purple-600 to-pink-600 rounded-2xl shadow-lg shadow-purple-200">
138
+ <Crown className="w-8 h-8 text-white" />
 
 
 
 
139
  </div>
140
+ <div>
141
+ <h1 className="text-3xl font-bold bg-gradient-to-r from-purple-600 to-pink-600 bg-clip-text text-transparent tracking-tight">
142
+ Партнёрская программа
143
+ </h1>
144
+ <p className="text-slate-600 mt-1">Зарабатывайте 50% с каждого клиента</p>
145
+ </div>
146
+ </motion.div>
147
 
148
+ <div className="max-w-5xl mx-auto">
149
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
150
+ {/* Benefits Column */}
151
+ <motion.div
152
+ variants={container}
153
+ initial="hidden"
154
+ animate="show"
155
+ className="space-y-6"
156
+ >
157
+ <motion.div variants={item} className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8">
158
+ <h2 className="text-xl font-bold text-slate-900 mb-6 flex items-center gap-2">
159
+ <Sparkles className="w-5 h-5 text-indigo-600" />
160
+ Преимущества партнёрства
161
+ </h2>
162
 
163
+ <div className="space-y-6">
164
+ <div className="flex items-start gap-4">
165
+ <div className="p-3 bg-emerald-50 rounded-xl text-emerald-600">
166
+ <DollarSign className="w-6 h-6" />
167
+ </div>
168
+ <div>
169
+ <h3 className="font-bold text-slate-900 mb-1">50% комиссия</h3>
170
+ <p className="text-sm text-slate-600 leading-relaxed">Получайте половину от каждого платежа ваших клиентов ежемесячно</p>
171
+ </div>
172
+ </div>
173
 
174
+ <div className="flex items-start gap-4">
175
+ <div className="p-3 bg-indigo-50 rounded-xl text-indigo-600">
176
+ <TrendingUp className="w-6 h-6" />
177
+ </div>
178
+ <div>
179
+ <h3 className="font-bold text-slate-900 mb-1">Пассивный доход</h3>
180
+ <p className="text-sm text-slate-600 leading-relaxed">Заработок с продлений подписок каждый месяц, пока клиент активен</p>
181
+ </div>
182
+ </div>
183
 
184
+ <div className="flex items-start gap-4">
185
+ <div className="p-3 bg-purple-50 rounded-xl text-purple-600">
186
+ <Users className="w-6 h-6" />
187
+ </div>
188
+ <div>
189
+ <h3 className="font-bold text-slate-900 mb-1">Личная панель</h3>
190
+ <p className="text-sm text-slate-600 leading-relaxed">Отслеживайте клиентов, начисления и выплаты в реальном времени</p>
191
+ </div>
192
+ </div>
193
 
194
+ <div className="flex items-start gap-4">
195
+ <div className="p-3 bg-blue-50 rounded-xl text-blue-600">
196
+ <Link2 className="w-6 h-6" />
197
+ </div>
198
+ <div>
199
+ <h3 className="font-bold text-slate-900 mb-1">Реферальная ссылка</h3>
200
+ <p className="text-sm text-slate-600 leading-relaxed">Уникальная ссылка для привлечения клиентов с автоматическим трекингом</p>
201
+ </div>
202
+ </div>
203
+ </div>
204
+ </motion.div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
+ {/* Pricing Example */}
207
+ <motion.div variants={item} className="bg-gradient-to-br from-indigo-600 to-purple-700 rounded-2xl p-8 text-white shadow-xl relative overflow-hidden">
208
+ <div className="absolute top-0 right-0 w-64 h-64 bg-white/10 rounded-full blur-3xl -mr-32 -mt-32" />
209
+ <div className="absolute bottom-0 left-0 w-64 h-64 bg-black/10 rounded-full blur-3xl -ml-32 -mb-32" />
 
 
210
 
211
+ <h3 className="font-bold text-lg mb-6 flex items-center gap-2 relative z-10">
212
+ <TrendingUp className="w-5 h-5" />
213
+ Пример заработка:
214
+ </h3>
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
+ <div className="space-y-4 relative z-10">
217
+ <div className="flex justify-between items-center py-2 border-b border-white/10">
218
+ <span className="text-indigo-100">1 клиент на Start ($99)</span>
219
+ <span className="font-bold text-emerald-300">+$49.50/мес</span>
220
+ </div>
221
+ <div className="flex justify-between items-center py-2 border-b border-white/10">
222
+ <span className="text-indigo-100">1 клиент на Growth ($199)</span>
223
+ <span className="font-bold text-emerald-300">+$99.50/мес</span>
224
+ </div>
225
+ <div className="flex justify-between items-center py-2 border-b border-white/10">
226
+ <span className="text-indigo-100">1 клиент на Scale ($499)</span>
227
+ <span className="font-bold text-emerald-300">+$249.50/мес</span>
228
+ </div>
229
+ <div className="pt-4 flex justify-between items-center">
230
+ <span className="font-bold text-white">10 клиентов (смешано):</span>
231
+ <span className="text-3xl font-bold text-white">~$1,500<span className="text-sm font-normal text-indigo-200">/мес</span></span>
232
+ </div>
233
  </div>
234
+ </motion.div>
235
+ </motion.div>
236
 
237
+ {/* Activation Column */}
238
+ <motion.div
239
+ initial={{ opacity: 0, x: 20 }}
240
+ animate={{ opacity: 1, x: 0 }}
241
+ transition={{ delay: 0.3 }}
242
  >
243
+ <div className="bg-white rounded-2xl shadow-xl border border-purple-100 overflow-hidden sticky top-8">
244
+ <div className="bg-gradient-to-r from-purple-600 to-pink-600 px-8 py-8 text-white relative overflow-hidden">
245
+ <div className="absolute top-0 right-0 w-64 h-64 bg-white/10 rounded-full blur-3xl -mr-16 -mt-32" />
 
 
 
 
 
 
 
 
 
246
 
247
+ <h2 className="text-2xl font-bold mb-2 relative z-10">Активация программы</h2>
248
+ <p className="text-purple-100 relative z-10">Станьте партнёром MicroFunnel Studio</p>
249
+
250
+ <div className="mt-6 inline-flex items-baseline gap-2 relative z-10">
251
+ <span className="text-4xl font-bold">$500</span>
252
+ <span className="text-purple-200 font-medium">единоразово</span>
253
+ </div>
254
+ </div>
255
+
256
+ <div className="p-8">
257
+ <div className="mb-8">
258
+ <label className="block text-sm font-bold text-slate-700 mb-2">
259
+ Название компании
260
+ </label>
261
+ <input
262
+ type="text"
263
+ value={companyName}
264
+ onChange={(e) => setCompanyName(e.target.value)}
265
+ placeholder="Введите название вашей компании"
266
+ className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500 font-semibold transition-all outline-none"
267
+ />
268
+ <p className="text-xs text-slate-500 mt-2">
269
+ Это название будет отображаться в вашей партнёрской панели
270
+ </p>
271
+ </div>
272
+
273
+ <div className="bg-amber-50 border border-amber-100 rounded-xl p-4 mb-8">
274
+ <div className="flex items-start gap-3">
275
+ <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
276
+ <div className="text-sm text-amber-800">
277
+ <p className="font-bold mb-1">Важно:</p>
278
+ <ul className="space-y-1.5">
279
+ <li className="flex items-center gap-2">
280
+ <span className="w-1 h-1 bg-amber-600 rounded-full" />
281
+ Единоразовый платёж за доступ
282
+ </li>
283
+ <li className="flex items-center gap-2">
284
+ <span className="w-1 h-1 bg-amber-600 rounded-full" />
285
+ Мгновенное получение реферальной ссылки
286
+ </li>
287
+ <li className="flex items-center gap-2">
288
+ <span className="w-1 h-1 bg-amber-600 rounded-full" />
289
+ Доступ к партнёрской панели навсегда
290
+ </li>
291
+ </ul>
292
+ </div>
293
+ </div>
294
+ </div>
295
+
296
+ <button
297
+ onClick={handleActivate}
298
+ disabled={activating || !companyName.trim()}
299
+ className="w-full px-8 py-4 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-500 hover:to-pink-500 text-white font-bold rounded-xl transition-all shadow-lg hover:shadow-purple-500/25 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-lg group"
300
+ >
301
+ {activating ? (
302
+ <>
303
+ <Loader2 className="w-6 h-6 animate-spin" />
304
+ Активация...
305
+ </>
306
+ ) : (
307
+ <>
308
+ <span>Активировать за $500</span>
309
+ <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
310
+ </>
311
+ )}
312
+ </button>
313
+
314
+ <div className="mt-6 flex items-center justify-center gap-6 text-xs font-medium text-slate-500">
315
+ <div className="flex items-center gap-1.5">
316
+ <ShieldCheck className="w-4 h-4 text-emerald-500" />
317
+ <span>Безопасный платёж</span>
318
+ </div>
319
+ <div className="flex items-center gap-1.5">
320
+ <CheckCircle className="w-4 h-4 text-emerald-500" />
321
+ <span>Мгновенный доступ</span>
322
+ </div>
323
+ </div>
324
+ </div>
325
  </div>
326
+ </motion.div>
327
  </div>
328
  </div>
329
  </div>
frontend/app/settings/playbook/page.tsx CHANGED
@@ -4,11 +4,11 @@ import { useState, useEffect } from 'react'
4
  import { useAuth } from '@/contexts/AuthContext'
5
  import { useToast } from '@/contexts/ToastContext'
6
  import { playbookApi } from '@/lib/api'
7
- import {
8
- ArrowUp,
9
- ArrowDown,
10
- Plus,
11
- Trash2,
12
  Save,
13
  Target,
14
  CheckCircle,
@@ -23,8 +23,12 @@ import {
23
  Sparkles,
24
  AlertCircle,
25
  Edit3,
26
- GripVertical
 
 
27
  } from 'lucide-react'
 
 
28
 
29
  interface SalesStage {
30
  id: string
@@ -63,7 +67,7 @@ export default function PlaybookEditorPage() {
63
  const [showTemplateModal, setShowTemplateModal] = useState(false)
64
  const [templates, setTemplates] = useState<Template[]>([])
65
  const [customFields, setCustomFields] = useState<string[]>([])
66
-
67
  // Form state for selected stage
68
  const [formData, setFormData] = useState({
69
  name: '',
@@ -125,7 +129,7 @@ export default function PlaybookEditorPage() {
125
 
126
  const handleSave = async () => {
127
  if (!selectedStage) return
128
-
129
  setSaving(true)
130
  try {
131
  await playbookApi.updateStage(selectedStage.id, formData)
@@ -175,29 +179,29 @@ export default function PlaybookEditorPage() {
175
 
176
  const handleMoveUp = async (index: number) => {
177
  if (index === 0) return
178
-
179
  const newStages = [...stages]
180
  const temp = newStages[index]
181
  newStages[index] = newStages[index - 1]
182
  newStages[index - 1] = temp
183
-
184
  await reorderStages(newStages)
185
  }
186
 
187
  const handleMoveDown = async (index: number) => {
188
  if (index === stages.length - 1) return
189
-
190
  const newStages = [...stages]
191
  const temp = newStages[index]
192
  newStages[index] = newStages[index + 1]
193
  newStages[index + 1] = temp
194
-
195
  await reorderStages(newStages)
196
  }
197
 
198
  const reorderStages = async (newStages: SalesStage[]) => {
199
  const stage_ids = newStages.map(s => s.id)
200
-
201
  try {
202
  await playbookApi.reorderStages(stage_ids)
203
  setStages(newStages)
@@ -229,161 +233,170 @@ export default function PlaybookEditorPage() {
229
 
230
  if (loading) {
231
  return (
232
- <div className="min-h-screen bg-gradient-to-br from-slate-50 via-indigo-50/30 to-purple-50/20 flex items-center justify-center">
233
- <div className="text-center">
234
- <div className="animate-spin rounded-full h-16 w-16 border-b-4 border-indigo-600 mx-auto mb-4"></div>
235
- <p className="text-lg font-semibold text-slate-700">Загрузка воронки...</p>
236
- </div>
237
  </div>
238
  )
239
  }
240
 
241
  return (
242
- <div className="min-h-screen bg-gradient-to-br from-slate-50 via-indigo-50/30 to-purple-50/20">
243
- {/* Header */}
244
- <div className="bg-white border-b-2 border-indigo-100 shadow-sm">
245
- <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
246
- <div className="flex items-center justify-between">
247
- <div className="flex items-center gap-4">
248
- <div className="p-3 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-xl shadow-lg">
249
- <Target className="w-8 h-8 text-white" />
250
- </div>
251
- <div>
252
- <h1 className="text-3xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
253
- Настройка Воронки
254
- </h1>
255
- <p className="text-sm text-slate-600 mt-1 flex items-center gap-2">
256
- <Sparkles className="w-4 h-4 text-indigo-500" />
257
- Настройте этапы продаж и цели AI
258
- </p>
259
- </div>
260
  </div>
261
- <div className="flex items-center gap-3">
262
- <span className="text-xs text-slate-500">
263
- Этапов: <span className="font-bold text-indigo-600">{stages.length}</span>
264
- </span>
 
 
 
 
265
  </div>
266
  </div>
267
- </div>
268
- </div>
 
 
 
 
 
 
 
269
 
270
- {/* Main Content */}
271
- <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
272
- <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
273
-
274
  {/* Left: Stage List */}
275
- <div className="lg:col-span-1">
276
- <div className="bg-white rounded-2xl shadow-lg border-2 border-indigo-100 p-6">
277
- <div className="flex items-center justify-between mb-6">
 
 
 
 
 
278
  <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
279
- <GripVertical className="w-5 h-5 text-indigo-500" />
280
  Этапы воронки
281
  </h2>
282
  <div className="flex items-center gap-2">
283
  <button
284
  onClick={() => setShowTemplateModal(true)}
285
- className="flex items-center gap-1.5 text-xs text-slate-600 hover:text-indigo-600 font-semibold px-3 py-2 border-2 border-slate-200 hover:border-indigo-300 rounded-lg hover:bg-indigo-50 transition-all"
 
286
  >
287
- <FolderOpen className="w-4 h-4" />
288
- Шаблон
289
  </button>
290
  <button
291
  onClick={handleAddStage}
292
- className="flex items-center gap-1.5 text-xs text-white bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 font-semibold px-3 py-2 rounded-lg shadow-md hover:shadow-lg transition-all"
 
293
  >
294
- <Plus className="w-4 h-4" />
295
- Добавить
296
  </button>
297
  </div>
298
  </div>
299
 
300
- <div className="space-y-3">
301
- {stages.map((stage, index) => (
302
- <div
303
- key={stage.id}
304
- className={`
305
- group relative p-4 rounded-xl border-2 cursor-pointer transition-all duration-200
306
- ${selectedStage?.id === stage.id
307
- ? 'border-indigo-500 bg-gradient-to-r from-indigo-50 to-purple-50 shadow-lg scale-[1.02]'
308
- : 'border-slate-200 hover:border-indigo-300 bg-white hover:shadow-md'
309
- }
310
- `}
311
- onClick={() => setSelectedStage(stage)}
312
- >
313
- {/* Drag Indicator */}
314
- <div className="absolute left-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity">
315
- <GripVertical className="w-4 h-4 text-slate-400" />
316
- </div>
317
-
318
- <div className="flex items-start justify-between pl-2">
319
- <div className="flex-1">
320
- {/* Step Number Badge */}
321
- <div className="flex items-center gap-2 mb-2">
322
- <span className={`
323
- inline-flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold
324
- ${selectedStage?.id === stage.id
325
- ? 'bg-indigo-600 text-white'
326
- : 'bg-slate-200 text-slate-600 group-hover:bg-indigo-100 group-hover:text-indigo-600'
327
- }
328
- `}>
329
  {index + 1}
330
  </span>
331
- <ChevronRight className={`w-4 h-4 ${selectedStage?.id === stage.id ? 'text-indigo-500' : 'text-slate-400'}`} />
 
 
 
332
  </div>
333
-
334
- {/* Stage Name */}
335
- <h3 className={`font-bold text-base mb-2 ${selectedStage?.id === stage.id ? 'text-indigo-700' : 'text-slate-900'}`}>
336
- {stage.name}
337
- </h3>
338
-
339
- {/* Criteria Count */}
340
- {stage.exit_criteria.length > 0 && (
341
- <div className="flex items-center gap-1.5">
342
- <CheckCircle className="w-4 h-4 text-emerald-600" />
343
- <span className="text-xs font-semibold text-emerald-600">
344
- {stage.exit_criteria.length} критериев
345
- </span>
346
  </div>
347
- )}
348
- </div>
349
 
350
- {/* Move Buttons */}
351
- <div className="flex flex-col gap-1 ml-2">
352
- <button
353
- onClick={(e) => {
354
- e.stopPropagation()
355
- handleMoveUp(index)
356
- }}
357
- disabled={index === 0}
358
- className="p-1.5 rounded-lg hover:bg-indigo-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
359
- >
360
- <ArrowUp className="w-4 h-4 text-indigo-600" />
361
- </button>
362
- <button
363
- onClick={(e) => {
364
- e.stopPropagation()
365
- handleMoveDown(index)
366
- }}
367
- disabled={index === stages.length - 1}
368
- className="p-1.5 rounded-lg hover:bg-indigo-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
369
- >
370
- <ArrowDown className="w-4 h-4 text-indigo-600" />
371
- </button>
 
 
 
 
 
 
 
 
 
 
372
  </div>
373
- </div>
374
- </div>
375
- ))}
376
 
377
  {stages.length === 0 && (
378
- <div className="text-center py-16">
379
- <div className="w-16 h-16 bg-gradient-to-br from-indigo-100 to-purple-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
380
- <Target className="w-8 h-8 text-indigo-600" />
381
  </div>
382
- <h3 className="font-bold text-slate-900 mb-2">Нет этапов</h3>
383
- <p className="text-sm text-slate-500 mb-4">Создайте первый этап воронки</p>
384
  <button
385
  onClick={handleAddStage}
386
- className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold rounded-lg transition-colors"
387
  >
388
  Создать этап
389
  </button>
@@ -391,213 +404,251 @@ export default function PlaybookEditorPage() {
391
  )}
392
  </div>
393
  </div>
394
- </div>
395
 
396
  {/* Right: Stage Editor */}
397
- <div className="lg:col-span-2">
398
- {selectedStage ? (
399
- <div className="bg-white rounded-2xl shadow-lg border-2 border-indigo-100 p-6">
400
- <div className="flex items-center justify-between mb-6 pb-4 border-b-2 border-slate-100">
401
- <div className="flex items-center gap-3">
402
- <div className="p-2 bg-indigo-100 rounded-lg">
403
- <Edit3 className="w-5 h-5 text-indigo-600" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
  </div>
405
- <h2 className="text-xl font-bold text-slate-900">Редактирование этапа</h2>
 
 
 
 
 
 
406
  </div>
407
- <button
408
- onClick={() => handleDelete(selectedStage.id)}
409
- className="flex items-center gap-2 text-sm text-red-600 hover:text-white hover:bg-red-600 font-semibold px-4 py-2 border-2 border-red-600 rounded-lg transition-all"
410
- >
411
- <Trash2 className="w-4 h-4" />
412
- Удалить
413
- </button>
414
- </div>
415
 
416
- <div className="space-y-6">
417
- {/* Stage Name */}
418
- <div>
419
- <label className="block text-sm font-bold text-slate-700 mb-2 flex items-center gap-2">
420
- <span className="w-1.5 h-1.5 bg-indigo-600 rounded-full"></span>
421
- Название этапа
422
- </label>
423
- <input
424
- type="text"
425
- value={formData.name}
426
- onChange={(e) => setFormData({ ...formData, name: e.target.value })}
427
- className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 font-semibold transition-all"
428
- placeholder="например: Квалификация, Демо, Коммерческое предложение"
429
- />
430
- </div>
431
 
432
- {/* Description */}
433
- <div>
434
- <label className="block text-sm font-bold text-slate-700 mb-2 flex items-center gap-2">
435
- <span className="w-1.5 h-1.5 bg-purple-600 rounded-full"></span>
436
- Описание <span className="text-xs font-normal text-slate-500">(опционально)</span>
437
- </label>
438
- <input
439
- type="text"
440
- value={formData.description}
441
- onChange={(e) => setFormData({ ...formData, description: e.target.value })}
442
- className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition-all"
443
- placeholder="Краткое описание этого этапа"
444
- />
445
- </div>
446
 
447
- {/* AI Goal */}
448
- <div className="p-4 bg-gradient-to-br from-indigo-50 to-purple-50 rounded-xl border-2 border-indigo-100">
449
- <label className="block text-sm font-bold text-slate-900 mb-3 flex items-center gap-2">
450
- <Sparkles className="w-5 h-5 text-indigo-600" />
451
- Цель AI на этом этапе
452
- </label>
453
- <textarea
454
- value={formData.ai_goal}
455
- onChange={(e) => setFormData({ ...formData, ai_goal: e.target.value })}
456
- rows={5}
457
- className="w-full px-4 py-3 border-2 border-indigo-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-white transition-all"
458
- placeholder="Пример: Узнайте ��юджет клиента и сроки принятия решения. Задавайте открытые вопросы, чтобы понять их срочность."
459
- />
460
- <div className="mt-3 flex items-start gap-2 text-xs text-indigo-700 bg-indigo-100 px-3 py-2 rounded-lg">
461
- <AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
462
- <span>
463
- <strong>Скажите AI,</strong> что она должна достичь на этом этапе разговора. Чем конкретнее, тем лучше!
464
- </span>
 
465
  </div>
466
- </div>
467
 
468
- {/* Exit Criteria */}
469
- <div className="p-4 bg-gradient-to-br from-emerald-50 to-teal-50 rounded-xl border-2 border-emerald-100">
470
- <label className="block text-sm font-bold text-slate-900 mb-2 flex items-center gap-2">
471
- <CheckCircle className="w-5 h-5 text-emerald-600" />
472
- Критерии завершения этапа
473
- </label>
474
- <p className="text-sm text-slate-600 mb-4">
475
- Выберите поля, которые AI должна заполнить перед переходом к следующему этапу:
476
- </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
477
 
478
- <div className="grid grid-cols-2 gap-3">
479
- {customFields.map((field) => (
480
- <label
481
- key={field}
482
- className={`
483
- flex items-center gap-3 p-3 rounded-xl border-2 cursor-pointer transition-all
484
- ${formData.exit_criteria.includes(field)
485
- ? 'border-emerald-500 bg-emerald-100 shadow-md'
486
- : 'border-slate-200 hover:border-emerald-300 bg-white hover:shadow-sm'
487
- }
488
- `}
489
- >
490
- <input
491
- type="checkbox"
492
- checked={formData.exit_criteria.includes(field)}
493
- onChange={() => toggleCriteria(field)}
494
- className="w-5 h-5 text-emerald-600 border-slate-300 rounded focus:ring-emerald-500"
495
- />
496
- <span className={`text-sm font-semibold ${
497
- formData.exit_criteria.includes(field) ? 'text-emerald-900' : 'text-slate-700'
498
- }`}>
499
- {field}
500
- </span>
501
- </label>
502
- ))}
503
  </div>
504
 
505
- {formData.exit_criteria.length === 0 && (
506
- <div className="mt-4 flex items-start gap-2 text-xs text-amber-800 bg-amber-100 px-3 py-3 rounded-lg border-2 border-amber-200">
507
- <AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
508
- <span>
509
- <strong>Внимание:</strong> Не выбрано ни одного критерия. Этот этап всегда будет считаться завершённым.
510
- </span>
511
- </div>
512
- )}
 
 
 
 
 
 
 
 
 
 
 
 
513
  </div>
514
-
515
- {/* Save Button */}
516
- <div className="pt-4 border-t-2 border-slate-100">
517
- <button
518
- onClick={handleSave}
519
- disabled={saving}
520
- className="w-full flex items-center justify-center gap-2 px-6 py-4 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 text-white font-bold rounded-xl transition-all shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed text-lg"
521
- >
522
- <Save className="w-6 h-6" />
523
- {saving ? 'Сохранение...' : 'Сохранить изменения'}
524
- </button>
525
  </div>
526
- </div>
527
- </div>
528
- ) : (
529
- <div className="bg-white rounded-2xl shadow-lg border-2 border-slate-200 p-12 text-center">
530
- <div className="w-20 h-20 bg-gradient-to-br from-slate-100 to-slate-200 rounded-2xl flex items-center justify-center mx-auto mb-4">
531
- <Target className="w-10 h-10 text-slate-400" />
532
- </div>
533
- <h3 className="text-xl font-bold text-slate-900 mb-2">
534
- Этап не выбран
535
- </h3>
536
- <p className="text-sm text-slate-500">
537
- Выберите этап слева для редактирования
538
- </p>
539
- </div>
540
- )}
541
- </div>
542
  </div>
543
  </div>
544
 
545
  {/* Template Modal */}
546
- {showTemplateModal && (
547
- <div className="fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
548
- <div className="bg-white rounded-2xl shadow-2xl max-w-3xl w-full max-h-[85vh] overflow-y-auto">
549
- <div className="sticky top-0 bg-gradient-to-r from-indigo-600 to-purple-600 px-6 py-5 flex items-center justify-between">
550
- <div className="flex items-center gap-3">
551
- <div className="p-2 bg-white/20 rounded-lg">
552
- <FolderOpen className="w-6 h-6 text-white" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
553
  </div>
554
- <h2 className="text-2xl font-bold text-white">Шаблоны воронок</h2>
 
 
 
 
 
555
  </div>
556
- <button
557
- onClick={() => setShowTemplateModal(false)}
558
- className="p-2 hover:bg-white/20 rounded-lg transition-colors"
559
- >
560
- <X className="w-6 h-6 text-white" />
561
- </button>
562
- </div>
563
 
564
- <div className="p-6">
565
- <p className="text-sm text-slate-600 mb-6 flex items-start gap-2">
566
- <Sparkles className="w-5 h-5 text-indigo-500 flex-shrink-0 mt-0.5" />
567
- <span>
568
- Готовые сценарии продаж для разных индустрий. Этапы можно редактировать после загрузки.
569
- </span>
570
- </p>
571
-
572
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
573
- {templates.map((template) => {
574
- const Icon = TEMPLATE_ICONS[template.id] || Target
575
- return (
576
- <button
577
- key={template.id}
578
- onClick={() => handleLoadTemplate(template.id)}
579
- className="group p-5 border-2 border-slate-200 hover:border-indigo-500 rounded-2xl transition-all bg-white hover:bg-gradient-to-br hover:from-indigo-50 hover:to-purple-50 text-left shadow-sm hover:shadow-lg"
580
- >
581
- <div className="flex items-start gap-4">
582
- <div className="p-3 bg-gradient-to-br from-indigo-100 to-purple-100 group-hover:from-indigo-200 group-hover:to-purple-200 rounded-xl transition-colors">
583
- <Icon className="w-8 h-8 text-indigo-600" />
584
- </div>
585
- <div className="flex-1">
586
- <h3 className="font-bold text-lg text-slate-900 mb-1 group-hover:text-indigo-700 transition-colors">
587
- {template.name}
588
- </h3>
589
- <p className="text-xs text-slate-500 group-hover:text-indigo-600 transition-colors">
590
- Нажмите для загрузки
591
- </p>
592
  </div>
593
- </div>
594
- </button>
595
- )
596
- })}
597
- </div>
598
 
599
- <div className="mt-6 p-4 bg-gradient-to-r from-amber-50 to-orange-50 border-2 border-amber-200 rounded-xl">
600
- <div className="flex items-start gap-3">
601
  <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
602
  <div>
603
  <p className="text-sm font-bold text-amber-900 mb-1">
@@ -609,10 +660,10 @@ export default function PlaybookEditorPage() {
609
  </div>
610
  </div>
611
  </div>
612
- </div>
613
- </div>
614
- </div>
615
- )}
616
  </div>
617
  )
618
  }
 
4
  import { useAuth } from '@/contexts/AuthContext'
5
  import { useToast } from '@/contexts/ToastContext'
6
  import { playbookApi } from '@/lib/api'
7
+ import {
8
+ ArrowUp,
9
+ ArrowDown,
10
+ Plus,
11
+ Trash2,
12
  Save,
13
  Target,
14
  CheckCircle,
 
23
  Sparkles,
24
  AlertCircle,
25
  Edit3,
26
+ GripVertical,
27
+ Loader2,
28
+ CheckCircle2
29
  } from 'lucide-react'
30
+ import { motion, AnimatePresence, Reorder } from 'framer-motion'
31
+ import { cn } from '@/lib/utils'
32
 
33
  interface SalesStage {
34
  id: string
 
67
  const [showTemplateModal, setShowTemplateModal] = useState(false)
68
  const [templates, setTemplates] = useState<Template[]>([])
69
  const [customFields, setCustomFields] = useState<string[]>([])
70
+
71
  // Form state for selected stage
72
  const [formData, setFormData] = useState({
73
  name: '',
 
129
 
130
  const handleSave = async () => {
131
  if (!selectedStage) return
132
+
133
  setSaving(true)
134
  try {
135
  await playbookApi.updateStage(selectedStage.id, formData)
 
179
 
180
  const handleMoveUp = async (index: number) => {
181
  if (index === 0) return
182
+
183
  const newStages = [...stages]
184
  const temp = newStages[index]
185
  newStages[index] = newStages[index - 1]
186
  newStages[index - 1] = temp
187
+
188
  await reorderStages(newStages)
189
  }
190
 
191
  const handleMoveDown = async (index: number) => {
192
  if (index === stages.length - 1) return
193
+
194
  const newStages = [...stages]
195
  const temp = newStages[index]
196
  newStages[index] = newStages[index + 1]
197
  newStages[index + 1] = temp
198
+
199
  await reorderStages(newStages)
200
  }
201
 
202
  const reorderStages = async (newStages: SalesStage[]) => {
203
  const stage_ids = newStages.map(s => s.id)
204
+
205
  try {
206
  await playbookApi.reorderStages(stage_ids)
207
  setStages(newStages)
 
233
 
234
  if (loading) {
235
  return (
236
+ <div className="flex items-center justify-center min-h-screen bg-slate-50">
237
+ <Loader2 className="w-12 h-12 animate-spin text-indigo-600" />
 
 
 
238
  </div>
239
  )
240
  }
241
 
242
  return (
243
+ <div className="min-h-screen bg-slate-50/50 p-8">
244
+ <div className="max-w-7xl mx-auto">
245
+ {/* Header */}
246
+ <motion.div
247
+ initial={{ opacity: 0, y: -20 }}
248
+ animate={{ opacity: 1, y: 0 }}
249
+ className="flex items-center justify-between mb-8"
250
+ >
251
+ <div className="flex items-center gap-4">
252
+ <div className="p-3 bg-indigo-600 rounded-2xl shadow-lg shadow-indigo-200">
253
+ <Target className="w-8 h-8 text-white" />
 
 
 
 
 
 
 
254
  </div>
255
+ <div>
256
+ <h1 className="text-3xl font-bold text-slate-900 mb-1 tracking-tight">
257
+ Настройка Воронки
258
+ </h1>
259
+ <p className="text-slate-600 flex items-center gap-2">
260
+ <Sparkles className="w-4 h-4 text-indigo-500" />
261
+ Настройте этапы продаж и цели AI
262
+ </p>
263
  </div>
264
  </div>
265
+ <div className="flex items-center gap-3">
266
+ <span className="text-sm font-medium text-slate-500 bg-white px-3 py-1.5 rounded-lg border border-slate-200 shadow-sm">
267
+ Этапов: <span className="font-bold text-indigo-600">{stages.length}</span>
268
+ </span>
269
+ </div>
270
+ </motion.div>
271
+
272
+ {/* Main Content */}
273
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
274
 
 
 
 
 
275
  {/* Left: Stage List */}
276
+ <motion.div
277
+ initial={{ opacity: 0, x: -20 }}
278
+ animate={{ opacity: 1, x: 0 }}
279
+ transition={{ delay: 0.1 }}
280
+ className="lg:col-span-1"
281
+ >
282
+ <div className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
283
+ <div className="p-6 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
284
  <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
285
+ <GripVertical className="w-5 h-5 text-indigo-600" />
286
  Этапы воронки
287
  </h2>
288
  <div className="flex items-center gap-2">
289
  <button
290
  onClick={() => setShowTemplateModal(true)}
291
+ className="p-2 text-slate-500 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-all"
292
+ title="Загрузить шаблон"
293
  >
294
+ <FolderOpen className="w-5 h-5" />
 
295
  </button>
296
  <button
297
  onClick={handleAddStage}
298
+ className="p-2 text-white bg-indigo-600 hover:bg-indigo-700 rounded-lg transition-all shadow-sm"
299
+ title="Добавить этап"
300
  >
301
+ <Plus className="w-5 h-5" />
 
302
  </button>
303
  </div>
304
  </div>
305
 
306
+ <div className="p-4 space-y-3 max-h-[calc(100vh-300px)] overflow-y-auto custom-scrollbar">
307
+ <AnimatePresence>
308
+ {stages.map((stage, index) => (
309
+ <motion.div
310
+ key={stage.id}
311
+ layout
312
+ initial={{ opacity: 0, y: 10 }}
313
+ animate={{ opacity: 1, y: 0 }}
314
+ exit={{ opacity: 0, scale: 0.95 }}
315
+ className={cn(
316
+ "group relative p-4 rounded-xl border-2 cursor-pointer transition-all duration-200",
317
+ selectedStage?.id === stage.id
318
+ ? "border-indigo-500 bg-indigo-50/50 shadow-md"
319
+ : "border-slate-200 hover:border-indigo-300 bg-white hover:shadow-sm"
320
+ )}
321
+ onClick={() => setSelectedStage(stage)}
322
+ >
323
+ <div className="flex items-start gap-3">
324
+ <div className="flex flex-col items-center gap-1 mt-1">
325
+ <span className={cn(
326
+ "flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold transition-colors",
327
+ selectedStage?.id === stage.id
328
+ ? "bg-indigo-600 text-white"
329
+ : "bg-slate-100 text-slate-500 group-hover:bg-indigo-100 group-hover:text-indigo-600"
330
+ )}>
 
 
 
 
331
  {index + 1}
332
  </span>
333
+ <div className={cn(
334
+ "w-0.5 h-full min-h-[20px] rounded-full",
335
+ index === stages.length - 1 ? "bg-transparent" : "bg-slate-200"
336
+ )} />
337
  </div>
338
+
339
+ <div className="flex-1 min-w-0">
340
+ <div className="flex items-center justify-between mb-1">
341
+ <h3 className={cn(
342
+ "font-bold text-sm truncate pr-2",
343
+ selectedStage?.id === stage.id ? "text-indigo-900" : "text-slate-900"
344
+ )}>
345
+ {stage.name}
346
+ </h3>
347
+ <ChevronRight className={cn(
348
+ "w-4 h-4 flex-shrink-0 transition-transform",
349
+ selectedStage?.id === stage.id ? "text-indigo-500 rotate-90" : "text-slate-300"
350
+ )} />
351
  </div>
 
 
352
 
353
+ {stage.exit_criteria.length > 0 && (
354
+ <div className="flex items-center gap-1.5 mb-2">
355
+ <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
356
+ <span className="text-xs font-medium text-emerald-600">
357
+ {stage.exit_criteria.length} критериев
358
+ </span>
359
+ </div>
360
+ )}
361
+
362
+ <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
363
+ <button
364
+ onClick={(e) => {
365
+ e.stopPropagation()
366
+ handleMoveUp(index)
367
+ }}
368
+ disabled={index === 0}
369
+ className="p-1 rounded hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed text-slate-400 hover:text-indigo-600"
370
+ >
371
+ <ArrowUp className="w-3.5 h-3.5" />
372
+ </button>
373
+ <button
374
+ onClick={(e) => {
375
+ e.stopPropagation()
376
+ handleMoveDown(index)
377
+ }}
378
+ disabled={index === stages.length - 1}
379
+ className="p-1 rounded hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed text-slate-400 hover:text-indigo-600"
380
+ >
381
+ <ArrowDown className="w-3.5 h-3.5" />
382
+ </button>
383
+ </div>
384
+ </div>
385
  </div>
386
+ </motion.div>
387
+ ))}
388
+ </AnimatePresence>
389
 
390
  {stages.length === 0 && (
391
+ <div className="text-center py-12 px-4">
392
+ <div className="w-12 h-12 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-3">
393
+ <Target className="w-6 h-6 text-slate-300" />
394
  </div>
395
+ <h3 className="font-bold text-slate-900 text-sm mb-1">Нет этапов</h3>
396
+ <p className="text-xs text-slate-500 mb-4">Создайте первый этап воронки</p>
397
  <button
398
  onClick={handleAddStage}
399
+ className="text-sm text-indigo-600 font-medium hover:underline"
400
  >
401
  Создать этап
402
  </button>
 
404
  )}
405
  </div>
406
  </div>
407
+ </motion.div>
408
 
409
  {/* Right: Stage Editor */}
410
+ <motion.div
411
+ initial={{ opacity: 0, x: 20 }}
412
+ animate={{ opacity: 1, x: 0 }}
413
+ transition={{ delay: 0.2 }}
414
+ className="lg:col-span-2"
415
+ >
416
+ <AnimatePresence mode="wait">
417
+ {selectedStage ? (
418
+ <motion.div
419
+ key={selectedStage.id}
420
+ initial={{ opacity: 0, y: 10 }}
421
+ animate={{ opacity: 1, y: 0 }}
422
+ exit={{ opacity: 0, y: -10 }}
423
+ className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden"
424
+ >
425
+ <div className="p-6 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
426
+ <div className="flex items-center gap-3">
427
+ <div className="p-2 bg-indigo-100 rounded-lg text-indigo-600">
428
+ <Edit3 className="w-5 h-5" />
429
+ </div>
430
+ <h2 className="text-lg font-bold text-slate-900">Редактирование этапа</h2>
431
  </div>
432
+ <button
433
+ onClick={() => handleDelete(selectedStage.id)}
434
+ className="flex items-center gap-2 text-sm text-red-600 hover:text-red-700 hover:bg-red-50 font-medium px-3 py-2 rounded-lg transition-all"
435
+ >
436
+ <Trash2 className="w-4 h-4" />
437
+ Удалить
438
+ </button>
439
  </div>
 
 
 
 
 
 
 
 
440
 
441
+ <div className="p-8 space-y-8">
442
+ {/* Stage Name */}
443
+ <div className="space-y-4">
444
+ <div>
445
+ <label className="block text-sm font-bold text-slate-700 mb-2">
446
+ Название этапа
447
+ </label>
448
+ <input
449
+ type="text"
450
+ value={formData.name}
451
+ onChange={(e) => setFormData({ ...formData, name: e.target.value })}
452
+ className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 font-semibold text-slate-900 transition-all outline-none"
453
+ placeholder="например: Квалификация"
454
+ />
455
+ </div>
456
 
457
+ <div>
458
+ <label className="block text-sm font-bold text-slate-700 mb-2">
459
+ Описание <span className="text-xs font-normal text-slate-400 ml-1">(опционально)</span>
460
+ </label>
461
+ <input
462
+ type="text"
463
+ value={formData.description}
464
+ onChange={(e) => setFormData({ ...formData, description: e.target.value })}
465
+ className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition-all outline-none"
466
+ placeholder="Краткое описание этого этапа"
467
+ />
468
+ </div>
469
+ </div>
 
470
 
471
+ {/* AI Goal */}
472
+ <div className="p-6 bg-indigo-50/50 rounded-2xl border border-indigo-100">
473
+ <label className="block text-sm font-bold text-indigo-900 mb-3 flex items-center gap-2">
474
+ <Sparkles className="w-4 h-4 text-indigo-600" />
475
+ Цель AI на этом этапе
476
+ </label>
477
+ <textarea
478
+ value={formData.ai_goal}
479
+ onChange={(e) => setFormData({ ...formData, ai_goal: e.target.value })}
480
+ rows={4}
481
+ className="w-full px-4 py-3 border border-indigo-200 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 bg-white transition-all outline-none resize-none"
482
+ placeholder="Пример: Узнайте бюджет клиента и сроки принятия решения..."
483
+ />
484
+ <div className="mt-3 flex items-start gap-2 text-xs text-indigo-600">
485
+ <AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
486
+ <p>
487
+ <strong>Совет:</strong> Будьте конкретны. Опишите, какую информацию AI должен получить от клиента, чтобы считать этап успешным.
488
+ </p>
489
+ </div>
490
  </div>
 
491
 
492
+ {/* Exit Criteria */}
493
+ <div>
494
+ <label className="block text-sm font-bold text-slate-900 mb-4 flex items-center gap-2">
495
+ <CheckCircle2 className="w-5 h-5 text-emerald-600" />
496
+ Критерии завершения
497
+ </label>
498
+
499
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
500
+ {customFields.map((field) => (
501
+ <label
502
+ key={field}
503
+ className={cn(
504
+ "flex items-center gap-3 p-3 rounded-xl border cursor-pointer transition-all select-none",
505
+ formData.exit_criteria.includes(field)
506
+ ? "border-emerald-500 bg-emerald-50 shadow-sm"
507
+ : "border-slate-200 hover:border-emerald-300 bg-white"
508
+ )}
509
+ >
510
+ <div className={cn(
511
+ "w-5 h-5 rounded border flex items-center justify-center transition-colors",
512
+ formData.exit_criteria.includes(field)
513
+ ? "bg-emerald-500 border-emerald-500"
514
+ : "bg-white border-slate-300"
515
+ )}>
516
+ {formData.exit_criteria.includes(field) && (
517
+ <CheckCircle2 className="w-3.5 h-3.5 text-white" />
518
+ )}
519
+ </div>
520
+ <input
521
+ type="checkbox"
522
+ checked={formData.exit_criteria.includes(field)}
523
+ onChange={() => toggleCriteria(field)}
524
+ className="hidden"
525
+ />
526
+ <span className={cn(
527
+ "text-sm font-medium",
528
+ formData.exit_criteria.includes(field) ? "text-emerald-900" : "text-slate-700"
529
+ )}>
530
+ {field}
531
+ </span>
532
+ </label>
533
+ ))}
534
+ </div>
535
 
536
+ {formData.exit_criteria.length === 0 && (
537
+ <div className="mt-4 p-4 bg-amber-50 border border-amber-100 rounded-xl flex items-start gap-3">
538
+ <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
539
+ <p className="text-sm text-amber-800">
540
+ <strong>Внимание:</strong> Не выбрано ни одного критерия. Этот этап будет считаться завершённым автоматически или вручную.
541
+ </p>
542
+ </div>
543
+ )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
544
  </div>
545
 
546
+ {/* Save Button */}
547
+ <div className="pt-6 border-t border-slate-100">
548
+ <button
549
+ onClick={handleSave}
550
+ disabled={saving}
551
+ className="w-full flex items-center justify-center gap-2 px-6 py-4 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl transition-all shadow-lg hover:shadow-indigo-500/25 disabled:opacity-50 disabled:cursor-not-allowed"
552
+ >
553
+ {saving ? (
554
+ <>
555
+ <Loader2 className="w-5 h-5 animate-spin" />
556
+ Сохранение...
557
+ </>
558
+ ) : (
559
+ <>
560
+ <Save className="w-5 h-5" />
561
+ Сохранить изменения
562
+ </>
563
+ )}
564
+ </button>
565
+ </div>
566
  </div>
567
+ </motion.div>
568
+ ) : (
569
+ <motion.div
570
+ initial={{ opacity: 0, scale: 0.95 }}
571
+ animate={{ opacity: 1, scale: 1 }}
572
+ className="bg-white rounded-2xl shadow-sm border border-slate-200 p-12 text-center h-full flex flex-col items-center justify-center min-h-[400px]"
573
+ >
574
+ <div className="w-20 h-20 bg-slate-50 rounded-full flex items-center justify-center mb-6">
575
+ <Target className="w-10 h-10 text-slate-300" />
 
 
576
  </div>
577
+ <h3 className="text-xl font-bold text-slate-900 mb-2">
578
+ Этап не выбран
579
+ </h3>
580
+ <p className="text-slate-500 max-w-xs mx-auto">
581
+ Выберите этап из списка слева, чтобы настроить его параметры и цели AI
582
+ </p>
583
+ </motion.div>
584
+ )}
585
+ </AnimatePresence>
586
+ </motion.div>
 
 
 
 
 
 
587
  </div>
588
  </div>
589
 
590
  {/* Template Modal */}
591
+ <AnimatePresence>
592
+ {showTemplateModal && (
593
+ <motion.div
594
+ initial={{ opacity: 0 }}
595
+ animate={{ opacity: 1 }}
596
+ exit={{ opacity: 0 }}
597
+ className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
598
+ >
599
+ <motion.div
600
+ initial={{ scale: 0.95, opacity: 0 }}
601
+ animate={{ scale: 1, opacity: 1 }}
602
+ exit={{ scale: 0.95, opacity: 0 }}
603
+ className="bg-white rounded-2xl shadow-2xl max-w-3xl w-full max-h-[85vh] overflow-hidden flex flex-col"
604
+ >
605
+ <div className="bg-indigo-600 px-6 py-5 flex items-center justify-between flex-shrink-0">
606
+ <div className="flex items-center gap-3">
607
+ <div className="p-2 bg-white/10 rounded-lg">
608
+ <FolderOpen className="w-6 h-6 text-white" />
609
+ </div>
610
+ <div>
611
+ <h2 className="text-xl font-bold text-white">Шаблоны воронок</h2>
612
+ <p className="text-indigo-200 text-sm">Выберите готовый сценарий</p>
613
+ </div>
614
  </div>
615
+ <button
616
+ onClick={() => setShowTemplateModal(false)}
617
+ className="p-2 hover:bg-white/10 rounded-lg transition-colors text-white/80 hover:text-white"
618
+ >
619
+ <X className="w-6 h-6" />
620
+ </button>
621
  </div>
 
 
 
 
 
 
 
622
 
623
+ <div className="p-6 overflow-y-auto custom-scrollbar">
624
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
625
+ {templates.map((template) => {
626
+ const Icon = TEMPLATE_ICONS[template.id] || Target
627
+ return (
628
+ <button
629
+ key={template.id}
630
+ onClick={() => handleLoadTemplate(template.id)}
631
+ className="group p-5 border border-slate-200 hover:border-indigo-500 rounded-2xl transition-all bg-white hover:bg-indigo-50/30 text-left hover:shadow-md"
632
+ >
633
+ <div className="flex items-start gap-4">
634
+ <div className="p-3 bg-indigo-50 group-hover:bg-indigo-100 rounded-xl transition-colors text-indigo-600">
635
+ <Icon className="w-8 h-8" />
636
+ </div>
637
+ <div className="flex-1">
638
+ <h3 className="font-bold text-lg text-slate-900 mb-1 group-hover:text-indigo-700 transition-colors">
639
+ {template.name}
640
+ </h3>
641
+ <p className="text-xs text-slate-500 group-hover:text-indigo-600 transition-colors font-medium">
642
+ Нажмите для загрузки
643
+ </p>
644
+ </div>
 
 
 
 
 
 
645
  </div>
646
+ </button>
647
+ )
648
+ })}
649
+ </div>
 
650
 
651
+ <div className="mt-6 p-4 bg-amber-50 border border-amber-100 rounded-xl flex items-start gap-3">
 
652
  <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
653
  <div>
654
  <p className="text-sm font-bold text-amber-900 mb-1">
 
660
  </div>
661
  </div>
662
  </div>
663
+ </motion.div>
664
+ </motion.div>
665
+ )}
666
+ </AnimatePresence>
667
  </div>
668
  )
669
  }
frontend/app/settings/team/page.tsx CHANGED
@@ -3,7 +3,9 @@
3
  import { useState, useEffect } from 'react'
4
  import { useAuth } from '@/contexts/AuthContext'
5
  import { useToast } from '@/contexts/ToastContext'
6
- import { Users, Plus, Trash2, Shield, Lock, Unlock, Loader2, Mail, User as UserIcon, AlertCircle, CheckCircle2 } from 'lucide-react'
 
 
7
 
8
  interface TeamMember {
9
  id: string
@@ -21,7 +23,7 @@ export default function TeamPage() {
21
  const [loading, setLoading] = useState(true)
22
  const [showAddModal, setShowAddModal] = useState(false)
23
  const [creating, setCreating] = useState(false)
24
-
25
  // Form state
26
  const [formData, setFormData] = useState({
27
  email: '',
@@ -54,7 +56,7 @@ export default function TeamPage() {
54
 
55
  const handleCreateManager = async (e: React.FormEvent) => {
56
  e.preventDefault()
57
-
58
  if (!formData.email || !formData.full_name || !formData.password) {
59
  toast.warning('Внимание', 'Заполните все поля')
60
  return
@@ -140,261 +142,300 @@ export default function TeamPage() {
140
 
141
  if (loading) {
142
  return (
143
- <div className="min-h-screen bg-gradient-to-br from-slate-50 via-indigo-50/30 to-purple-50/20 flex items-center justify-center">
144
- <div className="text-center">
145
- <div className="animate-spin rounded-full h-16 w-16 border-b-4 border-indigo-600 mx-auto mb-4"></div>
146
- <p className="text-lg font-semibold text-slate-700">Загрузка команды...</p>
147
- </div>
148
  </div>
149
  )
150
  }
151
 
152
  return (
153
- <div className="min-h-screen bg-gradient-to-br from-slate-50 via-indigo-50/30 to-purple-50/20">
154
- {/* Header */}
155
- <div className="bg-white border-b-2 border-indigo-100 shadow-sm">
156
- <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
157
- <div className="flex items-center justify-between">
158
- <div className="flex items-center gap-4">
159
- <div className="p-3 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-xl shadow-lg">
160
- <Users className="w-8 h-8 text-white" />
161
- </div>
162
- <div>
163
- <h1 className="text-3xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
164
- Управление Командой
165
- </h1>
166
- <p className="text-sm text-slate-600 mt-1">
167
- Добавляйте менеджеров для работы с чатами
168
- </p>
169
- </div>
170
- </div>
171
- <button
172
- onClick={() => setShowAddModal(true)}
173
- className="flex items-center gap-2 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-xl transition-all shadow-lg hover:shadow-xl"
174
- >
175
- <Plus className="w-5 h-5" />
176
- Добавить менеджера
177
- </button>
178
  </div>
179
- </div>
180
- </div>
 
 
 
 
 
 
181
 
182
- {/* Main Content */}
183
- <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
184
  {/* Info Card */}
185
- <div className="mb-6 p-4 bg-gradient-to-r from-indigo-50 to-purple-50 border-2 border-indigo-100 rounded-xl">
186
- <div className="flex items-start gap-3">
187
- <AlertCircle className="w-5 h-5 text-indigo-600 flex-shrink-0 mt-0.5" />
188
- <div className="text-sm text-indigo-900">
189
- <p className="font-bold mb-1">О ролях:</p>
190
- <ul className="list-disc list-inside space-y-1 text-indigo-800">
191
- <li><strong>Владелец</strong> - полный доступ ко всем функциям</li>
192
- <li><strong>Менеджер</strong> - доступ только к чатам (без настроек)</li>
193
- </ul>
 
 
 
 
 
 
 
 
 
 
 
194
  </div>
195
  </div>
196
- </div>
197
 
198
  {/* Team Members List */}
199
- <div className="bg-white rounded-2xl shadow-lg border-2 border-indigo-100">
200
- <div className="p-6 border-b-2 border-slate-100">
 
 
 
 
 
201
  <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
202
  <Users className="w-5 h-5 text-indigo-600" />
203
- Члены команды ({members.length})
204
  </h2>
 
 
 
205
  </div>
206
 
207
  <div className="p-6">
208
  {members.length === 0 ? (
209
  <div className="text-center py-16">
210
- <div className="w-16 h-16 bg-gradient-to-br from-slate-100 to-slate-200 rounded-2xl flex items-center justify-center mx-auto mb-4">
211
- <Users className="w-8 h-8 text-slate-400" />
212
  </div>
213
  <h3 className="font-bold text-slate-900 mb-2">Нет членов команды</h3>
214
- <p className="text-sm text-slate-500 mb-4">Добавьте первого менеджера для работы с чатами</p>
215
  <button
216
  onClick={() => setShowAddModal(true)}
217
- className="px-6 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold rounded-xl transition-all"
218
  >
219
  Добавить менеджера
220
  </button>
221
  </div>
222
  ) : (
223
- <div className="space-y-3">
224
- {members.map((member) => (
225
- <div
226
- key={member.id}
227
- className="border-2 border-slate-200 rounded-xl p-4 hover:shadow-lg hover:border-indigo-300 transition-all duration-200 bg-gradient-to-br from-white to-slate-50"
228
- >
229
- <div className="flex items-center justify-between">
230
- <div className="flex items-center gap-4 flex-1">
231
- {/* Avatar */}
232
- <div className={`w-12 h-12 rounded-full flex items-center justify-center ${
233
- member.role === 'OWNER' ? 'bg-indigo-100' : 'bg-slate-100'
234
- }`}>
235
- <UserIcon className={`w-6 h-6 ${
236
- member.role === 'OWNER' ? 'text-indigo-600' : 'text-slate-600'
237
- }`} />
238
- </div>
 
 
 
 
 
 
239
 
240
- {/* Info */}
241
- <div className="flex-1">
242
- <div className="flex items-center gap-2 mb-1">
243
- <h3 className="font-bold text-slate-900">{member.full_name || member.email}</h3>
244
- <span className={`px-2 py-0.5 rounded text-xs font-bold uppercase ${
245
- member.role === 'OWNER'
246
- ? 'bg-indigo-600 text-white'
247
- : 'bg-slate-600 text-white'
248
- }`}>
249
- {member.role === 'OWNER' ? 'Владелец' : 'Менеджер'}
250
- </span>
251
- {!member.is_active && (
252
- <span className="px-2 py-0.5 rounded text-xs font-bold bg-red-100 text-red-700">
253
- НЕАКТИВЕН
254
  </span>
255
- )}
256
- </div>
257
- <div className="flex items-center gap-2 text-sm text-slate-600">
258
- <Mail className="w-4 h-4" />
259
- {member.email}
 
 
 
 
 
 
 
 
 
 
 
260
  </div>
261
- <p className="text-xs text-slate-500 mt-1">
262
- Добавлен: {new Date(member.created_at).toLocaleDateString('ru-RU')}
263
- </p>
264
  </div>
265
- </div>
266
 
267
- {/* Actions */}
268
- {member.role !== 'OWNER' && member.id !== user?.id && (
269
- <div className="flex items-center gap-2">
270
- <button
271
- onClick={() => handleToggleStatus(member.id)}
272
- className={`p-2 rounded-lg transition-all ${
273
- member.is_active
274
- ? 'text-amber-600 hover:bg-amber-50'
275
- : 'text-emerald-600 hover:bg-emerald-50'
276
- }`}
277
- title={member.is_active ? 'Деактивировать' : 'Активировать'}
278
- >
279
- {member.is_active ? (
280
- <Lock className="w-5 h-5" />
281
- ) : (
282
- <Unlock className="w-5 h-5" />
283
- )}
284
- </button>
285
- <button
286
- onClick={() => handleDeleteManager(member.id, member.full_name || member.email)}
287
- className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-all"
288
- title="Удалить"
289
- >
290
- <Trash2 className="w-5 h-5" />
291
- </button>
292
- </div>
293
- )}
294
- </div>
295
- </div>
296
- ))}
 
 
297
  </div>
298
  )}
299
  </div>
300
- </div>
301
  </div>
302
 
303
  {/* Add Manager Modal */}
304
- {showAddModal && (
305
- <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
306
- <div className="bg-white rounded-2xl shadow-2xl max-w-md w-full">
307
- <div className="bg-gradient-to-r from-indigo-600 to-purple-600 px-6 py-5 rounded-t-2xl">
308
- <h2 className="text-2xl font-bold text-white">Добавить менеджера</h2>
309
- <p className="text-indigo-100 text-sm mt-1">Создайте нового члена команды</p>
310
- </div>
311
-
312
- <form onSubmit={handleCreateManager} className="p-6 space-y-4">
313
- <div>
314
- <label className="block text-sm font-bold text-slate-700 mb-2">
315
- Email
316
- </label>
317
- <input
318
- type="email"
319
- value={formData.email}
320
- onChange={(e) => setFormData({ ...formData, email: e.target.value })}
321
- placeholder="manager@company.com"
322
- className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
323
- required
324
- />
 
325
  </div>
326
 
327
- <div>
328
- <label className="block text-sm font-bold text-slate-700 mb-2">
329
- Полное имя
330
- </label>
331
- <input
332
- type="text"
333
- value={formData.full_name}
334
- onChange={(e) => setFormData({ ...formData, full_name: e.target.value })}
335
- placeholder="Иван Иванов"
336
- className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
337
- required
338
- />
339
- </div>
 
340
 
341
- <div>
342
- <label className="block text-sm font-bold text-slate-700 mb-2">
343
- Пароль (минимум 8 символов)
344
- </label>
345
- <input
346
- type="password"
347
- value={formData.password}
348
- onChange={(e) => setFormData({ ...formData, password: e.target.value })}
349
- placeholder="••••••••"
350
- className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
351
- required
352
- minLength={8}
353
- />
354
- </div>
355
 
356
- <div className="p-4 bg-amber-50 border-2 border-amber-200 rounded-xl">
357
- <div className="flex items-start gap-2">
358
- <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
359
- <p className="text-sm text-amber-800">
360
- Менеджер сможет войти используя указанный email и пароль. У него будет доступ <strong>только к чатам</strong>.
361
- </p>
 
 
 
 
 
 
 
362
  </div>
363
- </div>
364
 
365
- <div className="flex gap-3 pt-2">
366
- <button
367
- type="button"
368
- onClick={() => {
369
- setShowAddModal(false)
370
- setFormData({ email: '', full_name: '', password: '' })
371
- }}
372
- className="flex-1 px-6 py-3 border-2 border-slate-300 text-slate-700 hover:bg-slate-50 font-semibold rounded-xl transition-all"
373
- >
374
- Отмена
375
- </button>
376
- <button
377
- type="submit"
378
- disabled={creating}
379
- 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-xl transition-all shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
380
- >
381
- {creating ? (
382
- <>
383
- <Loader2 className="w-5 h-5 animate-spin" />
384
- Создание...
385
- </>
386
- ) : (
387
- <>
388
- <CheckCircle2 className="w-5 h-5" />
389
- Создать
390
- </>
391
- )}
392
- </button>
393
- </div>
394
- </form>
395
- </div>
396
- </div>
397
- )}
 
 
 
 
 
 
 
 
 
 
398
  </div>
399
  )
400
  }
 
3
  import { useState, useEffect } from 'react'
4
  import { useAuth } from '@/contexts/AuthContext'
5
  import { useToast } from '@/contexts/ToastContext'
6
+ import { Users, Plus, Trash2, Shield, Lock, Unlock, Loader2, Mail, User as UserIcon, AlertCircle, CheckCircle2, ShieldCheck } from 'lucide-react'
7
+ import { motion, AnimatePresence } from 'framer-motion'
8
+ import { cn } from '@/lib/utils'
9
 
10
  interface TeamMember {
11
  id: string
 
23
  const [loading, setLoading] = useState(true)
24
  const [showAddModal, setShowAddModal] = useState(false)
25
  const [creating, setCreating] = useState(false)
26
+
27
  // Form state
28
  const [formData, setFormData] = useState({
29
  email: '',
 
56
 
57
  const handleCreateManager = async (e: React.FormEvent) => {
58
  e.preventDefault()
59
+
60
  if (!formData.email || !formData.full_name || !formData.password) {
61
  toast.warning('Внимание', 'Заполните все поля')
62
  return
 
142
 
143
  if (loading) {
144
  return (
145
+ <div className="flex items-center justify-center min-h-screen bg-slate-50">
146
+ <Loader2 className="w-12 h-12 animate-spin text-indigo-600" />
 
 
 
147
  </div>
148
  )
149
  }
150
 
151
  return (
152
+ <div className="min-h-screen bg-slate-50/50 p-8">
153
+ <div className="max-w-5xl mx-auto">
154
+ {/* Header */}
155
+ <motion.div
156
+ initial={{ opacity: 0, y: -20 }}
157
+ animate={{ opacity: 1, y: 0 }}
158
+ className="flex items-center justify-between mb-8"
159
+ >
160
+ <div>
161
+ <h1 className="text-3xl font-bold text-slate-900 mb-2 tracking-tight flex items-center gap-3">
162
+ Управление Командой
163
+ </h1>
164
+ <p className="text-slate-600">
165
+ Добавляйте менеджеров для работы с чатами и управления клиентами
166
+ </p>
 
 
 
 
 
 
 
 
 
 
167
  </div>
168
+ <button
169
+ onClick={() => setShowAddModal(true)}
170
+ className="flex items-center gap-2 px-6 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl transition-all shadow-lg hover:shadow-indigo-500/25"
171
+ >
172
+ <Plus className="w-5 h-5" />
173
+ Добавить менеджера
174
+ </button>
175
+ </motion.div>
176
 
 
 
177
  {/* Info Card */}
178
+ <motion.div
179
+ initial={{ opacity: 0, y: 20 }}
180
+ animate={{ opacity: 1, y: 0 }}
181
+ transition={{ delay: 0.1 }}
182
+ className="mb-8 p-6 bg-white border border-indigo-100 rounded-2xl shadow-sm flex items-start gap-4"
183
+ >
184
+ <div className="p-3 bg-indigo-50 rounded-xl">
185
+ <ShieldCheck className="w-6 h-6 text-indigo-600" />
186
+ </div>
187
+ <div>
188
+ <h3 className="font-bold text-slate-900 mb-2">Роли и доступы</h3>
189
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
190
+ <div className="flex items-center gap-2 text-sm text-slate-600">
191
+ <span className="px-2 py-1 bg-indigo-100 text-indigo-700 rounded-md font-bold text-xs uppercase">Владелец</span>
192
+ Полный доступ ко всем настройкам и биллингу
193
+ </div>
194
+ <div className="flex items-center gap-2 text-sm text-slate-600">
195
+ <span className="px-2 py-1 bg-slate-100 text-slate-700 rounded-md font-bold text-xs uppercase">Менеджер</span>
196
+ Доступ только к чатам и CRM (без настроек)
197
+ </div>
198
  </div>
199
  </div>
200
+ </motion.div>
201
 
202
  {/* Team Members List */}
203
+ <motion.div
204
+ initial={{ opacity: 0, y: 20 }}
205
+ animate={{ opacity: 1, y: 0 }}
206
+ transition={{ delay: 0.2 }}
207
+ className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden"
208
+ >
209
+ <div className="p-6 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
210
  <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
211
  <Users className="w-5 h-5 text-indigo-600" />
212
+ Члены команды
213
  </h2>
214
+ <span className="text-xs font-bold bg-white border border-slate-200 px-2 py-1 rounded-md text-slate-600">
215
+ {members.length}
216
+ </span>
217
  </div>
218
 
219
  <div className="p-6">
220
  {members.length === 0 ? (
221
  <div className="text-center py-16">
222
+ <div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-4">
223
+ <Users className="w-8 h-8 text-slate-300" />
224
  </div>
225
  <h3 className="font-bold text-slate-900 mb-2">Нет членов команды</h3>
226
+ <p className="text-sm text-slate-500 mb-6">Добавьте первого менеджера для работы с чатами</p>
227
  <button
228
  onClick={() => setShowAddModal(true)}
229
+ className="px-6 py-3 bg-indigo-50 text-indigo-600 font-semibold rounded-xl hover:bg-indigo-100 transition-colors"
230
  >
231
  Добавить менеджера
232
  </button>
233
  </div>
234
  ) : (
235
+ <div className="grid grid-cols-1 gap-4">
236
+ <AnimatePresence>
237
+ {members.map((member, idx) => (
238
+ <motion.div
239
+ key={member.id}
240
+ initial={{ opacity: 0, x: -20 }}
241
+ animate={{ opacity: 1, x: 0 }}
242
+ exit={{ opacity: 0, x: 20 }}
243
+ transition={{ delay: idx * 0.05 }}
244
+ className="group p-4 border border-slate-200 rounded-xl hover:border-indigo-300 hover:shadow-md transition-all bg-white"
245
+ >
246
+ <div className="flex items-center justify-between">
247
+ <div className="flex items-center gap-4">
248
+ {/* Avatar */}
249
+ <div className={cn(
250
+ "w-12 h-12 rounded-full flex items-center justify-center text-lg font-bold transition-colors",
251
+ member.role === 'OWNER'
252
+ ? "bg-indigo-100 text-indigo-600"
253
+ : "bg-slate-100 text-slate-600"
254
+ )}>
255
+ {member.full_name ? member.full_name[0].toUpperCase() : <UserIcon className="w-6 h-6" />}
256
+ </div>
257
 
258
+ {/* Info */}
259
+ <div>
260
+ <div className="flex items-center gap-2 mb-1">
261
+ <h3 className="font-bold text-slate-900">{member.full_name || 'Без имени'}</h3>
262
+ <span className={cn(
263
+ "px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide",
264
+ member.role === 'OWNER'
265
+ ? "bg-indigo-50 text-indigo-700 border border-indigo-100"
266
+ : "bg-slate-50 text-slate-600 border border-slate-100"
267
+ )}>
268
+ {member.role === 'OWNER' ? 'Владелец' : 'Менеджер'}
 
 
 
269
  </span>
270
+ {!member.is_active && (
271
+ <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-red-50 text-red-600 border border-red-100 uppercase tracking-wide">
272
+ Отключен
273
+ </span>
274
+ )}
275
+ </div>
276
+ <div className="flex items-center gap-4 text-sm text-slate-500">
277
+ <span className="flex items-center gap-1.5">
278
+ <Mail className="w-3.5 h-3.5" />
279
+ {member.email}
280
+ </span>
281
+ <span className="text-slate-300">•</span>
282
+ <span className="text-xs">
283
+ Добавлен {new Date(member.created_at).toLocaleDateString('ru-RU')}
284
+ </span>
285
+ </div>
286
  </div>
 
 
 
287
  </div>
 
288
 
289
+ {/* Actions */}
290
+ {member.role !== 'OWNER' && member.id !== user?.id && (
291
+ <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
292
+ <button
293
+ onClick={() => handleToggleStatus(member.id)}
294
+ className={cn(
295
+ "p-2 rounded-lg transition-all",
296
+ member.is_active
297
+ ? "text-slate-400 hover:text-amber-600 hover:bg-amber-50"
298
+ : "text-slate-400 hover:text-emerald-600 hover:bg-emerald-50"
299
+ )}
300
+ title={member.is_active ? 'Деактивировать' : 'Активировать'}
301
+ >
302
+ {member.is_active ? (
303
+ <Lock className="w-5 h-5" />
304
+ ) : (
305
+ <Unlock className="w-5 h-5" />
306
+ )}
307
+ </button>
308
+ <button
309
+ onClick={() => handleDeleteManager(member.id, member.full_name || member.email)}
310
+ className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-all"
311
+ title="Удалить"
312
+ >
313
+ <Trash2 className="w-5 h-5" />
314
+ </button>
315
+ </div>
316
+ )}
317
+ </div>
318
+ </motion.div>
319
+ ))}
320
+ </AnimatePresence>
321
  </div>
322
  )}
323
  </div>
324
+ </motion.div>
325
  </div>
326
 
327
  {/* Add Manager Modal */}
328
+ <AnimatePresence>
329
+ {showAddModal && (
330
+ <motion.div
331
+ initial={{ opacity: 0 }}
332
+ animate={{ opacity: 1 }}
333
+ exit={{ opacity: 0 }}
334
+ className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
335
+ >
336
+ <motion.div
337
+ initial={{ scale: 0.95, opacity: 0 }}
338
+ animate={{ scale: 1, opacity: 1 }}
339
+ exit={{ scale: 0.95, opacity: 0 }}
340
+ className="bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden"
341
+ >
342
+ <div className="bg-slate-50 px-6 py-5 border-b border-slate-100 flex items-center justify-between">
343
+ <div>
344
+ <h2 className="text-xl font-bold text-slate-900">Добавить менеджера</h2>
345
+ <p className="text-slate-500 text-sm mt-1">Создайте нового члена команды</p>
346
+ </div>
347
+ <div className="p-2 bg-indigo-100 rounded-full">
348
+ <UserIcon className="w-6 h-6 text-indigo-600" />
349
+ </div>
350
  </div>
351
 
352
+ <form onSubmit={handleCreateManager} className="p-6 space-y-4">
353
+ <div>
354
+ <label className="block text-sm font-bold text-slate-700 mb-2">
355
+ Email
356
+ </label>
357
+ <input
358
+ type="email"
359
+ value={formData.email}
360
+ onChange={(e) => setFormData({ ...formData, email: e.target.value })}
361
+ placeholder="manager@company.com"
362
+ className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition-all outline-none"
363
+ required
364
+ />
365
+ </div>
366
 
367
+ <div>
368
+ <label className="block text-sm font-bold text-slate-700 mb-2">
369
+ Полное имя
370
+ </label>
371
+ <input
372
+ type="text"
373
+ value={formData.full_name}
374
+ onChange={(e) => setFormData({ ...formData, full_name: e.target.value })}
375
+ placeholder="Иван Иванов"
376
+ className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition-all outline-none"
377
+ required
378
+ />
379
+ </div>
 
380
 
381
+ <div>
382
+ <label className="block text-sm font-bold text-slate-700 mb-2">
383
+ Пароль (минимум 8 символов)
384
+ </label>
385
+ <input
386
+ type="password"
387
+ value={formData.password}
388
+ onChange={(e) => setFormData({ ...formData, password: e.target.value })}
389
+ placeholder="••••••••"
390
+ className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition-all outline-none"
391
+ required
392
+ minLength={8}
393
+ />
394
  </div>
 
395
 
396
+ <div className="p-4 bg-amber-50 border border-amber-100 rounded-xl">
397
+ <div className="flex items-start gap-3">
398
+ <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
399
+ <p className="text-sm text-amber-800 leading-relaxed">
400
+ Менеджер сможет войти используя указанный email и пароль. У него будет доступ <strong>только к чатам</strong>.
401
+ </p>
402
+ </div>
403
+ </div>
404
+
405
+ <div className="flex gap-3 pt-4">
406
+ <button
407
+ type="button"
408
+ onClick={() => {
409
+ setShowAddModal(false)
410
+ setFormData({ email: '', full_name: '', password: '' })
411
+ }}
412
+ className="flex-1 px-6 py-3 border border-slate-200 text-slate-700 hover:bg-slate-50 font-semibold rounded-xl transition-all"
413
+ >
414
+ Отмена
415
+ </button>
416
+ <button
417
+ type="submit"
418
+ disabled={creating}
419
+ className="flex-1 px-6 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl transition-all shadow-lg hover:shadow-indigo-500/25 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
420
+ >
421
+ {creating ? (
422
+ <>
423
+ <Loader2 className="w-5 h-5 animate-spin" />
424
+ Создание...
425
+ </>
426
+ ) : (
427
+ <>
428
+ <CheckCircle2 className="w-5 h-5" />
429
+ Создать
430
+ </>
431
+ )}
432
+ </button>
433
+ </div>
434
+ </form>
435
+ </motion.div>
436
+ </motion.div>
437
+ )}
438
+ </AnimatePresence>
439
  </div>
440
  )
441
  }
frontend/components/Sidebar.tsx CHANGED
@@ -2,15 +2,17 @@
2
 
3
  import Link from 'next/link'
4
  import { usePathname } from 'next/navigation'
5
- import { LayoutDashboard, MessageSquare, Database, DollarSign, Send, LogOut, Brain, Target, Plug, Zap, Users } from 'lucide-react'
6
  import { useAuth } from '@/contexts/AuthContext'
 
 
7
 
8
  export function Sidebar() {
9
  const pathname = usePathname()
10
  const { user, logout, isLoading } = useAuth()
11
 
12
  // Don't show sidebar on auth pages
13
- if (pathname === '/login' || pathname === '/register') {
14
  return null
15
  }
16
 
@@ -44,190 +46,288 @@ export function Sidebar() {
44
  return colors[index]
45
  }
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  return (
48
- <aside className="w-64 bg-slate-900 border-r border-slate-800 flex flex-col font-['Inter']">
 
 
 
 
 
 
 
 
 
 
 
49
  {/* Logo Section */}
50
- <div className="p-6 border-b border-slate-800">
51
- <div className="flex items-center gap-3">
52
- <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center">
53
- <span className="text-white font-bold text-sm">MF</span>
 
 
 
54
  </div>
55
  <div>
56
- <h1 className="text-base font-bold text-white">
57
  MicroFunnel
58
  </h1>
59
- <p className="text-xs text-slate-500 font-medium">AI Sales Platform</p>
60
  </div>
61
- </div>
62
  </div>
63
 
64
  {/* Loading State - Skeleton Loader */}
65
  {isLoading ? (
66
- <nav className="flex-1 overflow-y-auto p-4 space-y-6">
67
- <div>
68
- <div className="h-3 w-20 bg-slate-800 rounded mb-3 animate-pulse" />
69
- <div className="space-y-2">
70
- <div className="h-9 bg-slate-800 rounded-lg animate-pulse" />
71
- <div className="h-9 bg-slate-800 rounded-lg animate-pulse" />
72
- </div>
73
- </div>
74
- <div>
75
- <div className="h-3 w-24 bg-slate-800 rounded mb-3 animate-pulse" />
76
- <div className="space-y-2">
77
- <div className="h-9 bg-slate-800 rounded-lg animate-pulse" />
78
- <div className="h-9 bg-slate-800 rounded-lg animate-pulse" />
79
  </div>
80
- </div>
81
  </nav>
82
  ) : (
83
- <nav className="flex-1 overflow-y-auto p-4 space-y-6">
84
- {/* WORKSPACE Group */}
85
- <div>
86
- <div className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2 px-3">
87
- Рабочее пространство
88
- </div>
89
- <div className="space-y-1">
90
- {user?.role === 'OWNER' && (
91
- <Link
92
- href="/dashboard"
93
- className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
94
- isActive('/dashboard')
95
- ? 'bg-indigo-600 text-white'
96
- : 'text-slate-400 hover:text-white hover:bg-white/10'
97
- }`}
98
- >
99
- <LayoutDashboard className="w-4 h-4" />
100
- Дашборд
101
- </Link>
102
- )}
103
- <Link
104
- href="/chats"
105
- className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
106
- isActive('/chats')
107
- ? 'bg-indigo-600 text-white'
108
- : 'text-slate-400 hover:text-white hover:bg-white/10'
109
- }`}
110
- >
111
- <MessageSquare className="w-4 h-4" />
112
- Чаты
113
- </Link>
114
- </div>
115
- </div>
116
-
117
- {/* INTELLIGENCE Group - ТОЛЬКО ДЛЯ OWNER */}
118
- {user?.role === 'OWNER' && (
119
- <div>
120
- <div className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2 px-3">
121
- Интеллект
122
  </div>
123
  <div className="space-y-1">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  <Link
125
- href="/knowledge"
126
- className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
127
- isActive('/knowledge')
128
- ? 'bg-indigo-600 text-white'
129
- : 'text-slate-400 hover:text-white hover:bg-white/10'
130
- }`}
 
131
  >
132
- <Database className="w-4 h-4" />
133
- База Знаний
134
- </Link>
135
- <Link
136
- href="/settings/brain"
137
- className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
138
- isActive('/settings/brain')
139
- ? 'bg-indigo-600 text-white'
140
- : 'text-slate-400 hover:text-white hover:bg-white/10'
141
- }`}
142
- >
143
- <Brain className="w-4 h-4" />
144
- AI Brain
145
- </Link>
146
- <Link
147
- href="/settings/playbook"
148
- className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
149
- isActive('/settings/playbook')
150
- ? 'bg-indigo-600 text-white'
151
- : 'text-slate-400 hover:text-white hover:bg-white/10'
152
- }`}
153
- >
154
- <Zap className="w-4 h-4" />
155
- Воронка
156
  </Link>
157
  </div>
158
- </div>
159
- )}
160
 
161
- {/* CONNECTIONS Group */}
162
- {user?.role === 'OWNER' && (
163
- <div>
164
- <div className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2 px-3">
165
- Подключения
166
- </div>
167
- <div className="space-y-1">
168
- <Link
169
- href="/channels"
170
- className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
171
- isActive('/channels')
172
- ? 'bg-indigo-600 text-white'
173
- : 'text-slate-400 hover:text-white hover:bg-white/10'
174
- }`}
175
- >
176
- <Send className="w-4 h-4" />
177
- Каналы
178
- </Link>
179
- <Link
180
- href="/settings/crm"
181
- className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
182
- isActive('/settings/crm')
183
- ? 'bg-indigo-600 text-white'
184
- : 'text-slate-400 hover:text-white hover:bg-white/10'
185
- }`}
186
- >
187
- <Plug className="w-4 h-4" />
188
- CRM Интеграция
189
- </Link>
190
- </div>
191
- </div>
192
- )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
- {/* SETTINGS Group - ТОЛЬКО ДЛЯ OWNER */}
195
- {user?.role === 'OWNER' && (
196
- <div>
197
- <div className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2 px-3">
198
- Настройки
199
- </div>
200
- <div className="space-y-1">
201
- <Link
202
- href="/settings/team"
203
- className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
204
- isActive('/settings/team')
205
- ? 'bg-indigo-600 text-white'
206
- : 'text-slate-400 hover:text-white hover:bg-white/10'
207
- }`}
208
- >
209
- <Users className="w-4 h-4" />
210
- Команда
211
- </Link>
212
- </div>
213
- </div>
214
- )}
215
- </nav>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  )}
217
 
218
  {/* Bottom Section */}
219
- <div className="mt-auto border-t border-slate-800">
220
  {/* Partner Program Link */}
221
  {user?.role === 'OWNER' && (
222
- <div className="p-4 border-b border-slate-800">
223
  <Link
224
- href="/partners"
225
- className="flex items-center gap-3 px-3 py-2.5 rounded-lg bg-gradient-to-r from-amber-600 to-orange-600 hover:from-amber-500 hover:to-orange-500 text-white transition-all duration-200 shadow-lg shadow-amber-900/30 font-medium text-sm"
226
  >
227
- <DollarSign className="w-4 h-4" />
228
- <span className="bg-gradient-to-r from-white to-amber-100 bg-clip-text text-transparent font-bold">
229
- Партнеры
 
230
  </span>
 
231
  </Link>
232
  </div>
233
  )}
@@ -235,36 +335,39 @@ export function Sidebar() {
235
  {/* User Profile Card or Sign In Fallback */}
236
  {user ? (
237
  <div className="p-4">
238
- <div className="flex items-center gap-3 px-3 py-2 rounded-lg bg-slate-800/50">
239
  {/* Avatar with Initials */}
240
- <div className={`w-9 h-9 rounded-full flex items-center justify-center text-white font-bold text-sm ${getAvatarColor(user.email)}`}>
 
 
 
241
  {getInitials(user.full_name, user.email)}
242
  </div>
243
-
244
  {/* User Info */}
245
  <div className="flex-1 min-w-0">
246
- <p className="text-sm font-medium text-white truncate">
247
  {user.full_name || user.email}
248
  </p>
249
  <div className="flex items-center gap-1.5">
250
- <span className={`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase ${
251
- user.role === 'OWNER'
252
- ? 'bg-indigo-600 text-white'
253
- : 'bg-slate-600 text-slate-200'
254
- }`}>
 
255
  {user.role === 'OWNER' ? 'Владелец' : 'Менеджер'}
256
  </span>
257
- <span className="text-xs text-slate-500 truncate">• {user.tenant_name}</span>
258
  </div>
259
  </div>
260
-
261
  {/* Logout Button */}
262
  <button
263
  onClick={logout}
264
- className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 transition-all duration-200"
265
  title="Выйти"
266
  >
267
- <LogOut className="w-4 h-4" />
268
  </button>
269
  </div>
270
  </div>
@@ -273,15 +376,15 @@ export function Sidebar() {
273
  <div className="p-4">
274
  <Link
275
  href="/login"
276
- className="flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white transition-all duration-200 font-medium text-sm"
277
  >
278
- <LogOut className="w-4 h-4" />
279
- Войти
280
  </Link>
281
  </div>
282
  )
283
  )}
284
  </div>
285
- </aside>
286
  )
287
  }
 
2
 
3
  import Link from 'next/link'
4
  import { usePathname } from 'next/navigation'
5
+ import { LayoutDashboard, MessageSquare, Database, DollarSign, Send, LogOut, Brain, Target, Plug, Zap, Users, ChevronRight, Sparkles, Command } from 'lucide-react'
6
  import { useAuth } from '@/contexts/AuthContext'
7
+ import { motion, AnimatePresence } from 'framer-motion'
8
+ import { cn } from '@/lib/utils'
9
 
10
  export function Sidebar() {
11
  const pathname = usePathname()
12
  const { user, logout, isLoading } = useAuth()
13
 
14
  // Don't show sidebar on auth pages
15
+ if (pathname === '/login' || pathname === '/register' || pathname === '/') {
16
  return null
17
  }
18
 
 
46
  return colors[index]
47
  }
48
 
49
+ const sidebarVariants = {
50
+ hidden: { x: -20, opacity: 0 },
51
+ visible: {
52
+ x: 0,
53
+ opacity: 1,
54
+ transition: {
55
+ duration: 0.4,
56
+ staggerChildren: 0.05
57
+ }
58
+ }
59
+ }
60
+
61
+ const itemVariants = {
62
+ hidden: { x: -10, opacity: 0 },
63
+ visible: { x: 0, opacity: 1 }
64
+ }
65
+
66
  return (
67
+ <motion.aside
68
+ initial="hidden"
69
+ animate="visible"
70
+ variants={sidebarVariants}
71
+ className="w-72 bg-[#0F172A] border-r border-slate-800 flex flex-col font-['Inter'] relative overflow-hidden shrink-0 h-screen sticky top-0"
72
+ >
73
+ {/* Background Glow Effect */}
74
+ <div className="absolute top-0 left-0 w-full h-full overflow-hidden pointer-events-none z-0">
75
+ <div className="absolute -top-[20%] -left-[20%] w-[140%] h-[50%] bg-indigo-900/20 blur-[100px] rounded-full animate-pulse-slow"></div>
76
+ <div className="absolute bottom-0 right-0 w-[80%] h-[40%] bg-purple-900/20 blur-[80px] rounded-full animate-pulse-slow delay-1000"></div>
77
+ </div>
78
+
79
  {/* Logo Section */}
80
+ <div className="p-6 border-b border-slate-800/50 relative z-10">
81
+ <Link href="/dashboard" className="flex items-center gap-3 group">
82
+ <div className="relative">
83
+ <div className="absolute inset-0 bg-indigo-500 blur-lg opacity-40 group-hover:opacity-60 transition-opacity" />
84
+ <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center shadow-lg shadow-indigo-500/20 relative z-10 group-hover:scale-105 transition-transform duration-300">
85
+ <Sparkles className="w-5 h-5 text-white" />
86
+ </div>
87
  </div>
88
  <div>
89
+ <h1 className="text-lg font-bold text-white tracking-tight group-hover:text-indigo-200 transition-colors">
90
  MicroFunnel
91
  </h1>
92
+ <p className="text-[10px] text-slate-400 font-medium uppercase tracking-wider">AI Sales Platform</p>
93
  </div>
94
+ </Link>
95
  </div>
96
 
97
  {/* Loading State - Skeleton Loader */}
98
  {isLoading ? (
99
+ <nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10">
100
+ {[1, 2, 3].map((i) => (
101
+ <div key={i}>
102
+ <div className="h-3 w-20 bg-slate-800/50 rounded mb-3 animate-pulse" />
103
+ <div className="space-y-2">
104
+ <div className="h-10 bg-slate-800/50 rounded-xl animate-pulse" />
105
+ <div className="h-10 bg-slate-800/50 rounded-xl animate-pulse" />
106
+ </div>
 
 
 
 
 
107
  </div>
108
+ ))}
109
  </nav>
110
  ) : (
111
+ <nav className="flex-1 overflow-y-auto p-4 space-y-8 relative z-10 scrollbar-thin scrollbar-thumb-slate-700 scrollbar-track-transparent">
112
+ {/* WORKSPACE Group */}
113
+ <motion.div variants={itemVariants}>
114
+ <div className="text-[11px] font-bold text-slate-500 uppercase tracking-widest mb-3 px-3 flex items-center gap-2">
115
+ <Command className="w-3 h-3" />
116
+ Рабочее пространство
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  </div>
118
  <div className="space-y-1">
119
+ {user?.role === 'OWNER' && (
120
+ <Link
121
+ href="/dashboard"
122
+ className={cn(
123
+ "group flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-200 font-medium text-sm border border-transparent relative overflow-hidden",
124
+ isActive('/dashboard')
125
+ ? "bg-indigo-600/10 text-indigo-400 border-indigo-500/20 shadow-sm"
126
+ : "text-slate-400 hover:text-white hover:bg-slate-800/50"
127
+ )}
128
+ >
129
+ {isActive('/dashboard') && (
130
+ <motion.div
131
+ layoutId="activeTab"
132
+ className="absolute inset-0 bg-indigo-600/10 rounded-xl"
133
+ transition={{ type: "spring", bounce: 0.2, duration: 0.6 }}
134
+ />
135
+ )}
136
+ <LayoutDashboard className={cn("w-5 h-5 transition-colors relative z-10", isActive('/dashboard') ? "text-indigo-400" : "text-slate-500 group-hover:text-white")} />
137
+ <span className="flex-1 relative z-10">Дашборд</span>
138
+ {isActive('/dashboard') && <div className="w-1.5 h-1.5 rounded-full bg-indigo-400 shadow-[0_0_8px_rgba(129,140,248,0.5)] relative z-10"></div>}
139
+ </Link>
140
+ )}
141
  <Link
142
+ href="/chats"
143
+ className={cn(
144
+ "group flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-200 font-medium text-sm border border-transparent relative overflow-hidden",
145
+ isActive('/chats')
146
+ ? "bg-indigo-600/10 text-indigo-400 border-indigo-500/20 shadow-sm"
147
+ : "text-slate-400 hover:text-white hover:bg-slate-800/50"
148
+ )}
149
  >
150
+ {isActive('/chats') && (
151
+ <motion.div
152
+ layoutId="activeTab"
153
+ className="absolute inset-0 bg-indigo-600/10 rounded-xl"
154
+ transition={{ type: "spring", bounce: 0.2, duration: 0.6 }}
155
+ />
156
+ )}
157
+ <MessageSquare className={cn("w-5 h-5 transition-colors relative z-10", isActive('/chats') ? "text-indigo-400" : "text-slate-500 group-hover:text-white")} />
158
+ <span className="flex-1 relative z-10">Чаты</span>
159
+ {isActive('/chats') && <div className="w-1.5 h-1.5 rounded-full bg-indigo-400 shadow-[0_0_8px_rgba(129,140,248,0.5)] relative z-10"></div>}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  </Link>
161
  </div>
162
+ </motion.div>
 
163
 
164
+ {/* INTELLIGENCE Group - ТОЛЬКО ДЛЯ OWNER */}
165
+ {user?.role === 'OWNER' && (
166
+ <motion.div variants={itemVariants}>
167
+ <div className="text-[11px] font-bold text-slate-500 uppercase tracking-widest mb-3 px-3 flex items-center gap-2">
168
+ <Brain className="w-3 h-3" />
169
+ Интеллект
170
+ </div>
171
+ <div className="space-y-1">
172
+ <Link
173
+ href="/knowledge"
174
+ className={cn(
175
+ "group flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-200 font-medium text-sm border border-transparent relative overflow-hidden",
176
+ isActive('/knowledge')
177
+ ? "bg-indigo-600/10 text-indigo-400 border-indigo-500/20 shadow-sm"
178
+ : "text-slate-400 hover:text-white hover:bg-slate-800/50"
179
+ )}
180
+ >
181
+ {isActive('/knowledge') && (
182
+ <motion.div
183
+ layoutId="activeTab"
184
+ className="absolute inset-0 bg-indigo-600/10 rounded-xl"
185
+ transition={{ type: "spring", bounce: 0.2, duration: 0.6 }}
186
+ />
187
+ )}
188
+ <Database className={cn("w-5 h-5 transition-colors relative z-10", isActive('/knowledge') ? "text-indigo-400" : "text-slate-500 group-hover:text-white")} />
189
+ <span className="flex-1 relative z-10">База Знаний</span>
190
+ </Link>
191
+ <Link
192
+ href="/settings/brain"
193
+ className={cn(
194
+ "group flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-200 font-medium text-sm border border-transparent relative overflow-hidden",
195
+ isActive('/settings/brain')
196
+ ? "bg-indigo-600/10 text-indigo-400 border-indigo-500/20 shadow-sm"
197
+ : "text-slate-400 hover:text-white hover:bg-slate-800/50"
198
+ )}
199
+ >
200
+ {isActive('/settings/brain') && (
201
+ <motion.div
202
+ layoutId="activeTab"
203
+ className="absolute inset-0 bg-indigo-600/10 rounded-xl"
204
+ transition={{ type: "spring", bounce: 0.2, duration: 0.6 }}
205
+ />
206
+ )}
207
+ <Brain className={cn("w-5 h-5 transition-colors relative z-10", isActive('/settings/brain') ? "text-indigo-400" : "text-slate-500 group-hover:text-white")} />
208
+ <span className="flex-1 relative z-10">AI Мозг</span>
209
+ </Link>
210
+ <Link
211
+ href="/settings/playbook"
212
+ className={cn(
213
+ "group flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-200 font-medium text-sm border border-transparent relative overflow-hidden",
214
+ isActive('/settings/playbook')
215
+ ? "bg-indigo-600/10 text-indigo-400 border-indigo-500/20 shadow-sm"
216
+ : "text-slate-400 hover:text-white hover:bg-slate-800/50"
217
+ )}
218
+ >
219
+ {isActive('/settings/playbook') && (
220
+ <motion.div
221
+ layoutId="activeTab"
222
+ className="absolute inset-0 bg-indigo-600/10 rounded-xl"
223
+ transition={{ type: "spring", bounce: 0.2, duration: 0.6 }}
224
+ />
225
+ )}
226
+ <Zap className={cn("w-5 h-5 transition-colors relative z-10", isActive('/settings/playbook') ? "text-indigo-400" : "text-slate-500 group-hover:text-white")} />
227
+ <span className="flex-1 relative z-10">Сценарии</span>
228
+ </Link>
229
+ </div>
230
+ </motion.div>
231
+ )}
232
 
233
+ {/* CONNECTIONS Group */}
234
+ {user?.role === 'OWNER' && (
235
+ <motion.div variants={itemVariants}>
236
+ <div className="text-[11px] font-bold text-slate-500 uppercase tracking-widest mb-3 px-3 flex items-center gap-2">
237
+ <Plug className="w-3 h-3" />
238
+ Подключения
239
+ </div>
240
+ <div className="space-y-1">
241
+ <Link
242
+ href="/channels"
243
+ className={cn(
244
+ "group flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-200 font-medium text-sm border border-transparent relative overflow-hidden",
245
+ isActive('/channels')
246
+ ? "bg-indigo-600/10 text-indigo-400 border-indigo-500/20 shadow-sm"
247
+ : "text-slate-400 hover:text-white hover:bg-slate-800/50"
248
+ )}
249
+ >
250
+ {isActive('/channels') && (
251
+ <motion.div
252
+ layoutId="activeTab"
253
+ className="absolute inset-0 bg-indigo-600/10 rounded-xl"
254
+ transition={{ type: "spring", bounce: 0.2, duration: 0.6 }}
255
+ />
256
+ )}
257
+ <Send className={cn("w-5 h-5 transition-colors relative z-10", isActive('/channels') ? "text-indigo-400" : "text-slate-500 group-hover:text-white")} />
258
+ <span className="flex-1 relative z-10">Каналы</span>
259
+ </Link>
260
+ <Link
261
+ href="/settings/crm"
262
+ className={cn(
263
+ "group flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-200 font-medium text-sm border border-transparent relative overflow-hidden",
264
+ isActive('/settings/crm')
265
+ ? "bg-indigo-600/10 text-indigo-400 border-indigo-500/20 shadow-sm"
266
+ : "text-slate-400 hover:text-white hover:bg-slate-800/50"
267
+ )}
268
+ >
269
+ {isActive('/settings/crm') && (
270
+ <motion.div
271
+ layoutId="activeTab"
272
+ className="absolute inset-0 bg-indigo-600/10 rounded-xl"
273
+ transition={{ type: "spring", bounce: 0.2, duration: 0.6 }}
274
+ />
275
+ )}
276
+ <Plug className={cn("w-5 h-5 transition-colors relative z-10", isActive('/settings/crm') ? "text-indigo-400" : "text-slate-500 group-hover:text-white")} />
277
+ <span className="flex-1 relative z-10">CRM Интеграция</span>
278
+ </Link>
279
+ </div>
280
+ </motion.div>
281
+ )}
282
+
283
+ {/* SETTINGS Group - ТОЛЬКО ДЛЯ OWNER */}
284
+ {user?.role === 'OWNER' && (
285
+ <motion.div variants={itemVariants}>
286
+ <div className="text-[11px] font-bold text-slate-500 uppercase tracking-widest mb-3 px-3 flex items-center gap-2">
287
+ <Users className="w-3 h-3" />
288
+ Настройки
289
+ </div>
290
+ <div className="space-y-1">
291
+ <Link
292
+ href="/settings/team"
293
+ className={cn(
294
+ "group flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-200 font-medium text-sm border border-transparent relative overflow-hidden",
295
+ isActive('/settings/team')
296
+ ? "bg-indigo-600/10 text-indigo-400 border-indigo-500/20 shadow-sm"
297
+ : "text-slate-400 hover:text-white hover:bg-slate-800/50"
298
+ )}
299
+ >
300
+ {isActive('/settings/team') && (
301
+ <motion.div
302
+ layoutId="activeTab"
303
+ className="absolute inset-0 bg-indigo-600/10 rounded-xl"
304
+ transition={{ type: "spring", bounce: 0.2, duration: 0.6 }}
305
+ />
306
+ )}
307
+ <Users className={cn("w-5 h-5 transition-colors relative z-10", isActive('/settings/team') ? "text-indigo-400" : "text-slate-500 group-hover:text-white")} />
308
+ <span className="flex-1 relative z-10">Команда</span>
309
+ </Link>
310
+ </div>
311
+ </motion.div>
312
+ )}
313
+ </nav>
314
  )}
315
 
316
  {/* Bottom Section */}
317
+ <div className="mt-auto border-t border-slate-800/50 relative z-10 bg-slate-900/50 backdrop-blur-sm">
318
  {/* Partner Program Link */}
319
  {user?.role === 'OWNER' && (
320
+ <div className="p-4 border-b border-slate-800/50">
321
  <Link
322
+ href="/settings/partner"
323
+ className="flex items-center gap-3 px-3 py-3 rounded-xl bg-gradient-to-r from-amber-600/90 to-orange-600/90 hover:from-amber-500 hover:to-orange-500 text-white transition-all duration-200 shadow-lg shadow-amber-900/20 font-medium text-sm group border border-white/10 relative overflow-hidden"
324
  >
325
+ <div className="absolute inset-0 bg-white/20 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700" />
326
+ <DollarSign className="w-5 h-5 text-amber-100" />
327
+ <span className="flex-1 bg-gradient-to-r from-white to-amber-100 bg-clip-text text-transparent font-bold">
328
+ Партнерская программа
329
  </span>
330
+ <ChevronRight className="w-4 h-4 text-amber-200/70 group-hover:translate-x-0.5 transition-transform" />
331
  </Link>
332
  </div>
333
  )}
 
335
  {/* User Profile Card or Sign In Fallback */}
336
  {user ? (
337
  <div className="p-4">
338
+ <div className="flex items-center gap-3 px-3 py-2.5 rounded-xl bg-slate-800/50 hover:bg-slate-800 transition-colors border border-slate-700/50 group">
339
  {/* Avatar with Initials */}
340
+ <div className={cn(
341
+ "w-10 h-10 rounded-full flex items-center justify-center text-white font-bold text-sm shadow-inner transition-transform group-hover:scale-105",
342
+ getAvatarColor(user.email)
343
+ )}>
344
  {getInitials(user.full_name, user.email)}
345
  </div>
346
+
347
  {/* User Info */}
348
  <div className="flex-1 min-w-0">
349
+ <p className="text-sm font-semibold text-white truncate group-hover:text-indigo-200 transition-colors">
350
  {user.full_name || user.email}
351
  </p>
352
  <div className="flex items-center gap-1.5">
353
+ <span className={cn(
354
+ "px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide",
355
+ user.role === 'OWNER'
356
+ ? "bg-indigo-500/20 text-indigo-300 border border-indigo-500/20"
357
+ : "bg-slate-600/30 text-slate-300 border border-slate-500/20"
358
+ )}>
359
  {user.role === 'OWNER' ? 'Владелец' : 'Менеджер'}
360
  </span>
 
361
  </div>
362
  </div>
363
+
364
  {/* Logout Button */}
365
  <button
366
  onClick={logout}
367
+ className="p-2 rounded-lg text-slate-400 hover:text-red-400 hover:bg-red-500/10 transition-all duration-200"
368
  title="Выйти"
369
  >
370
+ <LogOut className="w-5 h-5" />
371
  </button>
372
  </div>
373
  </div>
 
376
  <div className="p-4">
377
  <Link
378
  href="/login"
379
+ className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white transition-all duration-200 font-bold text-sm shadow-lg shadow-indigo-900/20"
380
  >
381
+ <LogOut className="w-5 h-5" />
382
+ Войти в систему
383
  </Link>
384
  </div>
385
  )
386
  )}
387
  </div>
388
+ </motion.aside>
389
  )
390
  }
frontend/lib/api.ts CHANGED
@@ -265,7 +265,9 @@ export const channelsApi = {
265
 
266
  // WhatsApp QR (Grey API)
267
  generateWhatsAppQR: async () => {
 
268
  const response = await api.post('/api/v1/channels/whatsapp/qr/generate')
 
269
  return response.data
270
  },
271
 
 
265
 
266
  // WhatsApp QR (Grey API)
267
  generateWhatsAppQR: async () => {
268
+ console.log('🔍 Sending WhatsApp QR request...')
269
  const response = await api.post('/api/v1/channels/whatsapp/qr/generate')
270
+ console.log('✅ WhatsApp QR response:', response.data)
271
  return response.data
272
  },
273