Spaces:
Running

axeronis commited on
Commit
5e04bce
·
1 Parent(s): 4f7187d

feat: Chat UI improvements and AI core enhancements

Browse files

- Added re-analyze button in ClientCard to manually trigger AI summary analysis
- AI toggle switch already exists in ChatWindow for enable/disable auto-reply
- Added funnel stage indicator showing current sales stage
- Fixed MissingGreenlet error in gemini_client.py using nest_asyncio
- Added LeadQualificationService and AutoSyncService for CRM integration
- Updated requirements.txt with nest_asyncio dependency

backend/app/services/auto_sync_service.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Auto CRM Sync Service
3
+
4
+ Automatically syncs qualified leads to CRM systems:
5
+ - Checks if lead meets CRM sync criteria
6
+ - Retrieves active CRM integrations
7
+ - Triggers sync for each integration
8
+ - Updates lead sync status
9
+ """
10
+
11
+ from typing import Dict, Any, Optional, List
12
+ from datetime import datetime, timedelta
13
+ from uuid import UUID
14
+ from sqlalchemy.ext.asyncio import AsyncSession
15
+ from sqlmodel import select
16
+
17
+ from app.models.lead import Lead, LeadHeat
18
+ from app.models.crm_integration import CRMIntegration, SyncStatus
19
+ from app.services.crm_sync import get_crm_sync_service
20
+ from app.core.logging import get_logger
21
+
22
+ logger = get_logger(__name__)
23
+
24
+
25
+ class AutoSyncService:
26
+ """Service for automatically syncing qualified leads to CRM."""
27
+
28
+ def __init__(self):
29
+ self.crm_sync_service = get_crm_sync_service()
30
+ self.min_sync_interval_minutes = 5 # Don't sync same lead more than once per 5 min
31
+
32
+ async def check_and_sync_lead(
33
+ self,
34
+ session: AsyncSession,
35
+ lead: Lead,
36
+ qualification_data: Optional[Dict[str, Any]] = None
37
+ ) -> Dict[str, Any]:
38
+ """
39
+ Check if lead should be synced and perform sync.
40
+
41
+ Args:
42
+ session: Database session
43
+ lead: Lead to potentially sync
44
+ qualification_data: Optional qualification analysis results
45
+
46
+ Returns:
47
+ Sync result summary
48
+ """
49
+
50
+ # Check basic sync criteria
51
+ if not self._should_attempt_sync(lead):
52
+ return {
53
+ "synced": False,
54
+ "reason": "Lead doesn't meet sync criteria",
55
+ "criteria_check": {
56
+ "heat_score": lead.heat_score,
57
+ "has_email": bool(lead.email),
58
+ "has_phone": bool(lead.phone)
59
+ }
60
+ }
61
+
62
+ # Check cooldown period
63
+ if lead.last_crm_sync_attempt:
64
+ time_since_last = datetime.utcnow() - lead.last_crm_sync_attempt
65
+ if time_since_last < timedelta(minutes=self.min_sync_interval_minutes):
66
+ return {
67
+ "synced": False,
68
+ "reason": "Sync cooldown period active",
69
+ "retry_after": self.min_sync_interval_minutes - int(time_since_last.total_seconds() / 60)
70
+ }
71
+
72
+ # Get active CRM integrations for tenant
73
+ integrations = await self._get_active_integrations(session, lead.tenant_id)
74
+
75
+ if not integrations:
76
+ logger.info(f"No active CRM integrations for tenant {lead.tenant_id}")
77
+ return {
78
+ "synced": False,
79
+ "reason": "No active CRM integrations configured"
80
+ }
81
+
82
+ # Update sync attempt timestamp
83
+ lead.last_crm_sync_attempt = datetime.utcnow()
84
+ lead.crm_sync_status = "syncing"
85
+ session.add(lead)
86
+ await session.commit()
87
+
88
+ # Sync to each integration
89
+ results = {}
90
+ any_success = False
91
+
92
+ for integration in integrations:
93
+ try:
94
+ result = await self.crm_sync_service.sync_lead_to_crm(
95
+ session=session,
96
+ lead=lead,
97
+ integration=integration,
98
+ force=False # Don't force if unchanged
99
+ )
100
+
101
+ results[integration.integration_name] = result
102
+
103
+ if result.get("success"):
104
+ any_success = True
105
+ logger.info(
106
+ f"✅ Synced lead {lead.id} to {integration.crm_type} "
107
+ f"(integration: {integration.integration_name})"
108
+ )
109
+ else:
110
+ logger.warning(
111
+ f"⚠️ Failed to sync lead {lead.id} to {integration.crm_type}: "
112
+ f"{result.get('error')}"
113
+ )
114
+
115
+ except Exception as e:
116
+ logger.error(f"❌ Error syncing to {integration.integration_name}: {e}", exc_info=True)
117
+ results[integration.integration_name] = {
118
+ "success": False,
119
+ "error": str(e)
120
+ }
121
+
122
+ # Update final sync status
123
+ if any_success:
124
+ lead.crm_sync_status = "synced"
125
+ lead.last_crm_synced_at = datetime.utcnow()
126
+ else:
127
+ lead.crm_sync_status = "failed"
128
+
129
+ session.add(lead)
130
+ await session.commit()
131
+
132
+ return {
133
+ "synced": any_success,
134
+ "total_integrations": len(integrations),
135
+ "successful_syncs": sum(1 for r in results.values() if r.get("success")),
136
+ "results": results
137
+ }
138
+
139
+ def _should_attempt_sync(self, lead: Lead) -> bool:
140
+ """Check if lead meets basic sync criteria."""
141
+
142
+ # Must be hot lead (score >= 70)
143
+ if lead.heat_score < 70:
144
+ return False
145
+
146
+ # Must have contact information
147
+ if not lead.email and not lead.phone:
148
+ return False
149
+
150
+ # Don't sync junk leads
151
+ if lead.heat_level == LeadHeat.JUNK:
152
+ return False
153
+
154
+ return True
155
+
156
+ async def _get_active_integrations(
157
+ self,
158
+ session: AsyncSession,
159
+ tenant_id: UUID
160
+ ) -> List[CRMIntegration]:
161
+ """Get all active CRM integrations for tenant."""
162
+
163
+ stmt = select(CRMIntegration).where(
164
+ CRMIntegration.tenant_id == tenant_id,
165
+ CRMIntegration.is_active == True,
166
+ CRMIntegration.status == SyncStatus.ACTIVE,
167
+ CRMIntegration.auto_sync == True # Must have auto-sync enabled
168
+ )
169
+
170
+ result = await session.execute(stmt)
171
+ integrations = list(result.scalars().all())
172
+
173
+ # Filter for integrations that sync to CRM (not from CRM)
174
+ return [
175
+ i for i in integrations
176
+ if i.sync_direction in ["to_crm", "bidirectional"]
177
+ ]
178
+
179
+ async def sync_all_qualified_leads(
180
+ self,
181
+ session: AsyncSession,
182
+ tenant_id: UUID,
183
+ limit: int = 50
184
+ ) -> Dict[str, Any]:
185
+ """
186
+ Batch sync all qualified leads that haven't been synced recently.
187
+ Useful for manual triggers or cron jobs.
188
+
189
+ Args:
190
+ session: Database session
191
+ tenant_id: Tenant to sync leads for
192
+ limit: Maximum number of leads to process
193
+
194
+ Returns:
195
+ Batch sync statistics
196
+ """
197
+
198
+ # Get qualified leads that need syncing
199
+ cutoff_time = datetime.utcnow() - timedelta(minutes=self.min_sync_interval_minutes)
200
+
201
+ stmt = select(Lead).where(
202
+ Lead.tenant_id == tenant_id,
203
+ Lead.heat_score >= 70,
204
+ Lead.crm_sync_status.in_(["pending", "failed", None])
205
+ ).where(
206
+ (Lead.last_crm_sync_attempt == None) |
207
+ (Lead.last_crm_sync_attempt < cutoff_time)
208
+ ).limit(limit)
209
+
210
+ result = await session.execute(stmt)
211
+ leads = list(result.scalars().all())
212
+
213
+ stats = {
214
+ "total_processed": len(leads),
215
+ "successful": 0,
216
+ "failed": 0,
217
+ "skipped": 0,
218
+ "errors": []
219
+ }
220
+
221
+ for lead in leads:
222
+ try:
223
+ result = await self.check_and_sync_lead(session, lead)
224
+
225
+ if result.get("synced"):
226
+ stats["successful"] += 1
227
+ elif result.get("reason"):
228
+ stats["skipped"] += 1
229
+ else:
230
+ stats["failed"] += 1
231
+
232
+ except Exception as e:
233
+ stats["failed"] += 1
234
+ stats["errors"].append({
235
+ "lead_id": str(lead.id),
236
+ "error": str(e)
237
+ })
238
+ logger.error(f"Error in batch sync for lead {lead.id}: {e}", exc_info=True)
239
+
240
+ return stats
241
+
242
+
243
+ # Singleton instance
244
+ _auto_sync_service: Optional[AutoSyncService] = None
245
+
246
+
247
+ def get_auto_sync_service() -> AutoSyncService:
248
+ """Get auto sync service singleton."""
249
+ global _auto_sync_service
250
+ if _auto_sync_service is None:
251
+ _auto_sync_service = AutoSyncService()
252
+ return _auto_sync_service
backend/app/services/gemini_client.py CHANGED
@@ -415,7 +415,14 @@ Respond with ONLY a number from 0 to 100."""
415
  )
416
  )
417
 
418
- response = await asyncio.to_thread(
 
 
 
 
 
 
 
419
  model_with_schema.generate_content,
420
  prompt
421
  )
 
415
  )
416
  )
417
 
418
+ # FIX: Use synchronous generate_content in async context properly
419
+ import nest_asyncio
420
+ nest_asyncio.apply() # Allow nested event loops
421
+
422
+ # Run in executor to avoid blocking
423
+ loop = asyncio.get_event_loop()
424
+ response = await loop.run_in_executor(
425
+ None, # Use default executor
426
  model_with_schema.generate_content,
427
  prompt
428
  )
backend/app/services/lead_qualification.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lead Qualification Service
3
+
4
+ Automatically qualifies leads based on conversation analysis:
5
+ - BANT scoring (Budget, Authority, Need, Timeline)
6
+ - Heat score calculation (0-100)
7
+ - Intent detection
8
+ - Psychotype analysis
9
+ """
10
+
11
+ from typing import List, Dict, Any, Optional
12
+ from pydantic import BaseModel
13
+ from datetime import datetime
14
+
15
+ from app.models.lead import Lead, LeadHeat, Psychotype, LeadStatus, Message
16
+
17
+
18
+ class BANTScore(BaseModel):
19
+ """BANT qualification scores."""
20
+ budget: int = 0 # 0-25
21
+ authority: int = 0 # 0-25
22
+ need: int = 0 # 0-25
23
+ timeline: int = 0 # 0-25
24
+ total: int = 0 # 0-100
25
+ confidence: float = 0.0 # 0-1
26
+
27
+
28
+ class QualificationResult(BaseModel):
29
+ """Result of lead qualification analysis."""
30
+ heat_score: int
31
+ heat_level: LeadHeat
32
+ bant: BANTScore
33
+ intent: str
34
+ psychotype: Psychotype
35
+ should_sync_to_crm: bool
36
+ extracted_fields: Dict[str, Any]
37
+ analysis_summary: str
38
+
39
+
40
+ class LeadQualificationService:
41
+ """Service for analyzing and qualifying leads."""
42
+
43
+ def __init__(self):
44
+ self.min_hot_score = 70
45
+ self.min_warm_score = 50
46
+ self.min_cold_score = 30
47
+
48
+ async def analyze_conversation(
49
+ self,
50
+ lead: Lead,
51
+ messages: List[Message],
52
+ ai_summary: Dict[str, Any]
53
+ ) -> QualificationResult:
54
+ """
55
+ Analyze conversation and qualify the lead.
56
+
57
+ Args:
58
+ lead: The lead to analyze
59
+ messages: Conversation messages
60
+ ai_summary: AI-generated summary with extracted info
61
+
62
+ Returns:
63
+ QualificationResult with scores and recommendations
64
+ """
65
+ # Extract BANT from AI summary
66
+ bant = self._extract_bant_from_summary(ai_summary, messages)
67
+
68
+ # Calculate heat score
69
+ heat_score = self.calculate_heat_score(bant, lead, ai_summary)
70
+ heat_level = self._calculate_heat_level(heat_score)
71
+
72
+ # Detect intent
73
+ intent = self._detect_intent(ai_summary, messages)
74
+
75
+ # Analyze psychotype
76
+ psychotype = self._analyze_psychotype(ai_summary, messages)
77
+
78
+ # Determine if should sync to CRM
79
+ should_sync = self._should_sync_to_crm(heat_score, lead, bant)
80
+
81
+ # Extract fields for CRM
82
+ extracted_fields = self._extract_crm_fields(ai_summary, lead)
83
+
84
+ # Generate analysis summary
85
+ analysis_summary = self._generate_analysis_summary(
86
+ bant, heat_score, intent, psychotype
87
+ )
88
+
89
+ return QualificationResult(
90
+ heat_score=heat_score,
91
+ heat_level=heat_level,
92
+ bant=bant,
93
+ intent=intent,
94
+ psychotype=psychotype,
95
+ should_sync_to_crm=should_sync,
96
+ extracted_fields=extracted_fields,
97
+ analysis_summary=analysis_summary
98
+ )
99
+
100
+ def _extract_bant_from_summary(
101
+ self,
102
+ ai_summary: Dict[str, Any],
103
+ messages: List[Message]
104
+ ) -> BANTScore:
105
+ """Extract BANT scores from AI summary."""
106
+
107
+ # Budget (0-25 points)
108
+ budget_score = 0
109
+ budget_text = ai_summary.get("budget", "").lower()
110
+
111
+ if "million" in budget_text or "млн" in budget_text:
112
+ budget_score = 25
113
+ elif any(word in budget_text for word in ["ready", "готов", "выделен"]):
114
+ budget_score = 20
115
+ elif any(word in budget_text for word in ["range", "диапазон", "approximate", "примерно"]):
116
+ budget_score = 15
117
+ elif any(word in budget_text for word in ["considering", "рассматриваю", "depends", "зависит"]):
118
+ budget_score = 10
119
+ elif any(word in budget_text for word in ["limited", "ограничен", "small", "небольшой"]):
120
+ budget_score = 5
121
+
122
+ # Authority (0-25 points)
123
+ authority_score = 0
124
+ authority_text = ai_summary.get("authority", "").lower()
125
+
126
+ if any(word in authority_text for word in ["owner", "ceo", "director", "владелец", "директор"]):
127
+ authority_score = 25
128
+ elif any(word in authority_text for word in ["head", "руководитель", "manager", "менеджер"]):
129
+ authority_score = 20
130
+ elif any(word in authority_text for word in ["team lead", "тимлид", "decision maker", "принимаю решения"]):
131
+ authority_score = 15
132
+ elif any(word in authority_text for word in ["influence", "влияние", "recommend", "рекомендую"]):
133
+ authority_score = 10
134
+ elif any(word in authority_text for word in ["employee", "сотрудник", "check with", "согласую"]):
135
+ authority_score = 5
136
+
137
+ # Need (0-25 points)
138
+ need_score = 0
139
+ need_text = ai_summary.get("need", "").lower()
140
+ pain_points = ai_summary.get("pain_points", "").lower()
141
+
142
+ urgency_keywords = ["urgent", "срочно", "critical", "критично", "losing", "теряем"]
143
+ moderate_keywords = ["need", "нужно", "want", "хочу", "improve", "улучшить"]
144
+
145
+ if any(word in need_text for word in urgency_keywords) or \
146
+ any(word in pain_points for word in urgency_keywords):
147
+ need_score = 25
148
+ elif "pain" in pain_points or "проблема" in pain_points:
149
+ need_score = 20
150
+ elif any(word in need_text for word in moderate_keywords):
151
+ need_score = 15
152
+ elif "nice to have" in need_text or "было бы неплохо" in need_text:
153
+ need_score = 10
154
+
155
+ # Timeline (0-25 points)
156
+ timeline_score = 0
157
+ timeline_text = ai_summary.get("timeline", "").lower()
158
+
159
+ if any(word in timeline_text for word in ["now", "immediately", "сейчас", "немедленно", "asap"]):
160
+ timeline_score = 25
161
+ elif any(word in timeline_text for word in ["week", "неделя", "days", "дней"]):
162
+ timeline_score = 20
163
+ elif any(word in timeline_text for word in ["month", "месяц", "quarter", "квартал"]):
164
+ timeline_score = 15
165
+ elif any(word in timeline_text for word in ["half year", "полгода", "year", "год"]):
166
+ timeline_score = 10
167
+ elif any(word in timeline_text for word in ["future", "будущем", "someday", "когда-нибудь"]):
168
+ timeline_score = 5
169
+
170
+ total = budget_score + authority_score + need_score + timeline_score
171
+
172
+ # Calculate confidence based on how much information we have
173
+ filled_fields = sum([
174
+ 1 if budget_score > 0 else 0,
175
+ 1 if authority_score > 0 else 0,
176
+ 1 if need_score > 0 else 0,
177
+ 1 if timeline_score > 0 else 0
178
+ ])
179
+ confidence = filled_fields / 4.0
180
+
181
+ return BANTScore(
182
+ budget=budget_score,
183
+ authority=authority_score,
184
+ need=need_score,
185
+ timeline=timeline_score,
186
+ total=total,
187
+ confidence=confidence
188
+ )
189
+
190
+ def calculate_heat_score(
191
+ self,
192
+ bant: BANTScore,
193
+ lead: Lead,
194
+ ai_summary: Dict[str, Any]
195
+ ) -> int:
196
+ """Calculate overall heat score (0-100)."""
197
+
198
+ # Base score from BANT
199
+ score = bant.total
200
+
201
+ # Bonus points for having contact info
202
+ if lead.email:
203
+ score += 5
204
+ if lead.phone:
205
+ score += 5
206
+
207
+ # Bonus for engagement
208
+ if ai_summary.get("objections_addressed"):
209
+ score += 5
210
+
211
+ # Reduce for negative indicators
212
+ if ai_summary.get("intent") in ["just_browsing", "competitor_research"]:
213
+ score -= 15
214
+
215
+ # Ensure 0-100 range
216
+ return max(0, min(100, score))
217
+
218
+ def _calculate_heat_level(self, heat_score: int) -> LeadHeat:
219
+ """Convert numerical score to heat level."""
220
+ if heat_score >= self.min_hot_score:
221
+ return LeadHeat.HOT
222
+ elif heat_score >= self.min_warm_score:
223
+ return LeadHeat.WARM
224
+ elif heat_score >= self.min_cold_score:
225
+ return LeadHeat.COLD
226
+ else:
227
+ return LeadHeat.JUNK
228
+
229
+ def _detect_intent(
230
+ self,
231
+ ai_summary: Dict[str, Any],
232
+ messages: List[Message]
233
+ ) -> str:
234
+ """Detect user intent from conversation."""
235
+ intent = ai_summary.get("intent", "unknown")
236
+
237
+ # Map AI summary intent to standard values
238
+ intent_mapping = {
239
+ "ready_to_buy": "ready_to_buy",
240
+ "готов_купить": "ready_to_buy",
241
+ "evaluating": "evaluating",
242
+ "оценивает": "evaluating",
243
+ "researching": "researching",
244
+ "исследует": "researching",
245
+ "competitor_check": "competitor_research",
246
+ "сравнение": "competitor_research",
247
+ "price_shopping": "price_shopping",
248
+ "ценовой_запрос": "price_shopping",
249
+ "just_browsing": "just_browsing",
250
+ "просто_смотрит": "just_browsing"
251
+ }
252
+
253
+ return intent_mapping.get(intent, intent)
254
+
255
+ def _analyze_psychotype(
256
+ self,
257
+ ai_summary: Dict[str, Any],
258
+ messages: List[Message]
259
+ ) -> Psychotype:
260
+ """Analyze psychotype from conversation."""
261
+ psycho = ai_summary.get("psychotype", "unknown").lower()
262
+
263
+ psychotype_mapping = {
264
+ "driver": Psychotype.DOMINANT,
265
+ "доминантный": Psychotype.DOMINANT,
266
+ "analytical": Psychotype.CONSCIENTIOUS,
267
+ "аналитический": Psychotype.CONSCIENTIOUS,
268
+ "expressive": Psychotype.INFLUENTIAL,
269
+ "влиятельный": Psychotype.INFLUENTIAL,
270
+ "amiable": Psychotype.STEADY,
271
+ "стабильный": Psychotype.STEADY,
272
+ }
273
+
274
+ return psychotype_mapping.get(psycho, Psychotype.UNKNOWN)
275
+
276
+ def _should_sync_to_crm(
277
+ self,
278
+ heat_score: int,
279
+ lead: Lead,
280
+ bant: BANTScore
281
+ ) -> bool:
282
+ """Determine if lead should be synced to CRM."""
283
+
284
+ # Must be hot lead
285
+ if heat_score < self.min_hot_score:
286
+ return False
287
+
288
+ # Must have contact info
289
+ if not lead.email and not lead.phone:
290
+ return False
291
+
292
+ # Must have decent confidence in BANT scoring
293
+ if bant.confidence < 0.5:
294
+ return False
295
+
296
+ return True
297
+
298
+ def _extract_crm_fields(
299
+ self,
300
+ ai_summary: Dict[str, Any],
301
+ lead: Lead
302
+ ) -> Dict[str, Any]:
303
+ """Extract fields suitable for CRM sync."""
304
+
305
+ fields = {
306
+ "name": lead.name,
307
+ "email": lead.email,
308
+ "phone": lead.phone,
309
+ "company": ai_summary.get("company"),
310
+ "position": ai_summary.get("position"),
311
+ "industry": ai_summary.get("industry"),
312
+ "budget": ai_summary.get("budget"),
313
+ "timeline": ai_summary.get("timeline"),
314
+ "use_case": ai_summary.get("use_case"),
315
+ "pain_points": ai_summary.get("pain_points"),
316
+ "decision_context": ai_summary.get("decision_context"),
317
+ }
318
+
319
+ # Remove None values
320
+ return {k: v for k, v in fields.items() if v is not None}
321
+
322
+ def _generate_analysis_summary(
323
+ self,
324
+ bant: BANTScore,
325
+ heat_score: int,
326
+ intent: str,
327
+ psychotype: Psychotype
328
+ ) -> str:
329
+ """Generate human-readable analysis summary."""
330
+
331
+ parts = [
332
+ f"Heat Score: {heat_score}/100",
333
+ f"BANT Total: {bant.total}/100",
334
+ f"Intent: {intent}",
335
+ f"Psychotype: {psychotype.value}"
336
+ ]
337
+
338
+ if bant.confidence < 0.5:
339
+ parts.append("⚠️ Need more information for accurate qualification")
340
+
341
+ return " | ".join(parts)
342
+
343
+
344
+ # Singleton instance
345
+ _qualification_service: Optional[LeadQualificationService] = None
346
+
347
+
348
+ def get_qualification_service() -> LeadQualificationService:
349
+ """Get lead qualification service singleton."""
350
+ global _qualification_service
351
+ if _qualification_service is None:
352
+ _qualification_service = LeadQualificationService()
353
+ return _qualification_service
backend/requirements.txt CHANGED
@@ -22,6 +22,7 @@ numpy>=1.24.0
22
  # Async Tasks
23
  celery==5.3.6
24
  redis==5.0.1
 
25
 
26
  # Authentication & Security
27
  python-jose[cryptography]==3.3.0
 
22
  # Async Tasks
23
  celery==5.3.6
24
  redis==5.0.1
25
+ nest_asyncio==1.6.0
26
 
27
  # Authentication & Security
28
  python-jose[cryptography]==3.3.0
backend/run.py CHANGED
@@ -15,7 +15,7 @@ if __name__ == "__main__":
15
  selector = selectors.SelectSelector()
16
  loop = asyncio.SelectorEventLoop(selector)
17
  asyncio.set_event_loop(loop)
18
- print(f"✅ Created SelectorEventLoop: {loop}")
19
 
20
  import uvicorn
21
 
 
15
  selector = selectors.SelectSelector()
16
  loop = asyncio.SelectorEventLoop(selector)
17
  asyncio.set_event_loop(loop)
18
+ print(f"Created SelectorEventLoop: {loop}")
19
 
20
  import uvicorn
21
 
frontend/app/channels/page.tsx CHANGED
@@ -10,665 +10,665 @@ import { Send, CheckCircle, XCircle, AlertCircle, Loader2, ExternalLink, Copy, C
10
  type Channel = 'telegram' | 'whatsapp' | 'linkedin'
11
 
12
  interface BotInfo {
13
- username: string
14
- first_name: string
15
- id: number
16
  }
17
 
18
  interface TelegramStatus {
19
- ok: boolean
20
- connected: boolean
21
- webhook_url: string | null
22
- bot_info: BotInfo | null
23
  }
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
-
41
- // Get Telegram status
42
- const { data: telegramStatus, isLoading: telegramLoading } = useQuery<TelegramStatus>({
43
- queryKey: ['telegram-status', user?.tenant_id],
44
- queryFn: channelsApi.getTelegramStatus,
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],
60
- queryFn: channelsApi.getLinkedInStatus,
61
- enabled: !!user,
62
- refetchInterval: 15000,
63
- })
64
-
65
- // Connect Telegram mutation
66
- const connectTelegramMutation = useMutation({
67
- mutationFn: channelsApi.connectTelegram,
68
- onSuccess: (data) => {
69
- queryClient.invalidateQueries({ queryKey: ['telegram-status', user?.tenant_id] })
70
- setBotToken('')
71
- toast.success('Успех!', data.message)
72
- },
73
- onError: (error: Error) => {
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) => {
92
- toast.error('Ошибка подключения', error.message)
93
- },
94
- })
95
-
96
- // Disconnect mutations
97
- const disconnectTelegramMutation = useMutation({
98
- mutationFn: channelsApi.disconnectTelegram,
99
- onSuccess: (data) => {
100
- queryClient.invalidateQueries({ queryKey: ['telegram-status', user?.tenant_id] })
101
- toast.info('Отключено', data.message)
102
- },
103
- onError: (error: Error) => {
104
- toast.error('Ошибка', error.message)
105
- },
106
- })
107
-
108
- const disconnectWhatsAppMutation = useMutation({
109
- mutationFn: channelsApi.disconnectWhatsApp,
110
- onSuccess: (data) => {
111
- queryClient.invalidateQueries({ queryKey: ['whatsapp-status', user?.tenant_id] })
112
- toast.info('Отключено', data.message)
113
- },
114
- onError: (error: Error) => {
115
- toast.error('Ошибка', error.message)
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()) {
133
- toast.warning('Внимание', 'Введите токен бота')
134
- return
 
 
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) {
148
- return (
149
- <div className="flex items-center justify-center h-screen bg-gradient-to-br from-slate-50 to-slate-100">
150
- <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
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 (
162
- <div className="min-h-screen bg-slate-100 p-8">
163
- <div className="max-w-5xl mx-auto">
164
- {/* Header */}
165
- <div className="mb-8">
166
- <h1 className="text-4xl font-bold text-slate-900 tracking-tight">Подключение каналов</h1>
167
- <p className="text-slate-600 mt-2">
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">
175
- {tabs.map((tab) => (
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" />
186
- {tab.label}
187
- {tab.status && (
188
- <span className="w-2 h-2 bg-emerald-500 rounded-full"></span>
189
- )}
190
- </div>
191
- {activeTab === tab.id && (
192
- <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-indigo-600"></div>
193
- )}
194
- </button>
195
- ))}
196
- </div>
197
-
198
- {/* Tab Content */}
199
- <div className="p-8">
200
- {/* Telegram Tab */}
201
- {activeTab === 'telegram' && (
202
- <TelegramTab
203
- status={telegramStatus}
204
- loading={telegramLoading}
205
- botToken={botToken}
206
- setBotToken={setBotToken}
207
- showToken={showToken}
208
- setShowToken={setShowToken}
209
- onConnect={handleConnectTelegram}
210
- onDisconnect={() => {
211
- if (confirm('Вы уверены, что хотите отключить Telegram бота?')) {
212
- disconnectTelegramMutation.mutate()
213
- }
214
- }}
215
- isProcessing={connectTelegramMutation.isPending || disconnectTelegramMutation.isPending}
216
- />
217
- )}
218
 
219
- {/* WhatsApp Tab */}
220
- {activeTab === 'whatsapp' && (
221
- <WhatsAppQRTab
222
- status={whatsappStatus}
223
- loading={whatsappLoading}
224
- onDisconnect={() => {
225
- if (confirm('Вы уверены, что хотите отключить WhatsApp?')) {
226
- disconnectWhatsAppMutation.mutate()
227
- }
228
- }}
229
- isProcessing={disconnectWhatsAppMutation.isPending}
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>
255
- </div>
256
- )
257
  }
258
 
259
  // Telegram Tab Component
260
  function TelegramTab({
261
- status,
262
- loading,
263
- botToken,
264
- setBotToken,
265
- showToken,
266
- setShowToken,
267
- onConnect,
268
- onDisconnect,
269
- isProcessing,
270
  }: any) {
271
- const isConnected = status?.connected || false
272
-
273
- return (
274
- <div className="space-y-6">
275
- {/* Status Badge */}
276
- <div className="flex items-center justify-between p-4 bg-slate-50 rounded-xl">
277
- <div className="flex items-center gap-3">
278
- <div className="w-12 h-12 bg-blue-50 rounded-xl flex items-center justify-center">
279
- <Send className="w-6 h-6 text-blue-600" />
280
- </div>
281
- <div>
282
- <h3 className="font-bold text-slate-900">Telegram Bot</h3>
283
- <p className="text-sm text-slate-600">Автоматизация через Telegram API</p>
284
- </div>
285
- </div>
286
- {loading ? (
287
- <Loader2 className="w-5 h-5 animate-spin text-slate-400" />
288
- ) : isConnected ? (
289
- <div className="flex items-center gap-2 px-3 py-1.5 bg-emerald-100 text-emerald-700 rounded-full">
290
- <div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
291
- <span className="text-sm font-semibold">Активен</span>
292
- </div>
293
- ) : (
294
- <div className="flex items-center gap-2 px-3 py-1.5 bg-slate-200 text-slate-600 rounded-full">
295
- <div className="w-2 h-2 bg-slate-400 rounded-full"></div>
296
- <span className="text-sm font-semibold">Не подключен</span>
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">
304
- <div className="flex items-center gap-2 mb-4">
305
- <CheckCircle className="w-5 h-5 text-emerald-600" />
306
- <h4 className="font-bold text-emerald-900">Подключенный бот</h4>
307
- </div>
308
- <div className="space-y-2 text-sm">
309
- <p><span className="font-semibold">Имя:</span> {status.bot_info.first_name}</p>
310
- <p><span className="font-semibold">Username:</span> @{status.bot_info.username}</p>
311
- <p><span className="font-semibold">Bot ID:</span> {status.bot_info.id}</p>
312
- </div>
313
- </div>
314
- <button
315
- onClick={onDisconnect}
316
- disabled={isProcessing}
317
- 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"
318
- >
319
- Отключить бота
320
- </button>
321
- </div>
322
- ) : (
323
  <div className="space-y-6">
324
- {/* Step 1 */}
325
- <div className="space-y-3">
326
- <div className="flex items-center gap-3">
327
- <div className="w-8 h-8 bg-indigo-100 text-indigo-600 rounded-full flex items-center justify-center font-bold text-sm">
328
- 1
329
- </div>
330
- <h4 className="font-bold text-slate-900">Откройте @BotFather в Telegram</h4>
331
- </div>
332
- <p className="ml-11 text-sm text-slate-600">
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">
340
- <div className="w-8 h-8 bg-indigo-100 text-indigo-600 rounded-full flex items-center justify-center font-bold text-sm">
341
- 2
342
- </div>
343
- <h4 className="font-bold text-slate-900">Создайте нового бота</h4>
344
- </div>
345
- <p className="ml-11 text-sm text-slate-600">
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">
353
- <div className="w-8 h-8 bg-indigo-100 text-indigo-600 rounded-full flex items-center justify-center font-bold text-sm">
354
- 3
355
- </div>
356
- <h4 className="font-bold text-slate-900">Введите токен и подключите</h4>
357
- </div>
358
- <div className="ml-11 space-y-3">
359
- <div>
360
- <label className="block text-sm font-semibold text-slate-700 mb-2">
361
- Токен бота
362
- </label>
363
- <div className="flex gap-2">
364
- <input
365
- type={showToken ? 'text' : 'password'}
366
- value={botToken}
367
- onChange={(e) => setBotToken(e.target.value)}
368
- placeholder="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
369
- className="flex-1 px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent font-mono text-sm"
370
- disabled={isProcessing}
371
- />
372
- <button
373
- onClick={() => setShowToken(!showToken)}
374
- className="px-4 py-3 border border-slate-200 rounded-xl hover:bg-slate-50"
375
- disabled={isProcessing}
376
- >
377
- {showToken ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
378
- </button>
379
  </div>
380
- <p className="mt-2 text-xs text-slate-500">
381
- Токен имеет формат: 123456:ABC-DEF...
382
- </p>
383
- </div>
384
- <button
385
- onClick={onConnect}
386
- disabled={isProcessing || !botToken.trim()}
387
- className="w-full px-6 py-3 bg-gradient-to-r from-indigo-600 to-indigo-700 text-white rounded-xl hover:from-indigo-500 hover:to-indigo-600 disabled:opacity-50 disabled:cursor-not-allowed font-semibold flex items-center justify-center gap-2 shadow-lg"
388
- >
389
- {isProcessing ? (
390
- <>
391
- <Loader2 className="w-5 h-5 animate-spin" />
392
- Подключение...
393
- </>
394
  ) : (
395
- <>
396
- <Send className="w-5 h-5" />
397
- Подключить Telegram
398
- </>
399
  )}
400
- </button>
401
  </div>
402
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
403
  </div>
404
- )}
405
- </div>
406
- )
407
  }
408
 
409
  // WhatsApp QR Tab Component
410
  function WhatsAppQRTab({
411
- status,
412
- loading,
413
- onDisconnect,
414
- isProcessing,
415
- tenantId,
416
  }: any) {
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 */}
443
- <div className="flex items-center justify-between p-4 bg-slate-50 rounded-xl">
444
- <div className="flex items-center gap-3">
445
- <div className="w-12 h-12 bg-emerald-50 rounded-xl flex items-center justify-center text-2xl">
446
- <Smartphone className="w-6 h-6 text-emerald-600" />
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 ? (
454
- <Loader2 className="w-5 h-5 animate-spin text-slate-400" />
455
- ) : isConnected ? (
456
- <div className="flex items-center gap-2 px-3 py-1.5 bg-emerald-100 text-emerald-700 rounded-full">
457
- <div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
458
- <span className="text-sm font-semibold">Активен</span>
459
- </div>
460
- ) : (
461
- <div className="flex items-center gap-2 px-3 py-1.5 bg-slate-200 text-slate-600 rounded-full">
462
- <div className="w-2 h-2 bg-slate-400 rounded-full"></div>
463
- <span className="text-sm font-semibold">Не подключен</span>
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">
471
- <div className="flex items-center gap-2 mb-4">
472
- <CheckCircle className="w-5 h-5 text-emerald-600" />
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
481
- onClick={onDisconnect}
482
- disabled={isProcessing}
483
- 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"
484
- >
485
- Отключить WhatsApp
486
- </button>
487
- </div>
488
- ) : (
489
  <div className="space-y-6">
490
- {/* Информация */}
491
- <div className="p-6 bg-gradient-to-br from-emerald-50 to-teal-50 border-2 border-emerald-200 rounded-2xl">
492
- <div className="flex items-start gap-4">
493
- <div className="w-12 h-12 bg-emerald-600 rounded-xl flex items-center justify-center flex-shrink-0">
494
- <Zap className="w-6 h-6 text-white" />
495
- </div>
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
514
- </p>
515
- </div>
516
  ) : (
517
- <div className="space-y-4">
518
- <div className="w-64 h-64 mx-auto bg-slate-100 rounded-xl flex items-center justify-center">
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
- >
526
- {isConnecting ? (
527
- <>
528
- <Loader2 className="w-6 h-6 animate-spin" />
529
- Генерация QR...
530
- </>
531
- ) : (
532
- <>
533
- <QrCode className="w-6 h-6" />
534
- Генерировать QR-код
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 flex items-center gap-2">
545
- <BookOpen className="w-5 h-5" />
546
- Как это работает:
547
- </h4>
548
- <ol className="list-decimal ml-5 space-y-2 text-sm text-blue-900">
549
- <li>Нажмите "Генерировать QR-код"</li>
550
- <li>Откройте WhatsApp на телефоне</li>
551
- <li>Перейдите: Настройки → Linked Devices → Link a Device</li>
552
- <li>Отсканируйте QR-код на экране</li>
553
- <li>Готово! WhatsApp подключён</li>
554
- </ol>
555
- </div>
556
  </div>
557
- )}
558
- </div>
559
- )
560
  }
561
 
562
  // LinkedIn Tab Component
563
  function LinkedInTab({
564
- status,
565
- loading,
566
- accessToken,
567
- setAccessToken,
568
- orgId,
569
- setOrgId,
570
- onConnect,
571
- onDisconnect,
572
- isProcessing,
573
  }: any) {
574
- const isConnected = status?.connected || false
575
-
576
- return (
577
- <div className="space-y-6">
578
- {/* Status Badge */}
579
- <div className="flex items-center justify-between p-4 bg-slate-50 rounded-xl">
580
- <div className="flex items-center gap-3">
581
- <div className="w-12 h-12 bg-blue-50 rounded-xl flex items-center justify-center">
582
- <Linkedin className="w-6 h-6 text-blue-600" />
583
- </div>
584
- <div>
585
- <h3 className="font-bold text-slate-900">LinkedIn</h3>
586
- <p className="text-sm text-slate-600">Автоматизация через LinkedIn API</p>
587
- </div>
588
- </div>
589
- {loading ? (
590
- <Loader2 className="w-5 h-5 animate-spin text-slate-400" />
591
- ) : isConnected ? (
592
- <div className="flex items-center gap-2 px-3 py-1.5 bg-emerald-100 text-emerald-700 rounded-full">
593
- <div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
594
- <span className="text-sm font-semibold">Активен</span>
595
- </div>
596
- ) : (
597
- <div className="flex items-center gap-2 px-3 py-1.5 bg-slate-200 text-slate-600 rounded-full">
598
- <div className="w-2 h-2 bg-slate-400 rounded-full"></div>
599
- <span className="text-sm font-semibold">Не подключен</span>
600
- </div>
601
- )}
602
- </div>
603
-
604
- {isConnected ? (
605
- <div className="space-y-4">
606
- <div className="p-6 bg-blue-50 border border-blue-200 rounded-xl">
607
- <div className="flex items-center gap-2 mb-4">
608
- <CheckCircle className="w-5 h-5 text-blue-600" />
609
- <h4 className="font-bold text-blue-900">LinkedIn подключён</h4>
610
- </div>
611
- <div className="space-y-2 text-sm">
612
- <p><span className="font-semibold">Организация:</span> {status.config?.org_name || status.config?.organization_id}</p>
613
- </div>
614
- </div>
615
- <button
616
- onClick={onDisconnect}
617
- disabled={isProcessing}
618
- 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"
619
- >
620
- Отключить LinkedIn
621
- </button>
622
- </div>
623
- ) : (
624
  <div className="space-y-6">
625
- <div className="space-y-4">
626
- <div>
627
- <label className="block text-sm font-semibold text-slate-700 mb-2">
628
- Access Token
629
- </label>
630
- <input
631
- type="password"
632
- value={accessToken}
633
- onChange={(e) => setAccessToken(e.target.value)}
634
- placeholder="LinkedIn Access Token"
635
- className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent"
636
- disabled={isProcessing}
637
- />
638
- </div>
639
- <div>
640
- <label className="block text-sm font-semibold text-slate-700 mb-2">
641
- Organization ID
642
- </label>
643
- <input
644
- type="text"
645
- value={orgId}
646
- onChange={(e) => setOrgId(e.target.value)}
647
- placeholder="12345678"
648
- className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent"
649
- disabled={isProcessing}
650
- />
651
  </div>
652
- <button
653
- onClick={onConnect}
654
- disabled={isProcessing || !accessToken.trim() || !orgId.trim()}
655
- 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"
656
- >
657
- {isProcessing ? (
658
- <>
659
- <Loader2 className="w-5 h-5 animate-spin" />
660
- Подключение...
661
- </>
662
- ) : (
663
- <>
664
- <Linkedin className="w-5 h-5" />
665
- Подключить LinkedIn
666
- </>
667
- )}
668
- </button>
669
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
670
  </div>
671
- )}
672
- </div>
673
- )
674
  }
 
10
  type Channel = 'telegram' | 'whatsapp' | 'linkedin'
11
 
12
  interface BotInfo {
13
+ username: string
14
+ first_name: string
15
+ id: number
16
  }
17
 
18
  interface TelegramStatus {
19
+ ok: boolean
20
+ connected: boolean
21
+ webhook_url: string | null
22
+ bot_info: BotInfo | null
23
  }
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
+
41
+ // Get Telegram status
42
+ const { data: telegramStatus, isLoading: telegramLoading } = useQuery<TelegramStatus>({
43
+ queryKey: ['telegram-status', user?.tenant_id],
44
+ queryFn: channelsApi.getTelegramStatus,
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],
60
+ queryFn: channelsApi.getLinkedInStatus,
61
+ enabled: !!user,
62
+ refetchInterval: 15000,
63
+ })
64
+
65
+ // Connect Telegram mutation
66
+ const connectTelegramMutation = useMutation({
67
+ mutationFn: channelsApi.connectTelegram,
68
+ onSuccess: (data) => {
69
+ queryClient.invalidateQueries({ queryKey: ['telegram-status', user?.tenant_id] })
70
+ setBotToken('')
71
+ toast.success('Успех!', data.message)
72
+ },
73
+ onError: (error: Error) => {
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) => {
92
+ toast.error('Ошибка подключения', error.message)
93
+ },
94
+ })
95
+
96
+ // Disconnect mutations
97
+ const disconnectTelegramMutation = useMutation({
98
+ mutationFn: channelsApi.disconnectTelegram,
99
+ onSuccess: (data) => {
100
+ queryClient.invalidateQueries({ queryKey: ['telegram-status', user?.tenant_id] })
101
+ toast.info('Отключено', data.message)
102
+ },
103
+ onError: (error: Error) => {
104
+ toast.error('Ошибка', error.message)
105
+ },
106
+ })
107
+
108
+ const disconnectWhatsAppMutation = useMutation({
109
+ mutationFn: channelsApi.disconnectWhatsApp,
110
+ onSuccess: (data) => {
111
+ queryClient.invalidateQueries({ queryKey: ['whatsapp-status', user?.tenant_id] })
112
+ toast.info('Отключено', data.message)
113
+ },
114
+ onError: (error: Error) => {
115
+ toast.error('Ошибка', error.message)
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()) {
133
+ toast.warning('Внимание', 'Введите токен бота')
134
+ return
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) {
148
+ return (
149
+ <div className="flex items-center justify-center h-screen bg-gradient-to-br from-slate-50 to-slate-100">
150
+ <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
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 (
162
+ <div className="min-h-screen bg-slate-100 p-8">
163
+ <div className="max-w-5xl mx-auto">
164
+ {/* Header */}
165
+ <div className="mb-8">
166
+ <h1 className="text-4xl font-bold text-slate-900 tracking-tight">Подключение каналов</h1>
167
+ <p className="text-slate-600 mt-2">
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">
175
+ {tabs.map((tab) => (
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" />
186
+ {tab.label}
187
+ {tab.status && (
188
+ <span className="w-2 h-2 bg-emerald-500 rounded-full"></span>
189
+ )}
190
+ </div>
191
+ {activeTab === tab.id && (
192
+ <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-indigo-600"></div>
193
+ )}
194
+ </button>
195
+ ))}
196
+ </div>
197
+
198
+ {/* Tab Content */}
199
+ <div className="p-8">
200
+ {/* Telegram Tab */}
201
+ {activeTab === 'telegram' && (
202
+ <TelegramTab
203
+ status={telegramStatus}
204
+ loading={telegramLoading}
205
+ botToken={botToken}
206
+ setBotToken={setBotToken}
207
+ showToken={showToken}
208
+ setShowToken={setShowToken}
209
+ onConnect={handleConnectTelegram}
210
+ onDisconnect={() => {
211
+ if (confirm('Вы уверены, что хотите отключить Telegram бота?')) {
212
+ disconnectTelegramMutation.mutate()
213
+ }
214
+ }}
215
+ isProcessing={connectTelegramMutation.isPending || disconnectTelegramMutation.isPending}
216
+ />
217
+ )}
218
+
219
+ {/* WhatsApp Tab */}
220
+ {activeTab === 'whatsapp' && (
221
+ <WhatsAppQRTab
222
+ status={whatsappStatus}
223
+ loading={whatsappLoading}
224
+ onDisconnect={() => {
225
+ if (confirm('Вы уверены, что хотите отключить WhatsApp?')) {
226
+ disconnectWhatsAppMutation.mutate()
227
+ }
228
+ }}
229
+ isProcessing={disconnectWhatsAppMutation.isPending}
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>
255
  </div>
256
+ )
 
 
257
  }
258
 
259
  // Telegram Tab Component
260
  function TelegramTab({
261
+ status,
262
+ loading,
263
+ botToken,
264
+ setBotToken,
265
+ showToken,
266
+ setShowToken,
267
+ onConnect,
268
+ onDisconnect,
269
+ isProcessing,
270
  }: any) {
271
+ const isConnected = status?.connected || false
272
+
273
+ return (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
  <div className="space-y-6">
275
+ {/* Status Badge */}
276
+ <div className="flex items-center justify-between p-4 bg-slate-50 rounded-xl">
277
+ <div className="flex items-center gap-3">
278
+ <div className="w-12 h-12 bg-blue-50 rounded-xl flex items-center justify-center">
279
+ <Send className="w-6 h-6 text-blue-600" />
280
+ </div>
281
+ <div>
282
+ <h3 className="font-bold text-slate-900">Telegram Bot</h3>
283
+ <p className="text-sm text-slate-600">Автоматизация через Telegram API</p>
284
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
  </div>
286
+ {loading ? (
287
+ <Loader2 className="w-5 h-5 animate-spin text-slate-400" />
288
+ ) : isConnected ? (
289
+ <div className="flex items-center gap-2 px-3 py-1.5 bg-emerald-100 text-emerald-700 rounded-full">
290
+ <div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
291
+ <span className="text-sm font-semibold">Активен</span>
292
+ </div>
 
 
 
 
 
 
 
293
  ) : (
294
+ <div className="flex items-center gap-2 px-3 py-1.5 bg-slate-200 text-slate-600 rounded-full">
295
+ <div className="w-2 h-2 bg-slate-400 rounded-full"></div>
296
+ <span className="text-sm font-semibold">Не подключен</span>
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">
304
+ <div className="flex items-center gap-2 mb-4">
305
+ <CheckCircle className="w-5 h-5 text-emerald-600" />
306
+ <h4 className="font-bold text-emerald-900">Подключенный бот</h4>
307
+ </div>
308
+ <div className="space-y-2 text-sm">
309
+ <p><span className="font-semibold">Имя:</span> {status.bot_info.first_name}</p>
310
+ <p><span className="font-semibold">Username:</span> @{status.bot_info.username}</p>
311
+ <p><span className="font-semibold">Bot ID:</span> {status.bot_info.id}</p>
312
+ </div>
313
+ </div>
314
+ <button
315
+ onClick={onDisconnect}
316
+ disabled={isProcessing}
317
+ 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"
318
+ >
319
+ Отключить бота
320
+ </button>
321
+ </div>
322
+ ) : (
323
+ <div className="space-y-6">
324
+ {/* Step 1 */}
325
+ <div className="space-y-3">
326
+ <div className="flex items-center gap-3">
327
+ <div className="w-8 h-8 bg-indigo-100 text-indigo-600 rounded-full flex items-center justify-center font-bold text-sm">
328
+ 1
329
+ </div>
330
+ <h4 className="font-bold text-slate-900">Откройте @BotFather в Telegram</h4>
331
+ </div>
332
+ <p className="ml-11 text-sm text-slate-600">
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">
340
+ <div className="w-8 h-8 bg-indigo-100 text-indigo-600 rounded-full flex items-center justify-center font-bold text-sm">
341
+ 2
342
+ </div>
343
+ <h4 className="font-bold text-slate-900">Создайте нового бота</h4>
344
+ </div>
345
+ <p className="ml-11 text-sm text-slate-600">
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">
353
+ <div className="w-8 h-8 bg-indigo-100 text-indigo-600 rounded-full flex items-center justify-center font-bold text-sm">
354
+ 3
355
+ </div>
356
+ <h4 className="font-bold text-slate-900">Введите токен и подключите</h4>
357
+ </div>
358
+ <div className="ml-11 space-y-3">
359
+ <div>
360
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
361
+ Токен бота
362
+ </label>
363
+ <div className="flex gap-2">
364
+ <input
365
+ type={showToken ? 'text' : 'password'}
366
+ value={botToken}
367
+ onChange={(e) => setBotToken(e.target.value)}
368
+ placeholder="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
369
+ className="flex-1 px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent font-mono text-sm"
370
+ disabled={isProcessing}
371
+ />
372
+ <button
373
+ onClick={() => setShowToken(!showToken)}
374
+ className="px-4 py-3 border border-slate-200 rounded-xl hover:bg-slate-50"
375
+ disabled={isProcessing}
376
+ >
377
+ {showToken ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
378
+ </button>
379
+ </div>
380
+ <p className="mt-2 text-xs text-slate-500">
381
+ Токен имеет формат: 123456:ABC-DEF...
382
+ </p>
383
+ </div>
384
+ <button
385
+ onClick={onConnect}
386
+ disabled={isProcessing || !botToken.trim()}
387
+ className="w-full px-6 py-3 bg-gradient-to-r from-indigo-600 to-indigo-700 text-white rounded-xl hover:from-indigo-500 hover:to-indigo-600 disabled:opacity-50 disabled:cursor-not-allowed font-semibold flex items-center justify-center gap-2 shadow-lg"
388
+ >
389
+ {isProcessing ? (
390
+ <>
391
+ <Loader2 className="w-5 h-5 animate-spin" />
392
+ Подключение...
393
+ </>
394
+ ) : (
395
+ <>
396
+ <Send className="w-5 h-5" />
397
+ Подключить Telegram
398
+ </>
399
+ )}
400
+ </button>
401
+ </div>
402
+ </div>
403
+ </div>
404
+ )}
405
  </div>
406
+ )
 
 
407
  }
408
 
409
  // WhatsApp QR Tab Component
410
  function WhatsAppQRTab({
411
+ status,
412
+ loading,
413
+ onDisconnect,
414
+ isProcessing,
415
+ tenantId,
416
  }: any) {
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 */}
443
+ <div className="flex items-center justify-between p-4 bg-slate-50 rounded-xl">
444
+ <div className="flex items-center gap-3">
445
+ <div className="w-12 h-12 bg-emerald-50 rounded-xl flex items-center justify-center text-2xl">
446
+ <Smartphone className="w-6 h-6 text-emerald-600" />
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 ? (
454
+ <Loader2 className="w-5 h-5 animate-spin text-slate-400" />
455
+ ) : isConnected ? (
456
+ <div className="flex items-center gap-2 px-3 py-1.5 bg-emerald-100 text-emerald-700 rounded-full">
457
+ <div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
458
+ <span className="text-sm font-semibold">Активен</span>
459
+ </div>
460
+ ) : (
461
+ <div className="flex items-center gap-2 px-3 py-1.5 bg-slate-200 text-slate-600 rounded-full">
462
+ <div className="w-2 h-2 bg-slate-400 rounded-full"></div>
463
+ <span className="text-sm font-semibold">Не подключен</span>
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">
471
+ <div className="flex items-center gap-2 mb-4">
472
+ <CheckCircle className="w-5 h-5 text-emerald-600" />
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
481
+ onClick={onDisconnect}
482
+ disabled={isProcessing}
483
+ 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"
484
+ >
485
+ Отключить WhatsApp
486
+ </button>
487
  </div>
 
 
 
 
488
  ) : (
489
+ <div className="space-y-6">
490
+ {/* Информация */}
491
+ <div className="p-6 bg-gradient-to-br from-emerald-50 to-teal-50 border-2 border-emerald-200 rounded-2xl">
492
+ <div className="flex items-start gap-4">
493
+ <div className="w-12 h-12 bg-emerald-600 rounded-xl flex items-center justify-center flex-shrink-0">
494
+ <Zap className="w-6 h-6 text-white" />
495
+ </div>
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
514
+ </p>
515
+ </div>
516
+ ) : (
517
+ <div className="space-y-4">
518
+ <div className="w-64 h-64 mx-auto bg-slate-100 rounded-xl flex items-center justify-center">
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
+ >
526
+ {isConnecting ? (
527
+ <>
528
+ <Loader2 className="w-6 h-6 animate-spin" />
529
+ Генерация QR...
530
+ </>
531
+ ) : (
532
+ <>
533
+ <QrCode className="w-6 h-6" />
534
+ Генерировать QR-код
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 flex items-center gap-2">
545
+ <BookOpen className="w-5 h-5" />
546
+ Как это работает:
547
+ </h4>
548
+ <ol className="list-decimal ml-5 space-y-2 text-sm text-blue-900">
549
+ <li>Нажмите "Генерировать QR-код"</li>
550
+ <li>Откройте WhatsApp на телефоне</li>
551
+ <li>Перейдите: Настройки → Linked Devices → Link a Device</li>
552
+ <li>Отсканируйте QR-код на экране</li>
553
+ <li>Готово! WhatsApp подключён</li>
554
+ </ol>
555
+ </div>
556
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558
  </div>
559
+ )
 
 
560
  }
561
 
562
  // LinkedIn Tab Component
563
  function LinkedInTab({
564
+ status,
565
+ loading,
566
+ accessToken,
567
+ setAccessToken,
568
+ orgId,
569
+ setOrgId,
570
+ onConnect,
571
+ onDisconnect,
572
+ isProcessing,
573
  }: any) {
574
+ const isConnected = status?.connected || false
575
+
576
+ return (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
577
  <div className="space-y-6">
578
+ {/* Status Badge */}
579
+ <div className="flex items-center justify-between p-4 bg-slate-50 rounded-xl">
580
+ <div className="flex items-center gap-3">
581
+ <div className="w-12 h-12 bg-blue-50 rounded-xl flex items-center justify-center">
582
+ <Linkedin className="w-6 h-6 text-blue-600" />
583
+ </div>
584
+ <div>
585
+ <h3 className="font-bold text-slate-900">LinkedIn</h3>
586
+ <p className="text-sm text-slate-600">Автоматизация через LinkedIn API</p>
587
+ </div>
588
+ </div>
589
+ {loading ? (
590
+ <Loader2 className="w-5 h-5 animate-spin text-slate-400" />
591
+ ) : isConnected ? (
592
+ <div className="flex items-center gap-2 px-3 py-1.5 bg-emerald-100 text-emerald-700 rounded-full">
593
+ <div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
594
+ <span className="text-sm font-semibold">Активен</span>
595
+ </div>
596
+ ) : (
597
+ <div className="flex items-center gap-2 px-3 py-1.5 bg-slate-200 text-slate-600 rounded-full">
598
+ <div className="w-2 h-2 bg-slate-400 rounded-full"></div>
599
+ <span className="text-sm font-semibold">Не подключен</span>
600
+ </div>
601
+ )}
 
 
602
  </div>
603
+
604
+ {isConnected ? (
605
+ <div className="space-y-4">
606
+ <div className="p-6 bg-blue-50 border border-blue-200 rounded-xl">
607
+ <div className="flex items-center gap-2 mb-4">
608
+ <CheckCircle className="w-5 h-5 text-blue-600" />
609
+ <h4 className="font-bold text-blue-900">LinkedIn подключён</h4>
610
+ </div>
611
+ <div className="space-y-2 text-sm">
612
+ <p><span className="font-semibold">Организация:</span> {status.config?.org_name || status.config?.organization_id}</p>
613
+ </div>
614
+ </div>
615
+ <button
616
+ onClick={onDisconnect}
617
+ disabled={isProcessing}
618
+ 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"
619
+ >
620
+ Отключить LinkedIn
621
+ </button>
622
+ </div>
623
+ ) : (
624
+ <div className="space-y-6">
625
+ <div className="space-y-4">
626
+ <div>
627
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
628
+ Access Token
629
+ </label>
630
+ <input
631
+ type="password"
632
+ value={accessToken}
633
+ onChange={(e) => setAccessToken(e.target.value)}
634
+ placeholder="LinkedIn Access Token"
635
+ className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent"
636
+ disabled={isProcessing}
637
+ />
638
+ </div>
639
+ <div>
640
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
641
+ Organization ID
642
+ </label>
643
+ <input
644
+ type="text"
645
+ value={orgId}
646
+ onChange={(e) => setOrgId(e.target.value)}
647
+ placeholder="12345678"
648
+ className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent"
649
+ disabled={isProcessing}
650
+ />
651
+ </div>
652
+ <button
653
+ onClick={onConnect}
654
+ disabled={isProcessing || !accessToken.trim() || !orgId.trim()}
655
+ 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"
656
+ >
657
+ {isProcessing ? (
658
+ <>
659
+ <Loader2 className="w-5 h-5 animate-spin" />
660
+ Подключение...
661
+ </>
662
+ ) : (
663
+ <>
664
+ <Linkedin className="w-5 h-5" />
665
+ Подключить LinkedIn
666
+ </>
667
+ )}
668
+ </button>
669
+ </div>
670
+ </div>
671
+ )}
672
  </div>
673
+ )
 
 
674
  }
frontend/app/chats/page.tsx CHANGED
@@ -11,130 +11,130 @@ import { ClientCard } from '@/components/ClientCard'
11
  import { Loader2 } from 'lucide-react'
12
 
13
  export default function ChatsPage() {
14
- const router = useRouter()
15
- const { user, isLoading: authLoading } = useAuth()
16
- const [selectedLead, setSelectedLead] = useState<Lead | undefined>(undefined)
17
- const [messages, setMessages] = useState<Message[]>([])
18
- const [messagesLoading, setMessagesLoading] = useState(false)
19
- const [searchQuery, setSearchQuery] = useState('')
20
- const [activeTab, setActiveTab] = useState<'all' | 'hot' | 'unread'>('all')
21
- const [conversation, setConversation] = useState<any>(null)
22
- const [isLeadsListOpen, setIsLeadsListOpen] = useState(true)
23
 
24
- // Fetch Leads
25
- const { data: leads, isLoading: leadsLoading, refetch: refetchLeads } = useQuery({
26
- queryKey: ['leads', user?.tenant_id],
27
- queryFn: () => leadsApi.getLeads(),
28
- enabled: !!user?.tenant_id,
29
- refetchInterval: 5000
30
- })
31
 
32
- // Fetch Conversation
33
- const fetchConversation = async (leadId: string) => {
34
- setMessagesLoading(true)
35
- try {
36
- const data = await leadsApi.getConversation(leadId)
37
- setMessages(data.messages || [])
38
- setConversation(data)
39
- } catch (error) {
40
- console.error('Error fetching conversation:', error)
41
- } finally {
42
- setMessagesLoading(false)
 
43
  }
44
- }
45
 
46
- // Handle Lead Selection
47
- const handleSelectLead = (lead: Lead) => {
48
- setSelectedLead(lead)
49
- fetchConversation(lead.id)
50
- }
 
 
 
 
 
 
 
 
51
 
52
- // Initial Selection
53
- useEffect(() => {
54
- if (leads && leads.length > 0 && !selectedLead) {
55
- // Optional: Auto-select first lead
56
- // handleSelectLead(leads[0])
 
57
  }
58
- }, [leads])
59
 
60
- // Refresh Handlers
61
- const handleRefresh = async () => {
62
- await refetchLeads()
63
- if (selectedLead) {
64
- await fetchConversation(selectedLead.id)
 
65
  }
66
- }
67
 
68
- if (authLoading || !user) {
69
  return (
70
- <div className="flex items-center justify-center h-screen bg-slate-50">
71
- <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
72
- </div>
73
- )
74
- }
75
-
76
- return (
77
- <div className="flex h-screen overflow-hidden bg-slate-100">
78
- {/* Left Column: Leads List (Collapsible) */}
79
- <div className={`h-full border-r border-slate-200 z-20 transition-all duration-300 ease-in-out overflow-hidden ${isLeadsListOpen ? 'w-1/4 min-w-[300px] max-w-[400px]' : 'w-0 border-none'}`}>
80
- <LeadsList
81
- leads={leads}
82
- isLoading={leadsLoading}
83
- selectedLeadId={selectedLead?.id}
84
- onSelectLead={handleSelectLead}
85
- searchQuery={searchQuery}
86
- setSearchQuery={setSearchQuery}
87
- activeTab={activeTab}
88
- setActiveTab={setActiveTab}
89
- />
90
- </div>
91
 
92
- {/* Center Column: Chat Window (50%) */}
93
- <div className="flex-1 h-full min-w-[400px] relative z-10">
94
- {selectedLead ? (
95
- <ChatWindow
96
- messages={messages}
97
- leadId={selectedLead.id}
98
- tenantId={user.tenant_id}
99
- conversationId={conversation?.id}
100
- lead={selectedLead}
101
- conversation={conversation}
102
- isLoading={messagesLoading}
103
- isAnalyzing={selectedLead.processing_status === 'analyzing'}
104
- onRefresh={handleRefresh}
105
- onTakeover={() => { }} // Implement takeover logic if needed
106
- onBack={() => setSelectedLead(undefined)} // Mobile back
107
- onToggleLeadsList={() => setIsLeadsListOpen(!isLeadsListOpen)}
108
- isLeadsListOpen={isLeadsListOpen}
109
- />
110
- ) : (
111
- <div className="h-full flex flex-col items-center justify-center bg-slate-50 text-slate-400">
112
- <div className="w-16 h-16 bg-white rounded-2xl flex items-center justify-center shadow-sm mb-4">
113
- <Loader2 className="w-8 h-8 animate-spin text-indigo-200" />
114
- {/* Or a static icon if not loading */}
 
 
 
 
115
  </div>
116
- <p className="font-medium">Выберите диалог из списка</p>
117
- </div>
118
- )}
119
- </div>
120
 
121
- {/* Right Column: Client Intelligence (25%) */}
122
- <div className="w-1/4 min-w-[300px] max-w-[400px] h-full border-l border-slate-200 bg-white hidden lg:block z-20">
123
- {selectedLead ? (
124
- <ClientCard
125
- lead={selectedLead}
126
- onTakeover={() => { }}
127
- isAnalyzing={selectedLead.processing_status === 'analyzing'}
128
- onRefresh={handleRefresh}
129
- conversationId={conversation?.id}
130
- tenantId={user.tenant_id}
131
- />
132
- ) : (
133
- <div className="h-full flex items-center justify-center bg-slate-50/50 text-slate-400 text-sm">
134
- Нет выбранного лида
135
- </div>
136
- )}
137
- </div>
138
- </div>
139
- )
140
  }
 
11
  import { Loader2 } from 'lucide-react'
12
 
13
  export default function ChatsPage() {
14
+ const router = useRouter()
15
+ const { user, isLoading: authLoading } = useAuth()
16
+ const [selectedLead, setSelectedLead] = useState<Lead | undefined>(undefined)
17
+ const [messages, setMessages] = useState<Message[]>([])
18
+ const [messagesLoading, setMessagesLoading] = useState(false)
19
+ const [searchQuery, setSearchQuery] = useState('')
20
+ const [activeTab, setActiveTab] = useState<'all' | 'hot' | 'unread'>('all')
21
+ const [conversation, setConversation] = useState<any>(null)
22
+ const [isLeadsListOpen, setIsLeadsListOpen] = useState(true)
23
 
24
+ // Fetch Leads
25
+ const { data: leads, isLoading: leadsLoading, refetch: refetchLeads } = useQuery({
26
+ queryKey: ['leads', user?.tenant_id],
27
+ queryFn: () => leadsApi.getLeads(),
28
+ enabled: !!user?.tenant_id,
29
+ refetchInterval: 5000
30
+ })
31
 
32
+ // Fetch Conversation
33
+ const fetchConversation = async (leadId: string) => {
34
+ setMessagesLoading(true)
35
+ try {
36
+ const data = await leadsApi.getConversation(leadId)
37
+ setMessages(data.messages || [])
38
+ setConversation(data)
39
+ } catch (error) {
40
+ console.error('Error fetching conversation:', error)
41
+ } finally {
42
+ setMessagesLoading(false)
43
+ }
44
  }
 
45
 
46
+ // Handle Lead Selection
47
+ const handleSelectLead = (lead: Lead) => {
48
+ setSelectedLead(lead)
49
+ fetchConversation(lead.id)
50
+ }
51
+
52
+ // Initial Selection
53
+ useEffect(() => {
54
+ if (leads && leads.length > 0 && !selectedLead) {
55
+ // Optional: Auto-select first lead
56
+ // handleSelectLead(leads[0])
57
+ }
58
+ }, [leads])
59
 
60
+ // Refresh Handlers
61
+ const handleRefresh = async () => {
62
+ await refetchLeads()
63
+ if (selectedLead) {
64
+ await fetchConversation(selectedLead.id)
65
+ }
66
  }
 
67
 
68
+ if (authLoading || !user) {
69
+ return (
70
+ <div className="flex items-center justify-center h-screen bg-slate-50">
71
+ <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
72
+ </div>
73
+ )
74
  }
 
75
 
 
76
  return (
77
+ <div className="flex h-screen overflow-hidden bg-slate-100">
78
+ {/* Left Column: Leads List (Collapsible) */}
79
+ <div className={`h-full border-r border-slate-200 z-20 transition-all duration-300 ease-in-out overflow-hidden ${isLeadsListOpen ? 'w-1/4 min-w-[300px] max-w-[400px]' : 'w-0 border-none'}`}>
80
+ <LeadsList
81
+ leads={leads}
82
+ isLoading={leadsLoading}
83
+ selectedLeadId={selectedLead?.id}
84
+ onSelectLead={handleSelectLead}
85
+ searchQuery={searchQuery}
86
+ setSearchQuery={setSearchQuery}
87
+ activeTab={activeTab}
88
+ setActiveTab={setActiveTab}
89
+ />
90
+ </div>
 
 
 
 
 
 
 
91
 
92
+ {/* Center Column: Chat Window (50%) */}
93
+ <div className="flex-1 h-full min-w-[400px] relative z-10">
94
+ {selectedLead ? (
95
+ <ChatWindow
96
+ messages={messages}
97
+ leadId={selectedLead.id}
98
+ tenantId={user.tenant_id}
99
+ conversationId={conversation?.id}
100
+ lead={selectedLead}
101
+ conversation={conversation}
102
+ isLoading={messagesLoading}
103
+ isAnalyzing={selectedLead.processing_status === 'analyzing'}
104
+ onRefresh={handleRefresh}
105
+ onTakeover={() => { }} // Implement takeover logic if needed
106
+ onBack={() => setSelectedLead(undefined)} // Mobile back
107
+ onToggleLeadsList={() => setIsLeadsListOpen(!isLeadsListOpen)}
108
+ isLeadsListOpen={isLeadsListOpen}
109
+ />
110
+ ) : (
111
+ <div className="h-full flex flex-col items-center justify-center bg-slate-50 text-slate-400">
112
+ <div className="w-16 h-16 bg-white rounded-2xl flex items-center justify-center shadow-sm mb-4">
113
+ <Loader2 className="w-8 h-8 animate-spin text-indigo-200" />
114
+ {/* Or a static icon if not loading */}
115
+ </div>
116
+ <p className="font-medium">Выберите диалог из списка</p>
117
+ </div>
118
+ )}
119
  </div>
 
 
 
 
120
 
121
+ {/* Right Column: Client Intelligence (25%) */}
122
+ <div className="w-1/4 min-w-[300px] max-w-[400px] h-full border-l border-slate-200 bg-white hidden lg:block z-20">
123
+ {selectedLead ? (
124
+ <ClientCard
125
+ lead={selectedLead}
126
+ onTakeover={() => { }}
127
+ isAnalyzing={selectedLead.processing_status === 'analyzing'}
128
+ onRefresh={handleRefresh}
129
+ conversationId={conversation?.id}
130
+ tenantId={user.tenant_id}
131
+ />
132
+ ) : (
133
+ <div className="h-full flex items-center justify-center bg-slate-50/50 text-slate-400 text-sm">
134
+ Нет выбранного лида
135
+ </div>
136
+ )}
137
+ </div>
138
+ </div>
139
+ )
140
  }
frontend/app/layout.tsx CHANGED
@@ -7,8 +7,35 @@ import { Providers } from './providers'
7
  import { Sidebar } from '@/components/Sidebar'
8
  import { usePathname } from 'next/navigation'
9
 
 
 
 
 
10
  const inter = Inter({ subsets: ['latin', 'cyrillic'] })
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  export default function RootLayout({
13
  children,
14
  }: {
@@ -29,14 +56,16 @@ export default function RootLayout({
29
  children
30
  ) : (
31
  // App layout (with sidebar)
32
- <div className="flex h-screen bg-slate-100">
33
- <Sidebar />
34
-
35
- {/* Main Content Area */}
36
- <main className="flex-1 overflow-auto">
37
- {children}
38
- </main>
39
- </div>
 
 
40
  )}
41
  </Providers>
42
  </body>
 
7
  import { Sidebar } from '@/components/Sidebar'
8
  import { usePathname } from 'next/navigation'
9
 
10
+ import { useAuth } from '@/contexts/AuthContext'
11
+ import { useEffect } from 'react'
12
+ import { useRouter } from 'next/navigation'
13
+
14
  const inter = Inter({ subsets: ['latin', 'cyrillic'] })
15
 
16
+ function ProtectedLayout({ children }: { children: React.ReactNode }) {
17
+ const { user, isLoading } = useAuth()
18
+ const router = useRouter()
19
+
20
+ useEffect(() => {
21
+ if (!isLoading && !user) {
22
+ router.push('/login')
23
+ }
24
+ }, [isLoading, user, router])
25
+
26
+ if (isLoading) {
27
+ return (
28
+ <div className="flex h-screen items-center justify-center bg-slate-100">
29
+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
30
+ </div>
31
+ )
32
+ }
33
+
34
+ if (!user) return null
35
+
36
+ return <>{children}</>
37
+ }
38
+
39
  export default function RootLayout({
40
  children,
41
  }: {
 
56
  children
57
  ) : (
58
  // App layout (with sidebar)
59
+ <ProtectedLayout>
60
+ <div className="flex h-screen bg-slate-100">
61
+ <Sidebar />
62
+
63
+ {/* Main Content Area */}
64
+ <main className="flex-1 overflow-auto">
65
+ {children}
66
+ </main>
67
+ </div>
68
+ </ProtectedLayout>
69
  )}
70
  </Providers>
71
  </body>
frontend/app/settings/brain/page.tsx CHANGED
@@ -7,591 +7,591 @@ import { motion, AnimatePresence } from 'framer-motion'
7
  import { cn } from '@/lib/utils'
8
 
9
  interface AISettings {
10
- business_description: string
11
- selling_style: 'Consultative' | 'Aggressive' | 'Friendly' | 'Educational'
12
- custom_fields: string[]
13
- ideal_customer_profile: string
14
  }
15
 
16
  interface AIPersona {
17
- tone_of_voice: 'Professional' | 'Friendly' | 'Empathetic' | 'Bold'
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 = [
25
- { value: 'Professional', label: 'Профессиональный', icon: Shield, description: 'Деловой, формальный тон' },
26
- { value: 'Friendly', label: 'Дружелюбный', icon: Users, description: 'Теплый, неформальный' },
27
- { value: 'Empathetic', label: 'Эмпатичный', icon: Sparkles, description: 'Понимающий, заботливый' },
28
- { value: 'Bold', label: 'Уверенный', icon: Zap, description: 'Прямолинейный, смелый' }
29
  ]
30
 
31
  const METHODOLOGY_OPTIONS = [
32
- {
33
- value: 'SPIN',
34
- label: 'SPIN Selling',
35
- icon: Target,
36
- description: 'Ситуация → Проблема → Импликация → Выгода. Глубокие вопросы для понимания потребностей.'
37
- },
38
- {
39
- value: 'Sandler',
40
- label: 'Sandler System',
41
- icon: Award,
42
- description: 'Построение доверия, поиск боли, обсуждение бюджета рано. "Не продавай, помогай купить".'
43
- },
44
- {
45
- value: 'Challenger',
46
- label: 'Challenger Sale',
47
- icon: Zap,
48
- description: 'Учи клиента, бросай вызов мышлению, контролируй разговор. Для сложных продаж.'
49
- },
50
- {
51
- value: 'Consultative',
52
- label: 'Консультативные продажи',
53
- icon: Users,
54
- description: 'Будь советником. Выявляй потребности, предлагай решения. Долгосрочные отношения.'
55
- },
56
- {
57
- value: 'MEDDIC',
58
- label: 'MEDDIC',
59
- icon: BookOpen,
60
- description: 'Метрики, Покупатель, Критерии, Процесс, Боль, Чемпион. Для enterprise продаж.'
61
- }
62
  ]
63
 
64
  export default function BrainSettingsPage() {
65
- const { user } = useAuth()
66
- const [loading, setLoading] = useState(true)
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',
74
- custom_fields: ['Бюджет', 'Срочность', 'Статус решения'],
75
- ideal_customer_profile: ''
76
- })
77
-
78
- const [persona, setPersona] = useState<AIPersona>({
79
- tone_of_voice: 'Professional',
80
- sales_methodology: 'Consultative',
81
- custom_instructions: '',
82
- banned_words: [],
83
- manager_monthly_salary: 1000
84
- })
85
-
86
- useEffect(() => {
87
- if (user) {
88
- fetchSettings()
89
- }
90
- }, [user])
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',
126
- custom_instructions: data.custom_instructions || '',
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
  }
136
- }
137
 
138
- const handleSave = async () => {
139
- if (!user?.tenant_id) return
140
 
141
- const apiUrl = process.env.NEXT_PUBLIC_API_URL
142
- if (!apiUrl) {
143
- alert('❌ API URL не настроен')
144
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  }
146
 
147
- setSaving(true)
148
- try {
149
- const token = localStorage.getItem('auth_token')
150
- if (!token) {
151
- alert('❌ Нет токена авторизации')
152
- setSaving(false)
153
- return
154
- }
155
-
156
- const response = await fetch(`${apiUrl}/api/v1/tenants/${user.tenant_id}`, {
157
- method: 'PATCH',
158
- headers: {
159
- 'Authorization': `Bearer ${token}`,
160
- 'Content-Type': 'application/json'
161
- },
162
- body: JSON.stringify({
163
- ai_settings: settings,
164
- ...persona
165
  })
166
- })
167
-
168
- if (response.ok) {
169
- alert('✅ Настройки AI Brain сохранены!')
170
- } else {
171
- alert(`❌ Ошибка сохранения настроек: ${response.status}`)
172
- }
173
- } catch (error) {
174
- console.error('Failed to save AI settings:', error)
175
- alert('❌ Ошибка сохранения настроек')
176
- } finally {
177
- setSaving(false)
178
  }
179
- }
180
 
181
- const addCustomField = () => {
182
- if (!newField.trim()) return
183
- if (settings.custom_fields.includes(newField.trim())) {
184
- alert('Это поле уже добавлено')
185
- return
186
  }
187
 
188
- setSettings({
189
- ...settings,
190
- custom_fields: [...settings.custom_fields, newField.trim()]
191
- })
192
- setNewField('')
193
- }
194
 
195
- const removeCustomField = (field: string) => {
196
- setSettings({
197
- ...settings,
198
- custom_fields: settings.custom_fields.filter(f => f !== field)
199
- })
200
- }
201
 
202
- const addBannedWord = () => {
203
- if (!newBannedWord.trim()) return
204
- if (persona.banned_words.includes(newBannedWord.trim())) {
205
- alert('Это слово уже в списке')
206
- return
207
  }
208
 
209
- setPersona({
210
- ...persona,
211
- banned_words: [...persona.banned_words, newBannedWord.trim()]
212
- })
213
- setNewBannedWord('')
214
- }
 
215
 
216
- const removeBannedWord = (word: string) => {
217
- setPersona({
218
- ...persona,
219
- banned_words: persona.banned_words.filter(w => w !== word)
220
- })
221
- }
 
 
 
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-100 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
- )
597
  }
 
7
  import { cn } from '@/lib/utils'
8
 
9
  interface AISettings {
10
+ business_description: string
11
+ selling_style: 'Consultative' | 'Aggressive' | 'Friendly' | 'Educational'
12
+ custom_fields: string[]
13
+ ideal_customer_profile: string
14
  }
15
 
16
  interface AIPersona {
17
+ tone_of_voice: 'Professional' | 'Friendly' | 'Empathetic' | 'Bold'
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 = [
25
+ { value: 'Professional', label: 'Профессиональный', icon: Shield, description: 'Деловой, формальный тон' },
26
+ { value: 'Friendly', label: 'Дружелюбный', icon: Users, description: 'Теплый, неформальный' },
27
+ { value: 'Empathetic', label: 'Эмпатичный', icon: Sparkles, description: 'Понимающий, заботливый' },
28
+ { value: 'Bold', label: 'Уверенный', icon: Zap, description: 'Прямолинейный, смелый' }
29
  ]
30
 
31
  const METHODOLOGY_OPTIONS = [
32
+ {
33
+ value: 'SPIN',
34
+ label: 'SPIN Selling',
35
+ icon: Target,
36
+ description: 'Ситуация → Проблема → Импликация → Выгода. Глубокие вопросы для понимания потребностей.'
37
+ },
38
+ {
39
+ value: 'Sandler',
40
+ label: 'Sandler System',
41
+ icon: Award,
42
+ description: 'Построение доверия, поиск боли, обсуждение бюджета рано. "Не продавай, помогай купить".'
43
+ },
44
+ {
45
+ value: 'Challenger',
46
+ label: 'Challenger Sale',
47
+ icon: Zap,
48
+ description: 'Учи клиента, бросай вызов мышлению, контролируй разговор. Для сложных продаж.'
49
+ },
50
+ {
51
+ value: 'Consultative',
52
+ label: 'Консультативные продажи',
53
+ icon: Users,
54
+ description: 'Будь советником. Выявляй потребности, предлагай решения. Долгосрочные отношения.'
55
+ },
56
+ {
57
+ value: 'MEDDIC',
58
+ label: 'MEDDIC',
59
+ icon: BookOpen,
60
+ description: 'Метрики, Покупатель, Критерии, Процесс, Боль, Чемпион. Для enterprise продаж.'
61
+ }
62
  ]
63
 
64
  export default function BrainSettingsPage() {
65
+ const { user } = useAuth()
66
+ const [loading, setLoading] = useState(true)
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',
74
+ custom_fields: ['Бюджет', 'Срочность', 'Статус решения'],
75
+ ideal_customer_profile: ''
76
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
+ const [persona, setPersona] = useState<AIPersona>({
79
+ tone_of_voice: 'Professional',
80
+ sales_methodology: 'Consultative',
81
+ custom_instructions: '',
82
+ banned_words: [],
83
+ manager_monthly_salary: 1000
84
+ })
85
 
86
+ useEffect(() => {
87
+ if (user) {
88
+ fetchSettings()
89
+ }
90
+ }, [user])
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',
126
+ custom_instructions: data.custom_instructions || '',
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
  }
 
 
 
 
 
 
 
 
 
 
 
 
136
  }
 
137
 
138
+ const handleSave = async () => {
139
+ if (!user?.tenant_id) return
140
 
141
+ const apiUrl = process.env.NEXT_PUBLIC_API_URL
142
+ if (!apiUrl) {
143
+ alert('❌ API URL не настроен')
144
+ return
145
+ }
146
+
147
+ setSaving(true)
148
+ try {
149
+ const token = localStorage.getItem('auth_token')
150
+ if (!token) {
151
+ alert('❌ Нет токена авторизации')
152
+ setSaving(false)
153
+ return
154
+ }
155
+
156
+ const response = await fetch(`${apiUrl}/api/v1/tenants/${user.tenant_id}`, {
157
+ method: 'PATCH',
158
+ headers: {
159
+ 'Authorization': `Bearer ${token}`,
160
+ 'Content-Type': 'application/json'
161
+ },
162
+ body: JSON.stringify({
163
+ ai_settings: settings,
164
+ ...persona
165
+ })
166
+ })
167
+
168
+ if (response.ok) {
169
+ alert('✅ Настройки AI Brain сохранены!')
170
+ } else {
171
+ alert(`❌ Ошибка сохранения настроек: ${response.status}`)
172
+ }
173
+ } catch (error) {
174
+ console.error('Failed to save AI settings:', error)
175
+ alert('❌ Ошибка сохранения настроек')
176
+ } finally {
177
+ setSaving(false)
178
+ }
179
  }
180
 
181
+ const addCustomField = () => {
182
+ if (!newField.trim()) return
183
+ if (settings.custom_fields.includes(newField.trim())) {
184
+ alert('Это поле уже добавлено')
185
+ return
186
+ }
187
+
188
+ setSettings({
189
+ ...settings,
190
+ custom_fields: [...settings.custom_fields, newField.trim()]
 
 
 
 
 
 
 
 
191
  })
192
+ setNewField('')
 
 
 
 
 
 
 
 
 
 
 
193
  }
 
194
 
195
+ const removeCustomField = (field: string) => {
196
+ setSettings({
197
+ ...settings,
198
+ custom_fields: settings.custom_fields.filter(f => f !== field)
199
+ })
200
  }
201
 
202
+ const addBannedWord = () => {
203
+ if (!newBannedWord.trim()) return
204
+ if (persona.banned_words.includes(newBannedWord.trim())) {
205
+ alert('Это слово уже в списке')
206
+ return
207
+ }
208
 
209
+ setPersona({
210
+ ...persona,
211
+ banned_words: [...persona.banned_words, newBannedWord.trim()]
212
+ })
213
+ setNewBannedWord('')
214
+ }
215
 
216
+ const removeBannedWord = (word: string) => {
217
+ setPersona({
218
+ ...persona,
219
+ banned_words: persona.banned_words.filter(w => w !== word)
220
+ })
221
  }
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-100 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
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597
  }
frontend/app/settings/brain/page_advanced.tsx CHANGED
@@ -226,8 +226,8 @@ export default function BrainSettingsPage() {
226
  key={tone.value}
227
  onClick={() => setPersona({ ...persona, tone_of_voice: tone.value as any })}
228
  className={`p-4 rounded-lg border-2 transition-all duration-200 text-left ${persona.tone_of_voice === tone.value
229
- ? 'border-indigo-600 bg-indigo-50'
230
- : 'border-gray-200 hover:border-indigo-300 bg-white'
231
  }`}
232
  >
233
  <div className="flex items-center gap-2 mb-1">
@@ -260,8 +260,8 @@ export default function BrainSettingsPage() {
260
  key={method.value}
261
  onClick={() => setPersona({ ...persona, sales_methodology: method.value as any })}
262
  className={`w-full p-4 rounded-lg border-2 transition-all duration-200 text-left ${persona.sales_methodology === method.value
263
- ? 'border-purple-600 bg-purple-50'
264
- : 'border-gray-200 hover:border-purple-300 bg-white'
265
  }`}
266
  >
267
  <div className="flex items-start gap-3">
 
226
  key={tone.value}
227
  onClick={() => setPersona({ ...persona, tone_of_voice: tone.value as any })}
228
  className={`p-4 rounded-lg border-2 transition-all duration-200 text-left ${persona.tone_of_voice === tone.value
229
+ ? 'border-indigo-600 bg-indigo-50'
230
+ : 'border-gray-200 hover:border-indigo-300 bg-white'
231
  }`}
232
  >
233
  <div className="flex items-center gap-2 mb-1">
 
260
  key={method.value}
261
  onClick={() => setPersona({ ...persona, sales_methodology: method.value as any })}
262
  className={`w-full p-4 rounded-lg border-2 transition-all duration-200 text-left ${persona.sales_methodology === method.value
263
+ ? 'border-purple-600 bg-purple-50'
264
+ : 'border-gray-200 hover:border-purple-300 bg-white'
265
  }`}
266
  >
267
  <div className="flex items-start gap-3">
frontend/app/settings/crm/page.tsx CHANGED
@@ -3,599 +3,599 @@
3
  import { useEffect, useState } from 'react'
4
  import { useAuth } from '@/contexts/AuthContext'
5
  import {
6
- Save, Loader2, AlertCircle, CheckCircle2, Plus, Trash2,
7
- RefreshCw, Settings, Database, Zap, ChevronDown, Eye, EyeOff,
8
- Webhook
9
  } from 'lucide-react'
10
 
11
  interface CRMIntegration {
12
- id: string
13
- crm_type: string
14
- integration_name: string
15
- sync_direction: string
16
- auto_sync: boolean
17
- sync_interval_minutes: number
18
- sync_only_hot_leads: boolean
19
- sync_statuses: string[] | null
20
- status: string
21
- is_active: boolean
22
- last_sync_at: string | null
23
- total_synced_leads: number
24
- failed_sync_count: number
25
  }
26
 
27
  const CRM_TYPES = [
28
- { value: 'amocrm', label: 'amoCRM' },
29
- { value: 'bitrix24', label: 'Bitrix24' },
30
- { value: 'hubspot', label: 'HubSpot' },
31
- { value: 'pipedrive', label: 'Pipedrive' },
32
- { value: 'salesforce', label: 'Salesforce' },
33
- { value: 'zoho', label: 'Zoho CRM' },
34
- { value: 'custom_webhook', label: 'Custom Webhook' }
35
  ]
36
 
37
  const LEAD_STATUSES = [
38
- { value: 'new', label: 'Новый' },
39
- { value: 'qualified', label: 'Квалифицирован' },
40
- { value: 'in_progress', label: 'В работе' },
41
- { value: 'closed_won', label: 'Закрыт успешно' },
42
- { value: 'closed_lost', label: 'Закрыт неудачно' }
43
  ]
44
 
45
  export default function CRMSettingsPage() {
46
- const { user } = useAuth()
47
- const [loading, setLoading] = useState(true)
48
- const [saving, setSaving] = useState(false)
49
- const [integrations, setIntegrations] = useState<CRMIntegration[]>([])
50
- const [showAddForm, setShowAddForm] = useState(false)
51
- const [successMessage, setSuccessMessage] = useState('')
52
- const [errorMessage, setErrorMessage] = useState('')
53
- const [showTokens, setShowTokens] = useState<{ [key: string]: boolean }>({})
54
-
55
- // New integration form
56
- const [newIntegration, setNewIntegration] = useState({
57
- crm_type: 'amocrm',
58
- integration_name: '',
59
- api_url: '',
60
- access_token: '',
61
- webhook_url: '',
62
- webhook_secret: '',
63
- auto_sync: true,
64
- sync_interval_minutes: 15,
65
- sync_only_hot_leads: true,
66
- sync_statuses: ['new', 'qualified', 'in_progress'],
67
- field_mapping: {}
68
- })
69
-
70
- useEffect(() => {
71
- fetchIntegrations()
72
- }, [])
73
-
74
- const fetchIntegrations = async () => {
75
- const token = localStorage.getItem('auth_token')
76
- if (!token || !user?.tenant_id) return
77
-
78
- try {
79
- const response = await fetch(
80
- `${process.env.NEXT_PUBLIC_API_URL}/api/v1/crm/${user.tenant_id}/integrations`,
81
- {
82
- headers: { 'Authorization': `Bearer ${token}` }
 
 
 
 
 
 
 
 
 
 
 
83
  }
84
- )
85
-
86
- if (response.ok) {
87
- const data = await response.json()
88
- setIntegrations(data)
89
- }
90
- } catch (error) {
91
- console.error('Failed to fetch integrations:', error)
92
- } finally {
93
- setLoading(false)
94
  }
95
- }
96
-
97
- const handleCreateIntegration = async () => {
98
- const token = localStorage.getItem('auth_token')
99
- if (!token || !user?.tenant_id) return
100
-
101
- setSaving(true)
102
- setErrorMessage('')
103
-
104
- try {
105
- const response = await fetch(
106
- `${process.env.NEXT_PUBLIC_API_URL}/api/v1/crm/${user.tenant_id}/integrations`,
107
- {
108
- method: 'POST',
109
- headers: {
110
- 'Authorization': `Bearer ${token}`,
111
- 'Content-Type': 'application/json'
112
- },
113
- body: JSON.stringify(newIntegration)
114
- }
115
- )
116
 
117
- if (response.ok) {
118
- setSuccessMessage('Интеграция создана успешно!')
119
- setShowAddForm(false)
120
- fetchIntegrations()
121
- // Reset form
122
- setNewIntegration({
123
- crm_type: 'amocrm',
124
- integration_name: '',
125
- api_url: '',
126
- access_token: '',
127
- webhook_url: '',
128
- webhook_secret: '',
129
- auto_sync: true,
130
- sync_interval_minutes: 15,
131
- sync_only_hot_leads: true,
132
- sync_statuses: ['new', 'qualified', 'in_progress'],
133
- field_mapping: {}
134
- })
135
- setTimeout(() => setSuccessMessage(''), 3000)
136
- } else {
137
- const error = await response.json()
138
- setErrorMessage(error.detail || 'Ошибка создания интеграции')
139
- }
140
- } catch (error) {
141
- setErrorMessage('Ошибка подключения к серверу')
142
- } finally {
143
- setSaving(false)
144
- }
145
- }
146
-
147
- const handleUpdateIntegration = async (id: string, updates: any) => {
148
- const token = localStorage.getItem('auth_token')
149
- if (!token || !user?.tenant_id) return
150
-
151
- try {
152
- const response = await fetch(
153
- `${process.env.NEXT_PUBLIC_API_URL}/api/v1/crm/${user.tenant_id}/integrations/${id}`,
154
- {
155
- method: 'PATCH',
156
- headers: {
157
- 'Authorization': `Bearer ${token}`,
158
- 'Content-Type': 'application/json'
159
- },
160
- body: JSON.stringify(updates)
 
 
 
161
  }
162
- )
163
-
164
- if (response.ok) {
165
- setSuccessMessage('Настройки обновлены!')
166
- fetchIntegrations()
167
- setTimeout(() => setSuccessMessage(''), 3000)
168
- }
169
- } catch (error) {
170
- console.error('Failed to update integration:', error)
171
  }
172
- }
173
-
174
- const handleDeleteIntegration = async (id: string) => {
175
- if (!confirm('Удалить интеграцию?')) return
176
-
177
- const token = localStorage.getItem('auth_token')
178
- if (!token || !user?.tenant_id) return
179
 
180
- try {
181
- const response = await fetch(
182
- `${process.env.NEXT_PUBLIC_API_URL}/api/v1/crm/${user.tenant_id}/integrations/${id}`,
183
- {
184
- method: 'DELETE',
185
- headers: { 'Authorization': `Bearer ${token}` }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  }
187
- )
188
 
189
- if (response.ok) {
190
- setSuccessMessage('Интеграция удалена')
191
- fetchIntegrations()
192
- setTimeout(() => setSuccessMessage(''), 3000)
193
- }
194
- } catch (error) {
195
- console.error('Failed to delete integration:', error)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  }
197
- }
198
 
199
- const getCRMIcon = (type: string) => {
200
- if (type === 'custom_webhook') return <Webhook className="w-8 h-8 text-indigo-600" />
201
- return <Database className="w-8 h-8 text-indigo-600" />
202
- }
203
 
204
- const getCRMLabel = (type: string) => {
205
- return CRM_TYPES.find(t => t.value === type)?.label || type
206
- }
207
 
208
- if (loading) {
209
- return (
210
- <div className="flex items-center justify-center h-screen">
211
- <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
212
- </div>
213
- )
214
- }
215
-
216
- return (
217
- <div className="min-h-screen bg-slate-100">
218
- <div className="max-w-6xl mx-auto p-8">
219
- {/* Header */}
220
- <div className="mb-8">
221
- <div className="flex items-center justify-between">
222
- <div>
223
- <h1 className="text-3xl font-bold text-slate-900 mb-2 flex items-center gap-3">
224
- <Database className="w-8 h-8 text-indigo-600" />
225
- Интеграция с CRM
226
- </h1>
227
- <p className="text-slate-600">
228
- Автоматическая синхронизация лидов с внешними CRM системами
229
- </p>
230
  </div>
231
- <button
232
- onClick={() => setShowAddForm(!showAddForm)}
233
- className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-colors shadow-lg shadow-indigo-500/20"
234
- >
235
- <Plus className="w-4 h-4" />
236
- Добавить интеграцию
237
- </button>
238
- </div>
239
- </div>
240
-
241
- {/* Success/Error Messages */}
242
- {successMessage && (
243
- <div className="mb-6 p-4 bg-green-50 border border-green-200 rounded-xl flex items-center gap-3">
244
- <CheckCircle2 className="w-5 h-5 text-green-600" />
245
- <p className="text-green-800">{successMessage}</p>
246
- </div>
247
- )}
248
-
249
- {errorMessage && (
250
- <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-xl flex items-center gap-3">
251
- <AlertCircle className="w-5 h-5 text-red-600" />
252
- <p className="text-red-800">{errorMessage}</p>
253
- </div>
254
- )}
255
-
256
- {/* Add New Integration Form */}
257
- {showAddForm && (
258
- <div className="mb-8 bg-white rounded-xl shadow-lg p-6 border border-slate-200">
259
- <h2 className="text-xl font-bold text-slate-900 mb-6">Новая интеграция</h2>
260
-
261
- <div className="space-y-6">
262
- {/* CRM Type */}
263
- <div>
264
- <label className="block text-sm font-semibold text-slate-700 mb-2">
265
- Тип CRM системы
266
- </label>
267
- <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
268
- {CRM_TYPES.map(type => (
269
- <button
270
- key={type.value}
271
- onClick={() => setNewIntegration({ ...newIntegration, crm_type: type.value })}
272
- className={`p-3 rounded-xl border text-left transition-all ${newIntegration.crm_type === type.value
273
- ? 'border-indigo-600 bg-indigo-50 ring-2 ring-indigo-500/20'
274
- : 'border-slate-200 hover:border-indigo-300 hover:bg-slate-50'
275
- }`}
276
- >
277
- <div className="font-medium text-slate-900">{type.label}</div>
278
- </button>
279
- ))}
280
- </div>
281
- </div>
282
-
283
- {/* Integration Name */}
284
- <div>
285
- <label className="block text-sm font-semibold text-slate-700 mb-2">
286
- Название интеграции
287
- </label>
288
- <input
289
- type="text"
290
- value={newIntegration.integration_name}
291
- onChange={(e) => setNewIntegration({ ...newIntegration, integration_name: e.target.value })}
292
- placeholder="Например: Основная amoCRM"
293
- className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
294
- />
295
- </div>
296
-
297
- {/* API URL (for amoCRM, HubSpot, etc.) */}
298
- {!['custom_webhook'].includes(newIntegration.crm_type) && (
299
- <div>
300
- <label className="block text-sm font-semibold text-slate-700 mb-2">
301
- API URL
302
- </label>
303
- <input
304
- type="text"
305
- value={newIntegration.api_url}
306
- onChange={(e) => setNewIntegration({ ...newIntegration, api_url: e.target.value })}
307
- placeholder={
308
- newIntegration.crm_type === 'amocrm' ? 'https://yourcompany.amocrm.ru' :
309
- newIntegration.crm_type === 'hubspot' ? 'https://api.hubapi.com' :
310
- 'https://yourinstance.salesforce.com'
311
- }
312
- className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
313
- />
314
- </div>
315
- )}
316
-
317
- {/* Access Token */}
318
- {!['bitrix24', 'custom_webhook'].includes(newIntegration.crm_type) && (
319
- <div>
320
- <label className="block text-sm font-semibold text-slate-700 mb-2">
321
- Access Token / API Key
322
- </label>
323
- <div className="relative">
324
- <input
325
- type={showTokens['new'] ? 'text' : 'password'}
326
- value={newIntegration.access_token}
327
- onChange={(e) => setNewIntegration({ ...newIntegration, access_token: e.target.value })}
328
- placeholder="Введите токен доступа"
329
- className="w-full px-4 py-3 pr-12 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent font-mono text-sm"
330
- />
331
- <button
332
- type="button"
333
- onClick={() => setShowTokens({ ...showTokens, new: !showTokens['new'] })}
334
- className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
335
- >
336
- {showTokens['new'] ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
337
- </button>
338
- </div>
339
- </div>
340
- )}
341
-
342
- {/* Webhook URL (for Bitrix24 and Custom) */}
343
- {['bitrix24', 'custom_webhook'].includes(newIntegration.crm_type) && (
344
- <div>
345
- <label className="block text-sm font-semibold text-slate-700 mb-2">
346
- Webhook URL
347
- </label>
348
- <input
349
- type="text"
350
- value={newIntegration.webhook_url}
351
- onChange={(e) => setNewIntegration({ ...newIntegration, webhook_url: e.target.value })}
352
- placeholder={
353
- newIntegration.crm_type === 'bitrix24'
354
- ? 'https://yourcompany.bitrix24.ru/rest/1/abc123xyz/'
355
- : 'https://your-crm.com/api/webhook'
356
- }
357
- className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
358
- />
359
- </div>
360
- )}
361
-
362
- {/* Auto Sync Settings */}
363
- <div className="bg-slate-50 rounded-xl p-6 space-y-4">
364
- <h3 className="font-semibold text-slate-900 flex items-center gap-2">
365
- <Zap className="w-5 h-5 text-yellow-500" />
366
- Настройки автосинхронизации
367
- </h3>
368
-
369
- {/* Auto Sync Toggle */}
370
- <div className="flex items-center justify-between">
371
- <div>
372
- <label className="text-sm font-medium text-slate-700">Автоматическая синхронизация</label>
373
- <p className="text-xs text-slate-500">Синхронизировать лиды автоматически при обновлении</p>
374
- </div>
375
- <label className="relative inline-flex items-center cursor-pointer">
376
- <input
377
- type="checkbox"
378
- checked={newIntegration.auto_sync}
379
- onChange={(e) => setNewIntegration({ ...newIntegration, auto_sync: e.target.checked })}
380
- className="sr-only peer"
381
- />
382
- <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
383
- </label>
384
- </div>
385
-
386
- {/* Sync Only Hot Leads */}
387
- <div className="flex items-center justify-between">
388
- <div>
389
- <label className="text-sm font-medium text-slate-700">Только горячие лиды</label>
390
- <p className="text-xs text-slate-500">Синхронизировать только лиды с heat_score ≥ 70</p>
391
- </div>
392
- <label className="relative inline-flex items-center cursor-pointer">
393
- <input
394
- type="checkbox"
395
- checked={newIntegration.sync_only_hot_leads}
396
- onChange={(e) => setNewIntegration({ ...newIntegration, sync_only_hot_leads: e.target.checked })}
397
- className="sr-only peer"
398
- />
399
- <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
400
- </label>
401
- </div>
402
-
403
- {/* Sync Interval */}
404
- <div>
405
- <label className="block text-sm font-medium text-slate-700 mb-2">
406
- Интервал синхронизации (минуты)
407
- </label>
408
- <select
409
- value={newIntegration.sync_interval_minutes}
410
- onChange={(e) => setNewIntegration({ ...newIntegration, sync_interval_minutes: parseInt(e.target.value) })}
411
- className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
412
- >
413
- <option value={5}>5 минут</option>
414
- <option value={15}>15 минут</option>
415
- <option value={30}>30 минут</option>
416
- <option value={60}>1 час</option>
417
- <option value={360}>6 часов</option>
418
- <option value={1440}>24 часа</option>
419
- </select>
420
- </div>
421
 
422
- {/* Sync Statuses */}
423
- <div>
424
- <label className="block text-sm font-medium text-slate-700 mb-2">
425
- Синхронизировать лиды со статусами:
426
- </label>
427
- <div className="grid grid-cols-2 gap-3">
428
- {LEAD_STATUSES.map(status => (
429
- <label key={status.value} className="flex items-center gap-2 cursor-pointer">
430
- <input
431
- type="checkbox"
432
- checked={newIntegration.sync_statuses.includes(status.value)}
433
- onChange={(e) => {
434
- if (e.target.checked) {
435
- setNewIntegration({
436
- ...newIntegration,
437
- sync_statuses: [...newIntegration.sync_statuses, status.value]
438
- })
439
- } else {
440
- setNewIntegration({
441
- ...newIntegration,
442
- sync_statuses: newIntegration.sync_statuses.filter(s => s !== status.value)
443
- })
444
- }
445
- }}
446
- className="w-4 h-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"
447
- />
448
- <span className="text-sm text-slate-700">{status.label}</span>
449
- </label>
450
- ))}
451
- </div>
452
- </div>
453
- </div>
454
-
455
- {/* Action Buttons */}
456
- <div className="flex gap-3">
457
- <button
458
- onClick={handleCreateIntegration}
459
- disabled={saving || !newIntegration.integration_name}
460
- className="flex-1 flex items-center justify-center gap-2 px-6 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
461
- >
462
- {saving ? (
463
- <>
464
- <Loader2 className="w-5 h-5 animate-spin" />
465
- Сохранение...
466
- </>
467
- ) : (
468
- <>
469
- <Save className="w-5 h-5" />
470
- Создать интеграцию
471
- </>
472
- )}
473
- </button>
474
- <button
475
- onClick={() => setShowAddForm(false)}
476
- className="px-6 py-3 border border-slate-300 text-slate-700 rounded-xl hover:bg-slate-50 transition-colors font-medium"
477
- >
478
- Отмена
479
- </button>
480
- </div>
481
- </div>
482
- </div>
483
- )}
484
-
485
- {/* Existing Integrations */}
486
- <div className="space-y-4">
487
- {integrations.length === 0 ? (
488
- <div className="bg-white rounded-xl shadow-lg p-12 text-center border border-slate-200">
489
- <Database className="w-16 h-16 text-slate-300 mx-auto mb-4" />
490
- <h3 className="text-xl font-semibold text-slate-900 mb-2">
491
- Нет активных интеграций
492
- </h3>
493
- <p className="text-slate-600 mb-6">
494
- Добавьте интеграцию с CRM системой для автоматической синхронизации лидов
495
- </p>
496
- <button
497
- onClick={() => setShowAddForm(true)}
498
- className="inline-flex items-center gap-2 px-6 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-colors font-medium"
499
- >
500
- <Plus className="w-5 h-5" />
501
- Добавить первую интеграцию
502
- </button>
503
- </div>
504
- ) : (
505
- integrations.map(integration => (
506
- <div key={integration.id} className="bg-white rounded-xl shadow-lg p-6 border border-slate-200">
507
- <div className="flex items-start justify-between mb-4">
508
- <div className="flex items-center gap-3">
509
- <div className="p-2 bg-indigo-50 rounded-lg border border-indigo-100">{getCRMIcon(integration.crm_type)}</div>
510
- <div>
511
- <h3 className="text-lg font-bold text-slate-900">{integration.integration_name}</h3>
512
- <p className="text-sm text-slate-600">{getCRMLabel(integration.crm_type)}</p>
513
  </div>
514
- </div>
515
- <div className="flex items-center gap-2">
516
- <span className={`px-3 py-1 rounded-full text-xs font-medium ${integration.status === 'active' ? 'bg-green-100 text-green-700' :
517
- integration.status === 'paused' ? 'bg-yellow-100 text-yellow-700' :
518
- 'bg-red-100 text-red-700'
519
- }`}>
520
- {integration.status === 'active' ? 'Активна' :
521
- integration.status === 'paused' ? 'Приостановлена' : 'Ошибка'}
522
- </span>
523
- <button
524
- onClick={() => handleDeleteIntegration(integration.id)}
525
- className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
526
- >
527
- <Trash2 className="w-4 h-4" />
528
- </button>
529
- </div>
530
  </div>
531
 
532
- {/* Stats */}
533
- <div className="grid grid-cols-3 gap-4 mb-4">
534
- <div className="bg-slate-50 rounded-lg p-3">
535
- <p className="text-xs text-slate-600 mb-1">Синхронизировано</p>
536
- <p className="text-2xl font-bold text-slate-900">{integration.total_synced_leads}</p>
537
- </div>
538
- <div className="bg-slate-50 rounded-lg p-3">
539
- <p className="text-xs text-slate-600 mb-1">Ошибок</p>
540
- <p className="text-2xl font-bold text-red-600">{integration.failed_sync_count}</p>
541
- </div>
542
- <div className="bg-slate-50 rounded-lg p-3">
543
- <p className="text-xs text-slate-600 mb-1">Последняя синхр.</p>
544
- <p className="text-sm font-medium text-slate-700">
545
- {integration.last_sync_at
546
- ? new Date(integration.last_sync_at).toLocaleString('ru-RU')
547
- : 'Не было'
548
- }
549
- </p>
550
- </div>
551
- </div>
552
 
553
- {/* Settings */}
554
- <div className="space-y-3">
555
- <div className="flex items-center justify-between">
556
- <span className="text-sm text-slate-700">Автосинхронизация</span>
557
- <label className="relative inline-flex items-center cursor-pointer">
558
- <input
559
- type="checkbox"
560
- checked={integration.auto_sync}
561
- onChange={(e) => handleUpdateIntegration(integration.id, { auto_sync: e.target.checked })}
562
- className="sr-only peer"
563
- />
564
- <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
565
- </label>
566
- </div>
567
-
568
- <div className="flex items-center justify-between">
569
- <span className="text-sm text-slate-700">Только горячие лиды</span>
570
- <label className="relative inline-flex items-center cursor-pointer">
571
- <input
572
- type="checkbox"
573
- checked={integration.sync_only_hot_leads}
574
- onChange={(e) => handleUpdateIntegration(integration.id, { sync_only_hot_leads: e.target.checked })}
575
- className="sr-only peer"
576
- />
577
- <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
578
- </label>
579
- </div>
580
-
581
- <div className="flex items-center justify-between">
582
- <span className="text-sm text-slate-700">Активна</span>
583
- <label className="relative inline-flex items-center cursor-pointer">
584
- <input
585
- type="checkbox"
586
- checked={integration.is_active}
587
- onChange={(e) => handleUpdateIntegration(integration.id, { is_active: e.target.checked })}
588
- className="sr-only peer"
589
- />
590
- <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
591
- </label>
592
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593
  </div>
594
- </div>
595
- ))
596
- )}
597
  </div>
598
- </div>
599
- </div>
600
- )
601
  }
 
3
  import { useEffect, useState } from 'react'
4
  import { useAuth } from '@/contexts/AuthContext'
5
  import {
6
+ Save, Loader2, AlertCircle, CheckCircle2, Plus, Trash2,
7
+ RefreshCw, Settings, Database, Zap, ChevronDown, Eye, EyeOff,
8
+ Webhook
9
  } from 'lucide-react'
10
 
11
  interface CRMIntegration {
12
+ id: string
13
+ crm_type: string
14
+ integration_name: string
15
+ sync_direction: string
16
+ auto_sync: boolean
17
+ sync_interval_minutes: number
18
+ sync_only_hot_leads: boolean
19
+ sync_statuses: string[] | null
20
+ status: string
21
+ is_active: boolean
22
+ last_sync_at: string | null
23
+ total_synced_leads: number
24
+ failed_sync_count: number
25
  }
26
 
27
  const CRM_TYPES = [
28
+ { value: 'amocrm', label: 'amoCRM' },
29
+ { value: 'bitrix24', label: 'Bitrix24' },
30
+ { value: 'hubspot', label: 'HubSpot' },
31
+ { value: 'pipedrive', label: 'Pipedrive' },
32
+ { value: 'salesforce', label: 'Salesforce' },
33
+ { value: 'zoho', label: 'Zoho CRM' },
34
+ { value: 'custom_webhook', label: 'Custom Webhook' }
35
  ]
36
 
37
  const LEAD_STATUSES = [
38
+ { value: 'new', label: 'Новый' },
39
+ { value: 'qualified', label: 'Квалифицирован' },
40
+ { value: 'in_progress', label: 'В работе' },
41
+ { value: 'closed_won', label: 'Закрыт успешно' },
42
+ { value: 'closed_lost', label: 'Закрыт неудачно' }
43
  ]
44
 
45
  export default function CRMSettingsPage() {
46
+ const { user } = useAuth()
47
+ const [loading, setLoading] = useState(true)
48
+ const [saving, setSaving] = useState(false)
49
+ const [integrations, setIntegrations] = useState<CRMIntegration[]>([])
50
+ const [showAddForm, setShowAddForm] = useState(false)
51
+ const [successMessage, setSuccessMessage] = useState('')
52
+ const [errorMessage, setErrorMessage] = useState('')
53
+ const [showTokens, setShowTokens] = useState<{ [key: string]: boolean }>({})
54
+
55
+ // New integration form
56
+ const [newIntegration, setNewIntegration] = useState({
57
+ crm_type: 'amocrm',
58
+ integration_name: '',
59
+ api_url: '',
60
+ access_token: '',
61
+ webhook_url: '',
62
+ webhook_secret: '',
63
+ auto_sync: true,
64
+ sync_interval_minutes: 15,
65
+ sync_only_hot_leads: true,
66
+ sync_statuses: ['new', 'qualified', 'in_progress'],
67
+ field_mapping: {}
68
+ })
69
+
70
+ useEffect(() => {
71
+ fetchIntegrations()
72
+ }, [])
73
+
74
+ const fetchIntegrations = async () => {
75
+ const token = localStorage.getItem('auth_token')
76
+ if (!token || !user?.tenant_id) return
77
+
78
+ try {
79
+ const response = await fetch(
80
+ `${process.env.NEXT_PUBLIC_API_URL}/api/v1/crm/${user.tenant_id}/integrations`,
81
+ {
82
+ headers: { 'Authorization': `Bearer ${token}` }
83
+ }
84
+ )
85
+
86
+ if (response.ok) {
87
+ const data = await response.json()
88
+ setIntegrations(data)
89
+ }
90
+ } catch (error) {
91
+ console.error('Failed to fetch integrations:', error)
92
+ } finally {
93
+ setLoading(false)
94
  }
 
 
 
 
 
 
 
 
 
 
95
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ const handleCreateIntegration = async () => {
98
+ const token = localStorage.getItem('auth_token')
99
+ if (!token || !user?.tenant_id) return
100
+
101
+ setSaving(true)
102
+ setErrorMessage('')
103
+
104
+ try {
105
+ const response = await fetch(
106
+ `${process.env.NEXT_PUBLIC_API_URL}/api/v1/crm/${user.tenant_id}/integrations`,
107
+ {
108
+ method: 'POST',
109
+ headers: {
110
+ 'Authorization': `Bearer ${token}`,
111
+ 'Content-Type': 'application/json'
112
+ },
113
+ body: JSON.stringify(newIntegration)
114
+ }
115
+ )
116
+
117
+ if (response.ok) {
118
+ setSuccessMessage('Интеграция создана успешно!')
119
+ setShowAddForm(false)
120
+ fetchIntegrations()
121
+ // Reset form
122
+ setNewIntegration({
123
+ crm_type: 'amocrm',
124
+ integration_name: '',
125
+ api_url: '',
126
+ access_token: '',
127
+ webhook_url: '',
128
+ webhook_secret: '',
129
+ auto_sync: true,
130
+ sync_interval_minutes: 15,
131
+ sync_only_hot_leads: true,
132
+ sync_statuses: ['new', 'qualified', 'in_progress'],
133
+ field_mapping: {}
134
+ })
135
+ setTimeout(() => setSuccessMessage(''), 3000)
136
+ } else {
137
+ const error = await response.json()
138
+ setErrorMessage(error.detail || 'Ошибка создания интеграции')
139
+ }
140
+ } catch (error) {
141
+ setErrorMessage('Ошибка подключения к серверу')
142
+ } finally {
143
+ setSaving(false)
144
  }
 
 
 
 
 
 
 
 
 
145
  }
 
 
 
 
 
 
 
146
 
147
+ const handleUpdateIntegration = async (id: string, updates: any) => {
148
+ const token = localStorage.getItem('auth_token')
149
+ if (!token || !user?.tenant_id) return
150
+
151
+ try {
152
+ const response = await fetch(
153
+ `${process.env.NEXT_PUBLIC_API_URL}/api/v1/crm/${user.tenant_id}/integrations/${id}`,
154
+ {
155
+ method: 'PATCH',
156
+ headers: {
157
+ 'Authorization': `Bearer ${token}`,
158
+ 'Content-Type': 'application/json'
159
+ },
160
+ body: JSON.stringify(updates)
161
+ }
162
+ )
163
+
164
+ if (response.ok) {
165
+ setSuccessMessage('Настройки обновлены!')
166
+ fetchIntegrations()
167
+ setTimeout(() => setSuccessMessage(''), 3000)
168
+ }
169
+ } catch (error) {
170
+ console.error('Failed to update integration:', error)
171
  }
172
+ }
173
 
174
+ const handleDeleteIntegration = async (id: string) => {
175
+ if (!confirm('Удалить интеграцию?')) return
176
+
177
+ const token = localStorage.getItem('auth_token')
178
+ if (!token || !user?.tenant_id) return
179
+
180
+ try {
181
+ const response = await fetch(
182
+ `${process.env.NEXT_PUBLIC_API_URL}/api/v1/crm/${user.tenant_id}/integrations/${id}`,
183
+ {
184
+ method: 'DELETE',
185
+ headers: { 'Authorization': `Bearer ${token}` }
186
+ }
187
+ )
188
+
189
+ if (response.ok) {
190
+ setSuccessMessage('Интеграция удалена')
191
+ fetchIntegrations()
192
+ setTimeout(() => setSuccessMessage(''), 3000)
193
+ }
194
+ } catch (error) {
195
+ console.error('Failed to delete integration:', error)
196
+ }
197
  }
 
198
 
199
+ const getCRMIcon = (type: string) => {
200
+ if (type === 'custom_webhook') return <Webhook className="w-8 h-8 text-indigo-600" />
201
+ return <Database className="w-8 h-8 text-indigo-600" />
202
+ }
203
 
204
+ const getCRMLabel = (type: string) => {
205
+ return CRM_TYPES.find(t => t.value === type)?.label || type
206
+ }
207
 
208
+ if (loading) {
209
+ return (
210
+ <div className="flex items-center justify-center h-screen">
211
+ <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  </div>
213
+ )
214
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
+ return (
217
+ <div className="min-h-screen bg-slate-100">
218
+ <div className="max-w-6xl mx-auto p-8">
219
+ {/* Header */}
220
+ <div className="mb-8">
221
+ <div className="flex items-center justify-between">
222
+ <div>
223
+ <h1 className="text-3xl font-bold text-slate-900 mb-2 flex items-center gap-3">
224
+ <Database className="w-8 h-8 text-indigo-600" />
225
+ Интеграция с CRM
226
+ </h1>
227
+ <p className="text-slate-600">
228
+ Автоматическая синхронизация лидов с внешними CRM системами
229
+ </p>
230
+ </div>
231
+ <button
232
+ onClick={() => setShowAddForm(!showAddForm)}
233
+ className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-colors shadow-lg shadow-indigo-500/20"
234
+ >
235
+ <Plus className="w-4 h-4" />
236
+ Добавить интеграцию
237
+ </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  </div>
240
 
241
+ {/* Success/Error Messages */}
242
+ {successMessage && (
243
+ <div className="mb-6 p-4 bg-green-50 border border-green-200 rounded-xl flex items-center gap-3">
244
+ <CheckCircle2 className="w-5 h-5 text-green-600" />
245
+ <p className="text-green-800">{successMessage}</p>
246
+ </div>
247
+ )}
 
 
 
 
 
 
 
 
 
 
 
 
 
248
 
249
+ {errorMessage && (
250
+ <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-xl flex items-center gap-3">
251
+ <AlertCircle className="w-5 h-5 text-red-600" />
252
+ <p className="text-red-800">{errorMessage}</p>
253
+ </div>
254
+ )}
255
+
256
+ {/* Add New Integration Form */}
257
+ {showAddForm && (
258
+ <div className="mb-8 bg-white rounded-xl shadow-lg p-6 border border-slate-200">
259
+ <h2 className="text-xl font-bold text-slate-900 mb-6">Новая интеграция</h2>
260
+
261
+ <div className="space-y-6">
262
+ {/* CRM Type */}
263
+ <div>
264
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
265
+ Тип CRM системы
266
+ </label>
267
+ <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
268
+ {CRM_TYPES.map(type => (
269
+ <button
270
+ key={type.value}
271
+ onClick={() => setNewIntegration({ ...newIntegration, crm_type: type.value })}
272
+ className={`p-3 rounded-xl border text-left transition-all ${newIntegration.crm_type === type.value
273
+ ? 'border-indigo-600 bg-indigo-50 ring-2 ring-indigo-500/20'
274
+ : 'border-slate-200 hover:border-indigo-300 hover:bg-slate-50'
275
+ }`}
276
+ >
277
+ <div className="font-medium text-slate-900">{type.label}</div>
278
+ </button>
279
+ ))}
280
+ </div>
281
+ </div>
282
+
283
+ {/* Integration Name */}
284
+ <div>
285
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
286
+ Название интеграции
287
+ </label>
288
+ <input
289
+ type="text"
290
+ value={newIntegration.integration_name}
291
+ onChange={(e) => setNewIntegration({ ...newIntegration, integration_name: e.target.value })}
292
+ placeholder="Например: Основная amoCRM"
293
+ className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
294
+ />
295
+ </div>
296
+
297
+ {/* API URL (for amoCRM, HubSpot, etc.) */}
298
+ {!['custom_webhook'].includes(newIntegration.crm_type) && (
299
+ <div>
300
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
301
+ API URL
302
+ </label>
303
+ <input
304
+ type="text"
305
+ value={newIntegration.api_url}
306
+ onChange={(e) => setNewIntegration({ ...newIntegration, api_url: e.target.value })}
307
+ placeholder={
308
+ newIntegration.crm_type === 'amocrm' ? 'https://yourcompany.amocrm.ru' :
309
+ newIntegration.crm_type === 'hubspot' ? 'https://api.hubapi.com' :
310
+ 'https://yourinstance.salesforce.com'
311
+ }
312
+ className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
313
+ />
314
+ </div>
315
+ )}
316
+
317
+ {/* Access Token */}
318
+ {!['bitrix24', 'custom_webhook'].includes(newIntegration.crm_type) && (
319
+ <div>
320
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
321
+ Access Token / API Key
322
+ </label>
323
+ <div className="relative">
324
+ <input
325
+ type={showTokens['new'] ? 'text' : 'password'}
326
+ value={newIntegration.access_token}
327
+ onChange={(e) => setNewIntegration({ ...newIntegration, access_token: e.target.value })}
328
+ placeholder="Введите токен доступа"
329
+ className="w-full px-4 py-3 pr-12 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent font-mono text-sm"
330
+ />
331
+ <button
332
+ type="button"
333
+ onClick={() => setShowTokens({ ...showTokens, new: !showTokens['new'] })}
334
+ className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
335
+ >
336
+ {showTokens['new'] ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
337
+ </button>
338
+ </div>
339
+ </div>
340
+ )}
341
+
342
+ {/* Webhook URL (for Bitrix24 and Custom) */}
343
+ {['bitrix24', 'custom_webhook'].includes(newIntegration.crm_type) && (
344
+ <div>
345
+ <label className="block text-sm font-semibold text-slate-700 mb-2">
346
+ Webhook URL
347
+ </label>
348
+ <input
349
+ type="text"
350
+ value={newIntegration.webhook_url}
351
+ onChange={(e) => setNewIntegration({ ...newIntegration, webhook_url: e.target.value })}
352
+ placeholder={
353
+ newIntegration.crm_type === 'bitrix24'
354
+ ? 'https://yourcompany.bitrix24.ru/rest/1/abc123xyz/'
355
+ : 'https://your-crm.com/api/webhook'
356
+ }
357
+ className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
358
+ />
359
+ </div>
360
+ )}
361
+
362
+ {/* Auto Sync Settings */}
363
+ <div className="bg-slate-50 rounded-xl p-6 space-y-4">
364
+ <h3 className="font-semibold text-slate-900 flex items-center gap-2">
365
+ <Zap className="w-5 h-5 text-yellow-500" />
366
+ Настройки автосинхронизации
367
+ </h3>
368
+
369
+ {/* Auto Sync Toggle */}
370
+ <div className="flex items-center justify-between">
371
+ <div>
372
+ <label className="text-sm font-medium text-slate-700">Автоматическая синхронизация</label>
373
+ <p className="text-xs text-slate-500">Синхронизировать лиды автоматически при обновлении</p>
374
+ </div>
375
+ <label className="relative inline-flex items-center cursor-pointer">
376
+ <input
377
+ type="checkbox"
378
+ checked={newIntegration.auto_sync}
379
+ onChange={(e) => setNewIntegration({ ...newIntegration, auto_sync: e.target.checked })}
380
+ className="sr-only peer"
381
+ />
382
+ <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
383
+ </label>
384
+ </div>
385
+
386
+ {/* Sync Only Hot Leads */}
387
+ <div className="flex items-center justify-between">
388
+ <div>
389
+ <label className="text-sm font-medium text-slate-700">Только горячие лиды</label>
390
+ <p className="text-xs text-slate-500">Синхронизировать только лиды с heat_score ≥ 70</p>
391
+ </div>
392
+ <label className="relative inline-flex items-center cursor-pointer">
393
+ <input
394
+ type="checkbox"
395
+ checked={newIntegration.sync_only_hot_leads}
396
+ onChange={(e) => setNewIntegration({ ...newIntegration, sync_only_hot_leads: e.target.checked })}
397
+ className="sr-only peer"
398
+ />
399
+ <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
400
+ </label>
401
+ </div>
402
+
403
+ {/* Sync Interval */}
404
+ <div>
405
+ <label className="block text-sm font-medium text-slate-700 mb-2">
406
+ Интервал синхронизации (минуты)
407
+ </label>
408
+ <select
409
+ value={newIntegration.sync_interval_minutes}
410
+ onChange={(e) => setNewIntegration({ ...newIntegration, sync_interval_minutes: parseInt(e.target.value) })}
411
+ className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
412
+ >
413
+ <option value={5}>5 минут</option>
414
+ <option value={15}>15 минут</option>
415
+ <option value={30}>30 минут</option>
416
+ <option value={60}>1 час</option>
417
+ <option value={360}>6 часов</option>
418
+ <option value={1440}>24 часа</option>
419
+ </select>
420
+ </div>
421
+
422
+ {/* Sync Statuses */}
423
+ <div>
424
+ <label className="block text-sm font-medium text-slate-700 mb-2">
425
+ Синхронизировать лиды со статусами:
426
+ </label>
427
+ <div className="grid grid-cols-2 gap-3">
428
+ {LEAD_STATUSES.map(status => (
429
+ <label key={status.value} className="flex items-center gap-2 cursor-pointer">
430
+ <input
431
+ type="checkbox"
432
+ checked={newIntegration.sync_statuses.includes(status.value)}
433
+ onChange={(e) => {
434
+ if (e.target.checked) {
435
+ setNewIntegration({
436
+ ...newIntegration,
437
+ sync_statuses: [...newIntegration.sync_statuses, status.value]
438
+ })
439
+ } else {
440
+ setNewIntegration({
441
+ ...newIntegration,
442
+ sync_statuses: newIntegration.sync_statuses.filter(s => s !== status.value)
443
+ })
444
+ }
445
+ }}
446
+ className="w-4 h-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"
447
+ />
448
+ <span className="text-sm text-slate-700">{status.label}</span>
449
+ </label>
450
+ ))}
451
+ </div>
452
+ </div>
453
+ </div>
454
+
455
+ {/* Action Buttons */}
456
+ <div className="flex gap-3">
457
+ <button
458
+ onClick={handleCreateIntegration}
459
+ disabled={saving || !newIntegration.integration_name}
460
+ className="flex-1 flex items-center justify-center gap-2 px-6 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
461
+ >
462
+ {saving ? (
463
+ <>
464
+ <Loader2 className="w-5 h-5 animate-spin" />
465
+ Сохранение...
466
+ </>
467
+ ) : (
468
+ <>
469
+ <Save className="w-5 h-5" />
470
+ Создать интеграцию
471
+ </>
472
+ )}
473
+ </button>
474
+ <button
475
+ onClick={() => setShowAddForm(false)}
476
+ className="px-6 py-3 border border-slate-300 text-slate-700 rounded-xl hover:bg-slate-50 transition-colors font-medium"
477
+ >
478
+ Отмена
479
+ </button>
480
+ </div>
481
+ </div>
482
+ </div>
483
+ )}
484
+
485
+ {/* Existing Integrations */}
486
+ <div className="space-y-4">
487
+ {integrations.length === 0 ? (
488
+ <div className="bg-white rounded-xl shadow-lg p-12 text-center border border-slate-200">
489
+ <Database className="w-16 h-16 text-slate-300 mx-auto mb-4" />
490
+ <h3 className="text-xl font-semibold text-slate-900 mb-2">
491
+ Нет активных интеграций
492
+ </h3>
493
+ <p className="text-slate-600 mb-6">
494
+ Добавьте интеграцию с CRM системой для автоматической синхронизации лидов
495
+ </p>
496
+ <button
497
+ onClick={() => setShowAddForm(true)}
498
+ className="inline-flex items-center gap-2 px-6 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-colors font-medium"
499
+ >
500
+ <Plus className="w-5 h-5" />
501
+ Добавить первую интеграцию
502
+ </button>
503
+ </div>
504
+ ) : (
505
+ integrations.map(integration => (
506
+ <div key={integration.id} className="bg-white rounded-xl shadow-lg p-6 border border-slate-200">
507
+ <div className="flex items-start justify-between mb-4">
508
+ <div className="flex items-center gap-3">
509
+ <div className="p-2 bg-indigo-50 rounded-lg border border-indigo-100">{getCRMIcon(integration.crm_type)}</div>
510
+ <div>
511
+ <h3 className="text-lg font-bold text-slate-900">{integration.integration_name}</h3>
512
+ <p className="text-sm text-slate-600">{getCRMLabel(integration.crm_type)}</p>
513
+ </div>
514
+ </div>
515
+ <div className="flex items-center gap-2">
516
+ <span className={`px-3 py-1 rounded-full text-xs font-medium ${integration.status === 'active' ? 'bg-green-100 text-green-700' :
517
+ integration.status === 'paused' ? 'bg-yellow-100 text-yellow-700' :
518
+ 'bg-red-100 text-red-700'
519
+ }`}>
520
+ {integration.status === 'active' ? 'Активна' :
521
+ integration.status === 'paused' ? 'Приостановлена' : 'Ошибка'}
522
+ </span>
523
+ <button
524
+ onClick={() => handleDeleteIntegration(integration.id)}
525
+ className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
526
+ >
527
+ <Trash2 className="w-4 h-4" />
528
+ </button>
529
+ </div>
530
+ </div>
531
+
532
+ {/* Stats */}
533
+ <div className="grid grid-cols-3 gap-4 mb-4">
534
+ <div className="bg-slate-50 rounded-lg p-3">
535
+ <p className="text-xs text-slate-600 mb-1">Синхронизировано</p>
536
+ <p className="text-2xl font-bold text-slate-900">{integration.total_synced_leads}</p>
537
+ </div>
538
+ <div className="bg-slate-50 rounded-lg p-3">
539
+ <p className="text-xs text-slate-600 mb-1">Ошибок</p>
540
+ <p className="text-2xl font-bold text-red-600">{integration.failed_sync_count}</p>
541
+ </div>
542
+ <div className="bg-slate-50 rounded-lg p-3">
543
+ <p className="text-xs text-slate-600 mb-1">Последняя синхр.</p>
544
+ <p className="text-sm font-medium text-slate-700">
545
+ {integration.last_sync_at
546
+ ? new Date(integration.last_sync_at).toLocaleString('ru-RU')
547
+ : 'Не было'
548
+ }
549
+ </p>
550
+ </div>
551
+ </div>
552
+
553
+ {/* Settings */}
554
+ <div className="space-y-3">
555
+ <div className="flex items-center justify-between">
556
+ <span className="text-sm text-slate-700">Автосинхронизация</span>
557
+ <label className="relative inline-flex items-center cursor-pointer">
558
+ <input
559
+ type="checkbox"
560
+ checked={integration.auto_sync}
561
+ onChange={(e) => handleUpdateIntegration(integration.id, { auto_sync: e.target.checked })}
562
+ className="sr-only peer"
563
+ />
564
+ <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
565
+ </label>
566
+ </div>
567
+
568
+ <div className="flex items-center justify-between">
569
+ <span className="text-sm text-slate-700">Только горячие лиды</span>
570
+ <label className="relative inline-flex items-center cursor-pointer">
571
+ <input
572
+ type="checkbox"
573
+ checked={integration.sync_only_hot_leads}
574
+ onChange={(e) => handleUpdateIntegration(integration.id, { sync_only_hot_leads: e.target.checked })}
575
+ className="sr-only peer"
576
+ />
577
+ <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
578
+ </label>
579
+ </div>
580
+
581
+ <div className="flex items-center justify-between">
582
+ <span className="text-sm text-slate-700">Активна</span>
583
+ <label className="relative inline-flex items-center cursor-pointer">
584
+ <input
585
+ type="checkbox"
586
+ checked={integration.is_active}
587
+ onChange={(e) => handleUpdateIntegration(integration.id, { is_active: e.target.checked })}
588
+ className="sr-only peer"
589
+ />
590
+ <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
591
+ </label>
592
+ </div>
593
+ </div>
594
+ </div>
595
+ ))
596
+ )}
597
  </div>
598
+ </div>
 
 
599
  </div>
600
+ )
 
 
601
  }
frontend/components/ClientCard.tsx CHANGED
@@ -1,6 +1,6 @@
1
  'use client'
2
 
3
- import { useState } from 'react'
4
  import { Lead } from '@/lib/api'
5
  import { cn } from '@/lib/utils'
6
  import {
@@ -23,10 +23,44 @@ interface ClientCardProps {
23
  }
24
 
25
  export function ClientCard({ lead, onTakeover, isAnalyzing, onRefresh, conversationId, tenantId }: ClientCardProps) {
26
- const { success } = useToast()
27
  const summary = lead.ai_summary_json || {}
28
  const [expandedSection, setExpandedSection] = useState<string | null>(null)
 
 
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  // Helper to clean values
31
  const cleanValue = (value: any, fallback: string): string => {
32
  if (!value || typeof value !== 'string') return fallback
@@ -90,18 +124,24 @@ export function ClientCard({ lead, onTakeover, isAnalyzing, onRefresh, conversat
90
  <div>
91
  <h2 className="font-bold text-slate-900 text-sm">AI Summary</h2>
92
  <p className="text-[10px] text-slate-500 font-medium">Анализ диалога</p>
 
 
 
 
 
 
93
  </div>
94
  </div>
95
 
96
  <div className="flex items-center gap-3">
97
  {/* Refresh Button */}
98
  <button
99
- onClick={onRefresh}
100
- disabled={isAnalyzing}
101
  className="flex items-center gap-1.5 px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-[10px] font-bold text-slate-600 hover:text-indigo-600 hover:border-indigo-200 hover:bg-indigo-50 transition-all shadow-sm active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
102
  >
103
- <RefreshCw className={cn("w-3 h-3", isAnalyzing && "animate-spin")} />
104
- <span>Обновить</span>
105
  </button>
106
 
107
  {/* Score Ring */}
 
1
  'use client'
2
 
3
+ import { useState, useEffect } from 'react'
4
  import { Lead } from '@/lib/api'
5
  import { cn } from '@/lib/utils'
6
  import {
 
23
  }
24
 
25
  export function ClientCard({ lead, onTakeover, isAnalyzing, onRefresh, conversationId, tenantId }: ClientCardProps) {
26
+ const { success, error } = useToast()
27
  const summary = lead.ai_summary_json || {}
28
  const [expandedSection, setExpandedSection] = useState<string | null>(null)
29
+ const [isReanalyzing, setIsReanalyzing] = useState(false)
30
+ const [currentStage, setCurrentStage] = useState<any>(null)
31
 
32
+ useEffect(() => {
33
+ if (!lead.current_stage_id) return
34
+ fetch(`/api/v1/playbook/stages`, {
35
+ headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }
36
+ })
37
+ .then(r => r.ok ? r.json() : [])
38
+ .then(stages => {
39
+ const stage = stages.find((s: any) => s.id === lead.current_stage_id)
40
+ if (stage) setCurrentStage(stage)
41
+ })
42
+ .catch(console.error)
43
+ }, [lead.current_stage_id])
44
+
45
+ const handleReanalyze = async () => {
46
+ setIsReanalyzing(true)
47
+ try {
48
+ const res = await fetch(`/api/v1/leads/${lead.id}/analyze`, {
49
+ method: 'POST',
50
+ headers: {
51
+ 'Content-Type': 'application/json',
52
+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
53
+ }
54
+ })
55
+ if (!res.ok) throw new Error('Failed')
56
+ success('Анализ запущен', 'AI переанализирует данные')
57
+ setTimeout(() => onRefresh?.(), 3000)
58
+ } catch {
59
+ error('Ошибка', 'Не удалось запустить анализ')
60
+ } finally {
61
+ setIsReanalyzing(false)
62
+ }
63
+ }
64
  // Helper to clean values
65
  const cleanValue = (value: any, fallback: string): string => {
66
  if (!value || typeof value !== 'string') return fallback
 
124
  <div>
125
  <h2 className="font-bold text-slate-900 text-sm">AI Summary</h2>
126
  <p className="text-[10px] text-slate-500 font-medium">Анализ диалога</p>
127
+ {currentStage && (
128
+ <span className="flex items-center gap-1 px-2 py-0.5 bg-indigo-50 border border-indigo-200 rounded-md text-[10px] font-semibold text-indigo-700">
129
+ <Target className="w-3 h-3" />
130
+ {currentStage.name}
131
+ </span>
132
+ )}
133
  </div>
134
  </div>
135
 
136
  <div className="flex items-center gap-3">
137
  {/* Refresh Button */}
138
  <button
139
+ onClick={handleReanalyze}
140
+ disabled={isReanalyzing || isAnalyzing}
141
  className="flex items-center gap-1.5 px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-[10px] font-bold text-slate-600 hover:text-indigo-600 hover:border-indigo-200 hover:bg-indigo-50 transition-all shadow-sm active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
142
  >
143
+ <Brain className={cn("w-3 h-3", (isReanalyzing || isAnalyzing) && "animate-pulse")} />
144
+ <span>{isReanalyzing ? 'Анализ...' : 'Анализ'}</span>
145
  </button>
146
 
147
  {/* Score Ring */}
frontend/components/Sidebar.tsx CHANGED
@@ -16,6 +16,12 @@ export function Sidebar() {
16
  return null
17
  }
18
 
 
 
 
 
 
 
19
  // Helper to check if route is active
20
  const isActive = (path: string) => pathname === path || pathname.startsWith(path + '/')
21
 
@@ -70,11 +76,7 @@ export function Sidebar() {
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 - Dark Mode */}
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-500/10 blur-[100px] rounded-full"></div>
76
- <div className="absolute bottom-0 right-0 w-[100%] h-[40%] bg-purple-500/5 blur-[80px] rounded-full"></div>
77
- </div>
78
 
79
  {/* Logo Section */}
80
  <div className="p-6 border-b border-slate-800 relative z-10">
@@ -112,8 +114,12 @@ export function Sidebar() {
112
  <nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10 scrollbar-thin scrollbar-thumb-slate-700 scrollbar-track-transparent">
113
 
114
  {/* Main Navigation */}
115
- <motion.div variants={itemVariants}>
116
- <p className="px-4 text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">
 
 
 
 
117
  Платформа
118
  </p>
119
  <div className="space-y-1">
@@ -121,7 +127,7 @@ export function Sidebar() {
121
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative overflow-hidden",
122
  isActive('/dashboard')
123
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
124
- : "text-slate-400 hover:text-white hover:bg-white/5"
125
  )}>
126
  {isActive('/dashboard') && (
127
  <motion.div
@@ -130,7 +136,7 @@ export function Sidebar() {
130
  transition={{ type: "spring", stiffness: 300, damping: 30 }}
131
  />
132
  )}
133
- <LayoutDashboard className={cn("w-5 h-5 transition-colors", isActive('/dashboard') ? "text-white" : "text-slate-500 group-hover:text-indigo-400")} />
134
  <span>Дашборд</span>
135
  {isActive('/dashboard') && <div className="ml-auto w-1.5 h-1.5 rounded-full bg-white animate-pulse" />}
136
  </Link>
@@ -139,9 +145,9 @@ export function Sidebar() {
139
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
140
  isActive('/chats')
141
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
142
- : "text-slate-400 hover:text-white hover:bg-white/5"
143
  )}>
144
- <MessageSquare className={cn("w-5 h-5 transition-colors", isActive('/chats') ? "text-white" : "text-slate-500 group-hover:text-indigo-400")} />
145
  <span>Чаты</span>
146
  {/* Badge for unread messages could go here */}
147
  </Link>
@@ -151,8 +157,12 @@ export function Sidebar() {
151
  </motion.div>
152
 
153
  {/* AI Tools */}
154
- <motion.div variants={itemVariants}>
155
- <p className="px-4 text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">
 
 
 
 
156
  AI Инструменты
157
  </p>
158
  <div className="space-y-1">
@@ -160,9 +170,9 @@ export function Sidebar() {
160
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
161
  isActive('/knowledge')
162
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
163
- : "text-slate-400 hover:text-white hover:bg-white/5"
164
  )}>
165
- <Brain className={cn("w-5 h-5 transition-colors", isActive('/knowledge') ? "text-white" : "text-slate-500 group-hover:text-indigo-400")} />
166
  <span>База Знаний</span>
167
  </Link>
168
 
@@ -170,17 +180,21 @@ export function Sidebar() {
170
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
171
  isActive('/channels')
172
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
173
- : "text-slate-400 hover:text-white hover:bg-white/5"
174
  )}>
175
- <Plug className={cn("w-5 h-5 transition-colors", isActive('/channels') ? "text-white" : "text-slate-500 group-hover:text-indigo-400")} />
176
  <span>Каналы</span>
177
  </Link>
178
  </div>
179
  </motion.div>
180
 
181
  {/* Settings Group */}
182
- <motion.div variants={itemVariants}>
183
- <p className="px-4 text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">
 
 
 
 
184
  Настройки
185
  </p>
186
  <div className="space-y-1">
@@ -188,9 +202,9 @@ export function Sidebar() {
188
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
189
  isActive('/settings/brain')
190
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
191
- : "text-slate-400 hover:text-white hover:bg-white/5"
192
  )}>
193
- <Sparkles className={cn("w-5 h-5 transition-colors", isActive('/settings/brain') ? "text-white" : "text-slate-500 group-hover:text-indigo-400")} />
194
  <span>Мозг AI</span>
195
  </Link>
196
 
@@ -198,9 +212,9 @@ export function Sidebar() {
198
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
199
  isActive('/settings/crm')
200
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
201
- : "text-slate-400 hover:text-white hover:bg-white/5"
202
  )}>
203
- <Database className={cn("w-5 h-5 transition-colors", isActive('/settings/crm') ? "text-white" : "text-slate-500 group-hover:text-indigo-400")} />
204
  <span>CRM Интеграция</span>
205
  </Link>
206
 
@@ -208,9 +222,9 @@ export function Sidebar() {
208
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
209
  isActive('/settings/playbook')
210
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
211
- : "text-slate-400 hover:text-white hover:bg-white/5"
212
  )}>
213
- <Target className={cn("w-5 h-5 transition-colors", isActive('/settings/playbook') ? "text-white" : "text-slate-500 group-hover:text-indigo-400")} />
214
  <span>Плейбуки</span>
215
  </Link>
216
 
@@ -218,9 +232,9 @@ export function Sidebar() {
218
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
219
  isActive('/settings/team')
220
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
221
- : "text-slate-400 hover:text-white hover:bg-white/5"
222
  )}>
223
- <Users className={cn("w-5 h-5 transition-colors", isActive('/settings/team') ? "text-white" : "text-slate-500 group-hover:text-indigo-400")} />
224
  <span>Команда</span>
225
  </Link>
226
 
@@ -228,9 +242,9 @@ export function Sidebar() {
228
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
229
  isActive('/settings/billing')
230
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
231
- : "text-slate-400 hover:text-white hover:bg-white/5"
232
  )}>
233
- <DollarSign className={cn("w-5 h-5 transition-colors", isActive('/settings/billing') ? "text-white" : "text-slate-500 group-hover:text-indigo-400")} />
234
  <span>Тариф и Оплата</span>
235
  </Link>
236
 
@@ -238,9 +252,9 @@ export function Sidebar() {
238
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
239
  isActive('/settings/account')
240
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
241
- : "text-slate-400 hover:text-white hover:bg-white/5"
242
  )}>
243
- <User className={cn("w-5 h-5 transition-colors", isActive('/settings/account') ? "text-white" : "text-slate-500 group-hover:text-indigo-400")} />
244
  <span>Аккаунт</span>
245
  </Link>
246
  </div>
@@ -249,7 +263,7 @@ export function Sidebar() {
249
  )}
250
 
251
  {/* Bottom Section */}
252
- <div className="p-4 border-t border-slate-800 bg-[#0F172A]/50 backdrop-blur-sm relative z-10">
253
  {/* Partner Program Link */}
254
  <Link href="/partners" className="block mb-4 group">
255
  <div className="relative overflow-hidden rounded-xl bg-gradient-to-r from-indigo-900 to-purple-900 border border-indigo-500/30 p-3 transition-all duration-300 hover:border-indigo-500/60 hover:shadow-lg hover:shadow-indigo-900/20">
 
16
  return null
17
  }
18
 
19
+ // Redirect if not authenticated (and not loading)
20
+ if (!isLoading && !user) {
21
+ // This should be handled by AuthContext/Middleware, but as a fallback:
22
+ return null
23
+ }
24
+
25
  // Helper to check if route is active
26
  const isActive = (path: string) => pathname === path || pathname.startsWith(path + '/')
27
 
 
76
  variants={sidebarVariants}
77
  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"
78
  >
79
+ {/* Background Glow Effect - Removed for better visibility */}
 
 
 
 
80
 
81
  {/* Logo Section */}
82
  <div className="p-6 border-b border-slate-800 relative z-10">
 
114
  <nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10 scrollbar-thin scrollbar-thumb-slate-700 scrollbar-track-transparent">
115
 
116
  {/* Main Navigation */}
117
+ <motion.div
118
+ initial="hidden"
119
+ animate="visible"
120
+ variants={itemVariants}
121
+ >
122
+ <p className="px-4 text-xs font-semibold text-white/90 uppercase tracking-wider mb-2">
123
  Платформа
124
  </p>
125
  <div className="space-y-1">
 
127
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative overflow-hidden",
128
  isActive('/dashboard')
129
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
130
+ : "text-white/80 hover:text-white hover:bg-white/5"
131
  )}>
132
  {isActive('/dashboard') && (
133
  <motion.div
 
136
  transition={{ type: "spring", stiffness: 300, damping: 30 }}
137
  />
138
  )}
139
+ <LayoutDashboard className={cn("w-5 h-5 transition-colors", isActive('/dashboard') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
140
  <span>Дашборд</span>
141
  {isActive('/dashboard') && <div className="ml-auto w-1.5 h-1.5 rounded-full bg-white animate-pulse" />}
142
  </Link>
 
145
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
146
  isActive('/chats')
147
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
148
+ : "text-white/80 hover:text-white hover:bg-white/5"
149
  )}>
150
+ <MessageSquare className={cn("w-5 h-5 transition-colors", isActive('/chats') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
151
  <span>Чаты</span>
152
  {/* Badge for unread messages could go here */}
153
  </Link>
 
157
  </motion.div>
158
 
159
  {/* AI Tools */}
160
+ <motion.div
161
+ initial="hidden"
162
+ animate="visible"
163
+ variants={itemVariants}
164
+ >
165
+ <p className="px-4 text-xs font-semibold text-white/90 uppercase tracking-wider mb-2">
166
  AI Инструменты
167
  </p>
168
  <div className="space-y-1">
 
170
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
171
  isActive('/knowledge')
172
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
173
+ : "text-white/80 hover:text-white hover:bg-white/5"
174
  )}>
175
+ <Brain className={cn("w-5 h-5 transition-colors", isActive('/knowledge') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
176
  <span>База Знаний</span>
177
  </Link>
178
 
 
180
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
181
  isActive('/channels')
182
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
183
+ : "text-white/80 hover:text-white hover:bg-white/5"
184
  )}>
185
+ <Plug className={cn("w-5 h-5 transition-colors", isActive('/channels') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
186
  <span>Каналы</span>
187
  </Link>
188
  </div>
189
  </motion.div>
190
 
191
  {/* Settings Group */}
192
+ <motion.div
193
+ initial="hidden"
194
+ animate="visible"
195
+ variants={itemVariants}
196
+ >
197
+ <p className="px-4 text-xs font-semibold text-white/90 uppercase tracking-wider mb-2">
198
  Настройки
199
  </p>
200
  <div className="space-y-1">
 
202
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
203
  isActive('/settings/brain')
204
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
205
+ : "text-white/80 hover:text-white hover:bg-white/5"
206
  )}>
207
+ <Sparkles className={cn("w-5 h-5 transition-colors", isActive('/settings/brain') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
208
  <span>Мозг AI</span>
209
  </Link>
210
 
 
212
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
213
  isActive('/settings/crm')
214
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
215
+ : "text-white/80 hover:text-white hover:bg-white/5"
216
  )}>
217
+ <Database className={cn("w-5 h-5 transition-colors", isActive('/settings/crm') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
218
  <span>CRM Интеграция</span>
219
  </Link>
220
 
 
222
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
223
  isActive('/settings/playbook')
224
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
225
+ : "text-white/80 hover:text-white hover:bg-white/5"
226
  )}>
227
+ <Target className={cn("w-5 h-5 transition-colors", isActive('/settings/playbook') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
228
  <span>Плейбуки</span>
229
  </Link>
230
 
 
232
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
233
  isActive('/settings/team')
234
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
235
+ : "text-white/80 hover:text-white hover:bg-white/5"
236
  )}>
237
+ <Users className={cn("w-5 h-5 transition-colors", isActive('/settings/team') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
238
  <span>Команда</span>
239
  </Link>
240
 
 
242
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
243
  isActive('/settings/billing')
244
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
245
+ : "text-white/80 hover:text-white hover:bg-white/5"
246
  )}>
247
+ <DollarSign className={cn("w-5 h-5 transition-colors", isActive('/settings/billing') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
248
  <span>Тариф и Оплата</span>
249
  </Link>
250
 
 
252
  "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
253
  isActive('/settings/account')
254
  ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
255
+ : "text-white/80 hover:text-white hover:bg-white/5"
256
  )}>
257
+ <User className={cn("w-5 h-5 transition-colors", isActive('/settings/account') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
258
  <span>Аккаунт</span>
259
  </Link>
260
  </div>
 
263
  )}
264
 
265
  {/* Bottom Section */}
266
+ <div className="p-4 border-t border-slate-800 bg-[#0F172A] relative z-10">
267
  {/* Partner Program Link */}
268
  <Link href="/partners" className="block mb-4 group">
269
  <div className="relative overflow-hidden rounded-xl bg-gradient-to-r from-indigo-900 to-purple-900 border border-indigo-500/30 p-3 transition-all duration-300 hover:border-indigo-500/60 hover:shadow-lg hover:shadow-indigo-900/20">