Spaces:
Running

axeronis commited on
Commit
ede3a87
·
1 Parent(s): ebaa9c3

feat: analytics dashboard improvements

Browse files
backend/app/services/analytics_service.py CHANGED
@@ -218,8 +218,15 @@ class AnalyticsService:
218
  session, tenant, leads, prev_leads
219
  )
220
 
221
- # 8. Рассчитать воронку продаж
222
- funnel = self._calculate_funnel(leads)
 
 
 
 
 
 
 
223
 
224
  # 9. Рассчитать DISC распределение
225
  disc_distribution = self._calculate_disc_distribution(leads)
@@ -237,8 +244,25 @@ class AnalyticsService:
237
  hot_leads=metrics.hot_leads
238
  )
239
 
240
- # 12. Рассчитать статистику по каналам
241
- channel_stats = self._calculate_channel_stats(leads)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
 
243
  return DashboardData(
244
  metrics=metrics,
@@ -459,42 +483,49 @@ class AnalyticsService:
459
  session: AsyncSession,
460
  tenant_id: UUID
461
  ) -> float:
462
- """Рассчитать среднее время ответа AI в секундах."""
463
  try:
464
- # Get recent AI messages (last 100)
465
  stmt = select(Message).where(
466
- Message.tenant_id == tenant_id,
467
- Message.sender_type == "assistant"
468
- ).order_by(Message.created_at.desc()).limit(100)
469
 
470
  result = await session.execute(stmt)
471
- ai_messages = list(result.scalars().all())
472
 
473
- if not ai_messages:
474
  return 0.0
475
 
476
- # Calculate time differences with previous user messages
 
 
477
  total_time = 0.0
478
  count = 0
479
 
480
- for ai_msg in ai_messages:
481
- # Find the user message immediately before this AI message
482
- user_stmt = select(Message).where(
483
- Message.tenant_id == tenant_id,
484
- Message.lead_id == ai_msg.lead_id,
485
- Message.sender_type == "user",
486
- Message.created_at < ai_msg.created_at
487
- ).order_by(Message.created_at.desc()).limit(1)
488
-
489
- user_result = await session.execute(user_stmt)
490
- user_msg = user_result.scalar_one_or_none()
491
 
492
- if user_msg:
493
- delta_seconds = (ai_msg.created_at - user_msg.created_at).total_seconds()
494
- # Sanity check: 0-300 seconds (5 minutes max)
495
- if 0 < delta_seconds < 300:
496
- total_time += delta_seconds
497
- count += 1
 
 
 
 
 
 
 
 
498
 
499
  return round(total_time / count, 2) if count > 0 else 0.0
500
 
@@ -502,27 +533,70 @@ class AnalyticsService:
502
  logger.warning(f"Failed to calculate avg response time: {e}")
503
  return 0.0
504
 
505
- def _calculate_funnel(self, leads: List[Lead]) -> List[FunnelStageData]:
506
- """Рассчитать распределение по этапам воронки."""
 
 
 
 
507
  total_leads = len(leads)
508
-
509
- funnel_stages = {
510
- "new": sum(1 for lead in leads if lead.status == "new"),
511
- "contacted": sum(1 for lead in leads if lead.status == "contacted"),
512
- "qualified": sum(1 for lead in leads if lead.status == "qualified"),
513
- "negotiation": sum(1 for lead in leads if lead.status == "negotiation"),
514
- "closed": sum(1 for lead in leads if lead.status == "closed"),
515
- }
516
-
517
- return [
518
- FunnelStageData(
519
- stage=stage.capitalize(),
520
- count=count,
521
- percentage=(count / total_leads * 100) if total_leads > 0 else 0.0
522
- )
523
- for stage, count in funnel_stages.items()
524
- if count > 0
525
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526
 
527
  def _calculate_disc_distribution(self, leads: List[Lead]) -> List[DISCDistributionData]:
528
  """Рассчитать распределение по DISC психотипам."""
@@ -543,8 +617,9 @@ class AnalyticsService:
543
  ]
544
 
545
  def _extract_top_objections(self, leads: List[Lead]) -> List[ObjectionData]:
546
- """Извлечь топ-5 возражений из AI summaries."""
547
  objection_counts: Dict[str, int] = {}
 
548
 
549
  for lead in leads:
550
  if lead.ai_summary_json and isinstance(lead.ai_summary_json, dict):
@@ -558,8 +633,14 @@ class AnalyticsService:
558
 
559
  # Подсчитать каждое возражение
560
  for objection in objections_list[:5]:
561
- if isinstance(objection, str) and len(objection) > 10:
562
- obj_normalized = objection.strip()[:100]
 
 
 
 
 
 
563
  objection_counts[obj_normalized] = objection_counts.get(obj_normalized, 0) + 1
564
 
565
  # Топ-5 самых частых
@@ -568,11 +649,11 @@ class AnalyticsService:
568
 
569
  return [
570
  ObjectionData(
571
- objection=objection,
572
  count=count,
573
  percentage=(count / total_objections * 100) if total_objections > 0 else 0.0
574
  )
575
- for objection, count in top_objections_list
576
  ]
577
 
578
  def _calculate_lead_value_over_time(self, leads: List[Lead]) -> List[LeadValueOverTimeData]:
@@ -608,27 +689,26 @@ class AnalyticsService:
608
 
609
  return lead_value_over_time
610
 
611
- def _calculate_channel_stats(self, leads: List[Lead]) -> List[ChannelStatsData]:
612
  """Рассчитать распределение лидов по каналам (source)."""
613
  total_leads = len(leads)
614
- channel_counts = {}
615
 
616
- for lead in leads:
617
- # Infer source from contact fields
618
- source = "manual"
619
- if lead.telegram_id:
620
- source = "telegram"
621
- elif lead.whatsapp_id:
622
- source = "whatsapp"
623
- elif lead.linkedin_urn or lead.linkedin_profile:
624
- source = "linkedin"
625
- elif lead.email:
626
- source = "email"
627
- channel_counts[source] = channel_counts.get(source, 0) + 1
628
-
629
- # Нормализация имен каналов для display
630
  normalized_counts = {}
631
- for source, count in channel_counts.items():
632
  display_name = source.capitalize().replace('_', ' ')
633
  if "whatsapp" in source.lower():
634
  display_name = "WhatsApp"
 
218
  session, tenant, leads, prev_leads
219
  )
220
 
221
+ # 8. Получить этапы продаж и рассчитать воронку
222
+ stages_result = await session.execute(
223
+ select(SalesStage)
224
+ .where(SalesStage.tenant_id == tenant_id, SalesStage.is_active == True)
225
+ .order_by(SalesStage.order_index)
226
+ )
227
+ sales_stages = stages_result.scalars().all()
228
+
229
+ funnel = self._calculate_funnel(leads, sales_stages)
230
 
231
  # 9. Рассчитать DISC распределение
232
  disc_distribution = self._calculate_disc_distribution(leads)
 
244
  hot_leads=metrics.hot_leads
245
  )
246
 
247
+ # 12. Рассчитать статистику по каналам (Real Data)
248
+ db_channel_counts = {}
249
+ if leads:
250
+ try:
251
+ lead_ids = [l.id for l in leads]
252
+ # Avoid large IN list if possible, but for dashboard pages it's usually fine (<1000 items)
253
+ # If leads list is large, this might be slow, but better than N+1
254
+ chan_stmt = (
255
+ select(Conversation.channel, func.count(func.distinct(Lead.id)))
256
+ .join(Lead)
257
+ .where(Lead.id.in_(lead_ids))
258
+ .group_by(Conversation.channel)
259
+ )
260
+ chan_res = await session.execute(chan_stmt)
261
+ db_channel_counts = {row[0]: row[1] for row in chan_res.all()}
262
+ except Exception as e:
263
+ logger.error(f"Error fetching channel stats: {e}")
264
+
265
+ channel_stats = self._calculate_channel_stats(leads, db_channel_counts)
266
 
267
  return DashboardData(
268
  metrics=metrics,
 
483
  session: AsyncSession,
484
  tenant_id: UUID
485
  ) -> float:
486
+ """Рассчитать среднее время ответа AI в секундах (Optimized)."""
487
  try:
488
+ # Fetch last 500 messages ordered by time (covers enough history for recent convs)
489
  stmt = select(Message).where(
490
+ Message.tenant_id == tenant_id
491
+ ).order_by(Message.created_at.desc()).limit(500)
 
492
 
493
  result = await session.execute(stmt)
494
+ all_messages = list(result.scalars().all())
495
 
496
+ if not all_messages:
497
  return 0.0
498
 
499
+ # Sort chronologically for easier processing: Oldest -> Newest
500
+ all_messages.sort(key=lambda m: m.created_at)
501
+
502
  total_time = 0.0
503
  count = 0
504
 
505
+ # Group by lead_id/conversation to ensure we compare messages in same chat
506
+ msgs_by_lead = {}
507
+ for msg in all_messages:
508
+ if msg.lead_id not in msgs_by_lead:
509
+ msgs_by_lead[msg.lead_id] = []
510
+ msgs_by_lead[msg.lead_id].append(msg)
511
+
512
+ for lead_id, msgs in msgs_by_lead.items():
513
+ last_user_msg_time = None
 
 
514
 
515
+ for msg in msgs:
516
+ if msg.sender_type == "user":
517
+ last_user_msg_time = msg.created_at
518
+ elif msg.sender_type in ["assistant", "ai"] and last_user_msg_time:
519
+ # Found AI reply to a user message
520
+ delta_seconds = (msg.created_at - last_user_msg_time).total_seconds()
521
+
522
+ # Sanity check: 0-300 seconds (ignores replies to very old messages)
523
+ if 0 < delta_seconds < 600: # Increased to 10 mins as 5 might be too tight
524
+ total_time += delta_seconds
525
+ count += 1
526
+
527
+ # Reset to avoid double counting or incorrect pairing
528
+ last_user_msg_time = None
529
 
530
  return round(total_time / count, 2) if count > 0 else 0.0
531
 
 
533
  logger.warning(f"Failed to calculate avg response time: {e}")
534
  return 0.0
535
 
536
+ def _calculate_funnel(self, leads: List[Lead], stages: List[SalesStage] = None) -> List[FunnelStageData]:
537
+ """
538
+ Рассчитать распределение по этапам воронки.
539
+ Использует динамические этапы из Playbook (SalesStage), если переданы.
540
+ Иначе фолбэк на старую логику.
541
+ """
542
  total_leads = len(leads)
543
+ result = []
544
+
545
+ if stages:
546
+ # Dynamic Stages Logic
547
+ stage_counts = {}
548
+ # Count leads by stage_id
549
+ for lead in leads:
550
+ sid = str(lead.current_stage_id) if lead.current_stage_id else "uncategorized"
551
+ stage_counts[sid] = stage_counts.get(sid, 0) + 1
552
+
553
+ # 1. Unassigned / New (Leads with no stage)
554
+ uncat_count = stage_counts.get("uncategorized", 0)
555
+ if uncat_count > 0:
556
+ result.append(FunnelStageData(
557
+ stage="Не распределено", # Localize later or keep generic
558
+ count=uncat_count,
559
+ percentage=(uncat_count / total_leads * 100) if total_leads > 0 else 0.0
560
+ ))
561
+
562
+ # 2. Configured Stages
563
+ for stage in stages:
564
+ sid = str(stage.id)
565
+ count = stage_counts.get(sid, 0)
566
+ # Funnel usually shows structure, so showing 0 is good.
567
+ result.append(FunnelStageData(
568
+ stage=stage.name,
569
+ count=count,
570
+ percentage=(count / total_leads * 100) if total_leads > 0 else 0.0
571
+ ))
572
+
573
+ else:
574
+ # Fallback Legacy Logic (Status Enum)
575
+ status_counts = {}
576
+ for lead in leads:
577
+ # Handle standard Enum
578
+ status = lead.status.value if hasattr(lead.status, 'value') else str(lead.status)
579
+ status_counts[status] = status_counts.get(status, 0) + 1
580
+
581
+ # Mapping LeadStatus -> Frontend Keys
582
+ funnel_map = [
583
+ ("new", "new"),
584
+ ("qualified", "qualified"),
585
+ ("in_progress", "negotiation"),
586
+ ("closed_won", "closed_won"),
587
+ ("closed_lost", "closed_lost")
588
+ ]
589
+
590
+ for enum_val, key in funnel_map:
591
+ count = status_counts.get(enum_val, 0)
592
+ if count > 0 or key == "new":
593
+ result.append(FunnelStageData(
594
+ stage=key,
595
+ count=count,
596
+ percentage=(count / total_leads * 100) if total_leads > 0 else 0.0
597
+ ))
598
+
599
+ return result
600
 
601
  def _calculate_disc_distribution(self, leads: List[Lead]) -> List[DISCDistributionData]:
602
  """Рассчитать распределение по DISC психотипам."""
 
617
  ]
618
 
619
  def _extract_top_objections(self, leads: List[Lead]) -> List[ObjectionData]:
620
+ """Извлечь топ-5 возражений из AI summaries (Deduplicated)."""
621
  objection_counts: Dict[str, int] = {}
622
+ original_cases: Dict[str, str] = {} # normalized -> display
623
 
624
  for lead in leads:
625
  if lead.ai_summary_json and isinstance(lead.ai_summary_json, dict):
 
633
 
634
  # Подсчитать каждое возражение
635
  for objection in objections_list[:5]:
636
+ if isinstance(objection, str) and len(objection) > 5:
637
+ # Normalize: lowercase, remove special chars at end
638
+ obj_normalized = objection.strip().lower().rstrip('.,;!')[:100]
639
+
640
+ # Store first occurrence as display version (usually has correct casing)
641
+ if obj_normalized not in original_cases:
642
+ original_cases[obj_normalized] = objection.strip()
643
+
644
  objection_counts[obj_normalized] = objection_counts.get(obj_normalized, 0) + 1
645
 
646
  # Топ-5 самых частых
 
649
 
650
  return [
651
  ObjectionData(
652
+ objection=original_cases.get(norm_obj, norm_obj).capitalize(),
653
  count=count,
654
  percentage=(count / total_objections * 100) if total_objections > 0 else 0.0
655
  )
656
+ for norm_obj, count in top_objections_list
657
  ]
658
 
659
  def _calculate_lead_value_over_time(self, leads: List[Lead]) -> List[LeadValueOverTimeData]:
 
689
 
690
  return lead_value_over_time
691
 
692
+ def _calculate_channel_stats(self, leads: List[Lead], db_counts: Dict[str, int] = None) -> List[ChannelStatsData]:
693
  """Рассчитать распределение лидов по каналам (source)."""
694
  total_leads = len(leads)
695
+ final_counts = {}
696
 
697
+ # 1. Use DB counts (from conversations)
698
+ if db_counts:
699
+ for channel, count in db_counts.items():
700
+ if channel:
701
+ final_counts[channel.lower()] = count
702
+
703
+ # 2. Fill remaining with 'manual' or custom logic if needed
704
+ counted = sum(final_counts.values())
705
+ remaining = total_leads - counted
706
+ if remaining > 0:
707
+ final_counts['manual'] = final_counts.get('manual', 0) + remaining
708
+
709
+ # Normalize names
 
710
  normalized_counts = {}
711
+ for source, count in final_counts.items():
712
  display_name = source.capitalize().replace('_', ' ')
713
  if "whatsapp" in source.lower():
714
  display_name = "WhatsApp"
frontend/app/dashboard/page.tsx CHANGED
@@ -192,6 +192,15 @@ export default function DashboardPage() {
192
  )
193
  }
194
 
 
 
 
 
 
 
 
 
 
195
  if (!data) return null
196
 
197
  return (
@@ -204,7 +213,6 @@ export default function DashboardPage() {
204
  <h1 className="text-2xl font-black text-white tracking-wider flex items-center gap-3">
205
  {t('nav.analytics').toUpperCase()}
206
  </h1>
207
- {/* Subtitle removed as requested */}
208
  </div>
209
  <div className="flex items-center gap-3">
210
  {/* Date Filter Dropdown */}
@@ -229,10 +237,10 @@ export default function DashboardPage() {
229
  className="absolute top-full right-0 mt-2 w-[180px] bg-[#050510]/90 backdrop-blur-2xl rounded-lg border border-white/10 z-50 overflow-hidden"
230
  >
231
  {[
232
- { val: '7d', label: '7 дней' },
233
- { val: '30d', label: '30 дней' },
234
- { val: '90d', label: '90 дней' },
235
- { val: 'all', label: 'Всё время' }
236
  ].map((option) => (
237
  <button
238
  key={option.val}
@@ -258,7 +266,7 @@ export default function DashboardPage() {
258
  <button
259
  onClick={() => refetch()}
260
  className="p-2 bg-surface border border-white/10 rounded-lg hover:border-indigo-500/50 text-slate-400 transition-colors hover:rotate-180 duration-500"
261
- title="Обновить"
262
  >
263
  <RefreshCw className="w-4 h-4" />
264
  </button>
@@ -276,6 +284,9 @@ export default function DashboardPage() {
276
  </div>
277
  <p className="text-[10px] sm:text-xs font-bold text-slate-500 uppercase tracking-wider mb-1">{t('dashboard.totalLeads')}</p>
278
  <p className="text-2xl sm:text-3xl font-bold text-white tracking-tight">{data.metrics.total_leads}</p>
 
 
 
279
  </div>
280
  </div>
281
 
@@ -286,9 +297,9 @@ export default function DashboardPage() {
286
  <div className="h-10 w-10 sm:h-12 sm:w-12 rounded-lg sm:rounded-xl bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center mb-3 sm:mb-4 group-hover:scale-110 transition-transform duration-300">
287
  <DollarSign className="w-5 h-5 sm:w-6 sm:h-6 text-emerald-400" />
288
  </div>
289
- <p className="text-[10px] sm:text-xs font-bold text-slate-500 uppercase tracking-wider mb-1">REVENUE FORECAST</p>
290
  <p className="text-2xl sm:text-3xl font-bold text-white tracking-tight">${data.metrics.weighted_pipeline_value?.toLocaleString() || '0'}</p>
291
- <p className="text-[10px] text-slate-500 mt-1">Weighted Pipeline</p>
292
  </div>
293
  </div>
294
 
@@ -301,11 +312,11 @@ export default function DashboardPage() {
301
  </div>
302
  <div className="flex justify-between items-start">
303
  <div>
304
- <p className="text-[10px] sm:text-xs font-bold text-slate-500 uppercase tracking-wider mb-1">AI AUTONOMY</p>
305
  <p className="text-2xl sm:text-3xl font-bold text-white tracking-tight">{data.metrics.ai_autonomy_rate}%</p>
306
  </div>
307
  </div>
308
- <p className="text-[10px] text-slate-500 mt-1">Fully automated chats</p>
309
  </div>
310
  </div>
311
 
@@ -316,9 +327,9 @@ export default function DashboardPage() {
316
  <div className="h-10 w-10 sm:h-12 sm:w-12 rounded-lg sm:rounded-xl bg-pink-500/10 border border-pink-500/20 flex items-center justify-center mb-3 sm:mb-4 group-hover:scale-110 transition-transform duration-300">
317
  <TrendingUp className="w-5 h-5 sm:w-6 sm:h-6 text-pink-400" />
318
  </div>
319
- <p className="text-[10px] sm:text-xs font-bold text-slate-500 uppercase tracking-wider mb-1">SALES VELOCITY</p>
320
- <p className="text-2xl sm:text-3xl font-bold text-white tracking-tight">{data.metrics.sales_velocity} <span className="text-sm font-medium text-slate-500">days</span></p>
321
- <p className="text-[10px] text-slate-500 mt-1">Avg time to close</p>
322
  </div>
323
  </div>
324
  </div>
@@ -329,25 +340,25 @@ export default function DashboardPage() {
329
  <div className="md:col-span-1 bg-[#050510]/60 backdrop-blur-xl rounded-2xl border border-indigo-500/20 p-6 relative overflow-hidden group">
330
  <div className="absolute top-0 right-0 p-4">
331
  <div className="px-2 py-1 rounded bg-emerald-500/20 border border-emerald-500/30 text-[10px] font-bold text-emerald-400 uppercase">
332
- Value Generated
333
  </div>
334
  </div>
335
  <h3 className="text-xs font-bold text-indigo-400 uppercase tracking-[0.2em] mb-4 flex items-center gap-2">
336
  <Target className="w-3 h-3" />
337
- AI IMPACT
338
  </h3>
339
  <div className="space-y-4">
340
  <div>
341
- <p className="text-[10px] text-slate-500 font-bold uppercase mb-1">Influenced Revenue</p>
342
  <p className="text-2xl font-mono font-bold text-white">${(data.metrics.revenue_influenced || 0).toLocaleString()}</p>
343
  </div>
344
  <div className="pt-2 border-t border-white/5 flex justify-between items-end">
345
  <div>
346
- <p className="text-[10px] text-slate-500 font-bold uppercase mb-1">Pipe Value (Total)</p>
347
  <p className="text-sm font-mono font-bold text-slate-400">${(data.metrics.pipeline_value || 0).toLocaleString()}</p>
348
  </div>
349
  <div className="text-right">
350
- <p className="text-[10px] text-slate-500 font-bold uppercase mb-1">Hours Saved</p>
351
  <p className="text-xl font-mono font-bold text-emerald-400">{data.metrics.hours_saved}h</p>
352
  </div>
353
  </div>
@@ -358,26 +369,26 @@ export default function DashboardPage() {
358
  <div className="flex items-center justify-between mb-4">
359
  <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2">
360
  <Shield className="w-4 h-4 text-indigo-400" />
361
- CONVERSION HEALTH
362
  </h3>
363
  </div>
364
  <div className="grid grid-cols-3 gap-4">
365
  <div className="p-3 bg-white/5 rounded-xl border border-white/5 text-center">
366
- <p className="text-[10px] text-slate-500 uppercase mb-1">Conversion Rate</p>
367
  <p className="text-2xl font-bold text-white">{data.metrics.conversion_rate}%</p>
368
  <p className={cn("text-[10px]", data.metrics.conversion_rate_change >= 0 ? "text-emerald-400" : "text-red-400")}>
369
  {data.metrics.conversion_rate_change > 0 ? '+' : ''}{data.metrics.conversion_rate_change}% vs prev
370
  </p>
371
  </div>
372
  <div className="p-3 bg-white/5 rounded-xl border border-white/5 text-center">
373
- <p className="text-[10px] text-slate-500 uppercase mb-1">Avg Response Time</p>
374
  <p className="text-2xl font-bold text-white">{data.metrics.avg_response_time_seconds.toFixed(0)}s</p>
375
- <p className="text-[10px] text-emerald-400">Optimal (&lt;60s)</p>
376
  </div>
377
  <div className="p-3 bg-white/5 rounded-xl border border-white/5 text-center">
378
- <p className="text-[10px] text-slate-500 uppercase mb-1">Hot Leads</p>
379
  <p className="text-2xl font-bold text-orange-400">{data.metrics.hot_leads}</p>
380
- <p className="text-[10px] text-slate-500">Ready to close</p>
381
  </div>
382
  </div>
383
  </div>
@@ -389,19 +400,25 @@ export default function DashboardPage() {
389
 
390
  {/* Leads by Channel (Donut Chart) */}
391
  <div className="bg-[#050510]/40 backdrop-blur-md rounded-2xl border border-white/10 p-6 relative overflow-hidden flex flex-col">
392
- <h3 className="text-sm font-bold text-slate-400 uppercase tracking-wider mb-6">ИСТОЧНИКИ ЛИДОВ</h3>
393
  <div className="h-[250px] w-full relative z-10 flex items-center justify-center">
394
  {data.channel_stats && data.channel_stats.length > 0 ? (
395
  <ResponsiveContainer width="100%" height="100%">
396
  <PieChart>
397
  <Pie
398
- data={data.channel_stats}
 
 
 
 
 
399
  cx="50%"
400
  cy="50%"
401
  innerRadius={60}
402
  outerRadius={80}
403
  paddingAngle={5}
404
  dataKey="count"
 
405
  >
406
  {data.channel_stats.map((entry, index) => (
407
  <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} stroke="rgba(0,0,0,0.2)" />
@@ -420,30 +437,30 @@ export default function DashboardPage() {
420
  </PieChart>
421
  </ResponsiveContainer>
422
  ) : (
423
- <div className="text-slate-500 text-sm">Нет данных по каналам</div>
424
  )}
425
  </div>
426
  </div>
427
 
428
  {/* Funnel Drop-off (Bar Chart) */}
429
  <div className="lg:col-span-2 bg-[#050510]/40 backdrop-blur-md rounded-2xl border border-white/10 p-6 relative overflow-hidden">
430
- <h3 className="text-sm font-bold text-slate-400 uppercase tracking-wider mb-6">ВОРОНКА ПРОДАЖ (ОТТОК КЛИЕНТОВ)</h3>
431
  <div className="h-[250px] w-full relative z-10">
432
  <ResponsiveContainer width="100%" height="100%">
433
  <BarChart
434
- data={data.funnel}
435
  layout="vertical"
436
  margin={{ top: 5, right: 30, left: 40, bottom: 5 }}
437
  >
438
  <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" horizontal={false} />
439
  <XAxis type="number" stroke="#475569" tick={{ fill: '#475569', fontSize: 10 }} />
440
- <YAxis type="category" dataKey="stage" stroke="#94a3b8" tick={{ fill: '#94a3b8', fontSize: 11 }} width={100} />
441
  <Tooltip
442
  cursor={{ fill: 'rgba(255,255,255,0.05)' }}
443
  contentStyle={{ backgroundColor: '#0F111A', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '12px' }}
444
  itemStyle={{ color: '#fff' }}
445
  />
446
- <Bar dataKey="count" name="Кол-во" fill="#8b5cf6" radius={[0, 4, 4, 0]}>
447
  {data.funnel.map((entry, index) => (
448
  <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
449
  ))}
@@ -459,7 +476,7 @@ export default function DashboardPage() {
459
  <div className="flex items-center justify-between mb-6">
460
  <h3 className="text-sm font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2">
461
  <Flame className="w-4 h-4 text-orange-400" />
462
- HIGH INTENT LEADS
463
  </h3>
464
  <button className="text-slate-500 hover:text-white transition-colors">
465
  <MoreHorizontal className="w-5 h-5" />
@@ -479,15 +496,15 @@ export default function DashboardPage() {
479
  </div>
480
  <div className="flex-1 min-w-0">
481
  <p className="font-medium text-white text-sm sm:text-base truncate group-hover:text-indigo-300 transition-colors">
482
- {lead.name || 'Неизвестный'}
483
  </p>
484
  <p className="text-[10px] sm:text-xs text-slate-500 truncate">
485
- {lead.telegram_id ? 'Telegram' : lead.whatsapp_id ? 'WhatsApp' : 'Contact'} • {lead.email || lead.telegram_id || lead.whatsapp_id || 'Нет контакта'}
486
  </p>
487
  </div>
488
  {/* Last activity - hidden on mobile */}
489
  <div className="hidden sm:flex flex-col items-end gap-1">
490
- <p className="text-[10px] text-slate-500">Last activity</p>
491
  <p className="text-xs text-slate-400">
492
  {lead.last_message_at ? new Date(lead.last_message_at).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' }) : '-'}
493
  </p>
@@ -509,7 +526,7 @@ export default function DashboardPage() {
509
  ) : (
510
  <div className="text-center py-8 text-slate-500">
511
  <Flame className="w-8 h-8 mx-auto mb-2 opacity-30" />
512
- <p className="text-sm">Нет горячих лидов</p>
513
  </div>
514
  )}
515
  </div>
@@ -522,7 +539,7 @@ export default function DashboardPage() {
522
  <div className="bg-[#050510]/40 backdrop-blur-md rounded-2xl border border-white/10 p-6 relative overflow-hidden">
523
  <h3 className="text-sm font-bold text-slate-400 uppercase tracking-wider mb-6 flex items-center gap-2">
524
  <AlertCircle className="w-4 h-4 text-red-400" />
525
- ЧАСТЫЕ ВОЗРАЖЕНИЯ
526
  </h3>
527
  <div className="space-y-4">
528
  {data.top_objections && data.top_objections.length > 0 ? (
@@ -546,14 +563,14 @@ export default function DashboardPage() {
546
  </div>
547
  ))
548
  ) : (
549
- <div className="text-center text-slate-500 text-sm py-4">Нет данных о возражениях</div>
550
  )}
551
  </div>
552
  </div>
553
 
554
  {/* Pipeline Dynamics (Area Chart) reused */}
555
  <div className="lg:col-span-2 bg-[#050510]/40 backdrop-blur-md rounded-2xl border border-white/10 p-6 relative overflow-hidden">
556
- <h3 className="text-sm font-bold text-slate-400 uppercase tracking-wider mb-6">ДИНАМИКА ЦЕННОСТИ ЛИДОВ (30 ДНЕЙ)</h3>
557
  <div className="h-[300px] w-full relative z-10">
558
  <ResponsiveContainer width="100%" height="100%">
559
  <AreaChart data={data.lead_value_over_time}>
 
192
  )
193
  }
194
 
195
+
196
+ // Helper to translate status
197
+ const translateStage = (stage: string) => {
198
+ const key = `status_${stage.toLowerCase()}`
199
+ // @ts-ignore - dynamic key access
200
+ const label = t(`dashboard.${key}`)
201
+ return label === key || label.startsWith('dashboard.') ? stage : label
202
+ }
203
+
204
  if (!data) return null
205
 
206
  return (
 
213
  <h1 className="text-2xl font-black text-white tracking-wider flex items-center gap-3">
214
  {t('nav.analytics').toUpperCase()}
215
  </h1>
 
216
  </div>
217
  <div className="flex items-center gap-3">
218
  {/* Date Filter Dropdown */}
 
237
  className="absolute top-full right-0 mt-2 w-[180px] bg-[#050510]/90 backdrop-blur-2xl rounded-lg border border-white/10 z-50 overflow-hidden"
238
  >
239
  {[
240
+ { val: '7d', label: t('dashboard.days7') },
241
+ { val: '30d', label: t('dashboard.days30') },
242
+ { val: '90d', label: t('dashboard.days90') },
243
+ { val: 'all', label: t('dashboard.allTime') }
244
  ].map((option) => (
245
  <button
246
  key={option.val}
 
266
  <button
267
  onClick={() => refetch()}
268
  className="p-2 bg-surface border border-white/10 rounded-lg hover:border-indigo-500/50 text-slate-400 transition-colors hover:rotate-180 duration-500"
269
+ title={t('common.refresh') || 'Refresh'}
270
  >
271
  <RefreshCw className="w-4 h-4" />
272
  </button>
 
284
  </div>
285
  <p className="text-[10px] sm:text-xs font-bold text-slate-500 uppercase tracking-wider mb-1">{t('dashboard.totalLeads')}</p>
286
  <p className="text-2xl sm:text-3xl font-bold text-white tracking-tight">{data.metrics.total_leads}</p>
287
+ <p className={cn("text-[10px] mt-1", data.metrics.total_leads_change >= 0 ? "text-emerald-400" : "text-red-400")}>
288
+ {data.metrics.total_leads_change > 0 ? '+' : ''}{data.metrics.total_leads_change}% vs prev
289
+ </p>
290
  </div>
291
  </div>
292
 
 
297
  <div className="h-10 w-10 sm:h-12 sm:w-12 rounded-lg sm:rounded-xl bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center mb-3 sm:mb-4 group-hover:scale-110 transition-transform duration-300">
298
  <DollarSign className="w-5 h-5 sm:w-6 sm:h-6 text-emerald-400" />
299
  </div>
300
+ <p className="text-[10px] sm:text-xs font-bold text-slate-500 uppercase tracking-wider mb-1">{t('dashboard.revenueForecast')}</p>
301
  <p className="text-2xl sm:text-3xl font-bold text-white tracking-tight">${data.metrics.weighted_pipeline_value?.toLocaleString() || '0'}</p>
302
+ <p className="text-[10px] text-slate-500 mt-1">{t('dashboard.weightedPipeline')}</p>
303
  </div>
304
  </div>
305
 
 
312
  </div>
313
  <div className="flex justify-between items-start">
314
  <div>
315
+ <p className="text-[10px] sm:text-xs font-bold text-slate-500 uppercase tracking-wider mb-1">{t('dashboard.aiAutonomy')}</p>
316
  <p className="text-2xl sm:text-3xl font-bold text-white tracking-tight">{data.metrics.ai_autonomy_rate}%</p>
317
  </div>
318
  </div>
319
+ <p className="text-[10px] text-slate-500 mt-1">{t('dashboard.fullyAutomatedChats')}</p>
320
  </div>
321
  </div>
322
 
 
327
  <div className="h-10 w-10 sm:h-12 sm:w-12 rounded-lg sm:rounded-xl bg-pink-500/10 border border-pink-500/20 flex items-center justify-center mb-3 sm:mb-4 group-hover:scale-110 transition-transform duration-300">
328
  <TrendingUp className="w-5 h-5 sm:w-6 sm:h-6 text-pink-400" />
329
  </div>
330
+ <p className="text-[10px] sm:text-xs font-bold text-slate-500 uppercase tracking-wider mb-1">{t('dashboard.salesVelocity')}</p>
331
+ <p className="text-2xl sm:text-3xl font-bold text-white tracking-tight">{data.metrics.sales_velocity} <span className="text-sm font-medium text-slate-500">{t('dashboard.days')}</span></p>
332
+ <p className="text-[10px] text-slate-500 mt-1">{t('dashboard.avgTimeToClose')}</p>
333
  </div>
334
  </div>
335
  </div>
 
340
  <div className="md:col-span-1 bg-[#050510]/60 backdrop-blur-xl rounded-2xl border border-indigo-500/20 p-6 relative overflow-hidden group">
341
  <div className="absolute top-0 right-0 p-4">
342
  <div className="px-2 py-1 rounded bg-emerald-500/20 border border-emerald-500/30 text-[10px] font-bold text-emerald-400 uppercase">
343
+ {t('dashboard.valueGenerated')}
344
  </div>
345
  </div>
346
  <h3 className="text-xs font-bold text-indigo-400 uppercase tracking-[0.2em] mb-4 flex items-center gap-2">
347
  <Target className="w-3 h-3" />
348
+ {t('dashboard.aiImpact')}
349
  </h3>
350
  <div className="space-y-4">
351
  <div>
352
+ <p className="text-[10px] text-slate-500 font-bold uppercase mb-1">{t('dashboard.influencedRevenue')}</p>
353
  <p className="text-2xl font-mono font-bold text-white">${(data.metrics.revenue_influenced || 0).toLocaleString()}</p>
354
  </div>
355
  <div className="pt-2 border-t border-white/5 flex justify-between items-end">
356
  <div>
357
+ <p className="text-[10px] text-slate-500 font-bold uppercase mb-1">{t('dashboard.pipelineValue')}</p>
358
  <p className="text-sm font-mono font-bold text-slate-400">${(data.metrics.pipeline_value || 0).toLocaleString()}</p>
359
  </div>
360
  <div className="text-right">
361
+ <p className="text-[10px] text-slate-500 font-bold uppercase mb-1">{t('dashboard.hoursSaved')}</p>
362
  <p className="text-xl font-mono font-bold text-emerald-400">{data.metrics.hours_saved}h</p>
363
  </div>
364
  </div>
 
369
  <div className="flex items-center justify-between mb-4">
370
  <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2">
371
  <Shield className="w-4 h-4 text-indigo-400" />
372
+ {t('dashboard.conversionHealth')}
373
  </h3>
374
  </div>
375
  <div className="grid grid-cols-3 gap-4">
376
  <div className="p-3 bg-white/5 rounded-xl border border-white/5 text-center">
377
+ <p className="text-[10px] text-slate-500 uppercase mb-1">{t('dashboard.conversionRate')}</p>
378
  <p className="text-2xl font-bold text-white">{data.metrics.conversion_rate}%</p>
379
  <p className={cn("text-[10px]", data.metrics.conversion_rate_change >= 0 ? "text-emerald-400" : "text-red-400")}>
380
  {data.metrics.conversion_rate_change > 0 ? '+' : ''}{data.metrics.conversion_rate_change}% vs prev
381
  </p>
382
  </div>
383
  <div className="p-3 bg-white/5 rounded-xl border border-white/5 text-center">
384
+ <p className="text-[10px] text-slate-500 uppercase mb-1">{t('dashboard.avgResponseTime')}</p>
385
  <p className="text-2xl font-bold text-white">{data.metrics.avg_response_time_seconds.toFixed(0)}s</p>
386
+ <p className="text-[10px] text-emerald-400">{t('dashboard.optimal')} {t('dashboard.opt')}</p>
387
  </div>
388
  <div className="p-3 bg-white/5 rounded-xl border border-white/5 text-center">
389
+ <p className="text-[10px] text-slate-500 uppercase mb-1">{t('dashboard.hotLeads')}</p>
390
  <p className="text-2xl font-bold text-orange-400">{data.metrics.hot_leads}</p>
391
+ <p className="text-[10px] text-slate-500">{t('dashboard.readyToClose')}</p>
392
  </div>
393
  </div>
394
  </div>
 
400
 
401
  {/* Leads by Channel (Donut Chart) */}
402
  <div className="bg-[#050510]/40 backdrop-blur-md rounded-2xl border border-white/10 p-6 relative overflow-hidden flex flex-col">
403
+ <h3 className="text-sm font-bold text-slate-400 uppercase tracking-wider mb-6">{t('dashboard.leadSources')}</h3>
404
  <div className="h-[250px] w-full relative z-10 flex items-center justify-center">
405
  {data.channel_stats && data.channel_stats.length > 0 ? (
406
  <ResponsiveContainer width="100%" height="100%">
407
  <PieChart>
408
  <Pie
409
+ data={data.channel_stats.map(s => ({
410
+ ...s,
411
+ channel: t(`dashboard.channel_${s.channel.toLowerCase()}`) !== `dashboard.channel_${s.channel.toLowerCase()}`
412
+ ? t(`dashboard.channel_${s.channel.toLowerCase()}`)
413
+ : s.channel
414
+ }))}
415
  cx="50%"
416
  cy="50%"
417
  innerRadius={60}
418
  outerRadius={80}
419
  paddingAngle={5}
420
  dataKey="count"
421
+ nameKey="channel"
422
  >
423
  {data.channel_stats.map((entry, index) => (
424
  <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} stroke="rgba(0,0,0,0.2)" />
 
437
  </PieChart>
438
  </ResponsiveContainer>
439
  ) : (
440
+ <div className="text-slate-500 text-sm">{t('dashboard.noChannelData')}</div>
441
  )}
442
  </div>
443
  </div>
444
 
445
  {/* Funnel Drop-off (Bar Chart) */}
446
  <div className="lg:col-span-2 bg-[#050510]/40 backdrop-blur-md rounded-2xl border border-white/10 p-6 relative overflow-hidden">
447
+ <h3 className="text-sm font-bold text-slate-400 uppercase tracking-wider mb-6">{t('dashboard.salesFunnel')}</h3>
448
  <div className="h-[250px] w-full relative z-10">
449
  <ResponsiveContainer width="100%" height="100%">
450
  <BarChart
451
+ data={data.funnel.map(f => ({ ...f, stage: translateStage(f.stage) }))}
452
  layout="vertical"
453
  margin={{ top: 5, right: 30, left: 40, bottom: 5 }}
454
  >
455
  <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" horizontal={false} />
456
  <XAxis type="number" stroke="#475569" tick={{ fill: '#475569', fontSize: 10 }} />
457
+ <YAxis type="category" dataKey="stage" stroke="#94a3b8" tick={{ fill: '#94a3b8', fontSize: 11 }} width={150} />
458
  <Tooltip
459
  cursor={{ fill: 'rgba(255,255,255,0.05)' }}
460
  contentStyle={{ backgroundColor: '#0F111A', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '12px' }}
461
  itemStyle={{ color: '#fff' }}
462
  />
463
+ <Bar dataKey="count" name={t('dashboard.totalLeads') || "Count"} fill="#8b5cf6" radius={[0, 4, 4, 0]}>
464
  {data.funnel.map((entry, index) => (
465
  <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
466
  ))}
 
476
  <div className="flex items-center justify-between mb-6">
477
  <h3 className="text-sm font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2">
478
  <Flame className="w-4 h-4 text-orange-400" />
479
+ {t('dashboard.highIntentLeads')}
480
  </h3>
481
  <button className="text-slate-500 hover:text-white transition-colors">
482
  <MoreHorizontal className="w-5 h-5" />
 
496
  </div>
497
  <div className="flex-1 min-w-0">
498
  <p className="font-medium text-white text-sm sm:text-base truncate group-hover:text-indigo-300 transition-colors">
499
+ {lead.name || t('common.unknown')}
500
  </p>
501
  <p className="text-[10px] sm:text-xs text-slate-500 truncate">
502
+ {lead.telegram_id ? 'Telegram' : lead.whatsapp_id ? 'WhatsApp' : 'Contact'} • {lead.email || lead.telegram_id || lead.whatsapp_id || t('common.noData')}
503
  </p>
504
  </div>
505
  {/* Last activity - hidden on mobile */}
506
  <div className="hidden sm:flex flex-col items-end gap-1">
507
+ <p className="text-[10px] text-slate-500">{t('dashboard.recentActivity')}</p>
508
  <p className="text-xs text-slate-400">
509
  {lead.last_message_at ? new Date(lead.last_message_at).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' }) : '-'}
510
  </p>
 
526
  ) : (
527
  <div className="text-center py-8 text-slate-500">
528
  <Flame className="w-8 h-8 mx-auto mb-2 opacity-30" />
529
+ <p className="text-sm">{t('dashboard.noHotLeads')}</p>
530
  </div>
531
  )}
532
  </div>
 
539
  <div className="bg-[#050510]/40 backdrop-blur-md rounded-2xl border border-white/10 p-6 relative overflow-hidden">
540
  <h3 className="text-sm font-bold text-slate-400 uppercase tracking-wider mb-6 flex items-center gap-2">
541
  <AlertCircle className="w-4 h-4 text-red-400" />
542
+ {t('dashboard.frequentObjections')}
543
  </h3>
544
  <div className="space-y-4">
545
  {data.top_objections && data.top_objections.length > 0 ? (
 
563
  </div>
564
  ))
565
  ) : (
566
+ <div className="text-center text-slate-500 text-sm py-4">{t('dashboard.noObjectionData')}</div>
567
  )}
568
  </div>
569
  </div>
570
 
571
  {/* Pipeline Dynamics (Area Chart) reused */}
572
  <div className="lg:col-span-2 bg-[#050510]/40 backdrop-blur-md rounded-2xl border border-white/10 p-6 relative overflow-hidden">
573
+ <h3 className="text-sm font-bold text-slate-400 uppercase tracking-wider mb-6">{t('dashboard.leadValueDynamics')}</h3>
574
  <div className="h-[300px] w-full relative z-10">
575
  <ResponsiveContainer width="100%" height="100%">
576
  <AreaChart data={data.lead_value_over_time}>
frontend/lib/i18n/translations/ru.ts CHANGED
@@ -149,6 +149,41 @@ export const ru = {
149
  noObjectionData: 'Нет данных о возражениях',
150
  retry: 'Повторить',
151
  systemError: 'Ошибка системы',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  },
153
 
154
  // Chats
 
149
  noObjectionData: 'Нет данных о возражениях',
150
  retry: 'Повторить',
151
  systemError: 'Ошибка системы',
152
+ // Advanced Metrics
153
+ revenueForecast: 'ПРОГНОЗ ВЫРУЧКИ',
154
+ weightedPipeline: 'Взвешенный пайплайн',
155
+ aiAutonomy: 'АВТОНОМИЯ AI',
156
+ fullyAutomatedChats: 'Полностью автоматизированные чаты',
157
+ salesVelocity: 'СКОРОСТЬ ПРОДАЖ',
158
+ days: 'дней',
159
+ avgTimeToClose: 'Среднее время закрытия',
160
+ aiImpact: 'ВЛИЯНИЕ AI',
161
+ valueGenerated: 'Ценность создана',
162
+ influencedRevenue: 'Влияние на выручку',
163
+ hoursSaved: 'Часов сэкономлено',
164
+ conversionHealth: 'ЗДОРОВЬЕ КОНВЕРСИИ',
165
+ optimal: 'Оптимально',
166
+ readyToClose: 'Готовы к закрытию',
167
+ highIntentLeads: 'ГОРЯЧИЕ ЛИДЫ',
168
+ leadValueDynamics: 'ДИНАМИКА ЦЕННОСТИ ЛИДОВ',
169
+ opt: '(<60с)',
170
+ // Status mappings
171
+ status_new: 'Новый',
172
+ status_contacted: 'Связались',
173
+ status_qualified: 'Квалифицирован',
174
+ status_negotiation: 'Переговоры',
175
+ status_closed: 'Закрыто',
176
+ status_closed_won: 'Успех',
177
+ status_closed_lost: 'Отказ',
178
+ status_junk: 'Спам',
179
+
180
+ // Channels
181
+ channel_manual: 'Ручной ввод',
182
+ channel_telegram: 'Telegram',
183
+ channel_whatsapp: 'WhatsApp',
184
+ channel_instagram: 'Instagram',
185
+ channel_email: 'Email',
186
+ channel_unknown: 'Неизвестно',
187
  },
188
 
189
  // Chats