All files / shared/services conversation-analytics.service.ts

0% Statements 0/104
0% Branches 0/98
0% Functions 0/11
0% Lines 0/101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
/**
 * Conversation Analytics Service
 *
 * Processes and analyzes conversation data to generate insights
 * and performance metrics for admin dashboards and reporting.
 */
 
import { v4 as uuidv4 } from 'uuid';
import type {
  ConversationAnalytics,
  Conversation
} from '@buzztrail/shared-database';
 
export interface AnalyticsData {
  connection_quality?: number;
  audio_quality?: number;
  video_quality?: number;
  latency_ms?: number;
  user_speech_time?: number;
  interaction_count?: number;
  session_duration?: number;
  completion_rate?: number;
  satisfaction_score?: number;
  task_completion_rate?: number;
  errors?: any[];
  warnings?: any[];
  recovery_attempts?: number;
}
 
export interface ConversationInsights {
  performance_rating: 'excellent' | 'good' | 'fair' | 'poor';
  improvement_suggestions: string[];
  success_indicators: string[];
  engagement_score: number;
  technical_score: number;
  overall_score: number;
}
 
export interface DatabaseManager {
  createConversationAnalytics(analytics: Partial<ConversationAnalytics>): Promise<ConversationAnalytics>;
  getConversationById(id: string): Promise<Conversation | null>;
  storeConversationInsights(conversationId: string, insights: ConversationInsights): Promise<void>;
}
 
/**
 * Conversation Analytics Service
 *
 * Analyzes conversation data and generates actionable insights
 */
export class ConversationAnalyticsService {
  private db: DatabaseManager;
 
  constructor(db: DatabaseManager) {
    this.db = db;
  }
 
  /**
   * Process conversation analytics data
   */
  async processConversationAnalytics(conversationId: string, analyticsData: AnalyticsData): Promise<void> {
    const conversation = await this.db.getConversationById(conversationId);
 
    Iif (!conversation) {
      throw new Error(`Conversation ${conversationId} not found`);
    }
 
    try {
      // Process and store analytics
      const analytics = await this.db.createConversationAnalytics({
        id: uuidv4(),
        conversation_id: conversationId,
        customer_id: conversation.customer_id,
 
        // Performance metrics
        connection_quality: analyticsData.connection_quality || 0,
        audio_quality: analyticsData.audio_quality || 0,
        video_quality: analyticsData.video_quality || 0,
        latency_ms: analyticsData.latency_ms || 0,
 
        // Engagement metrics
        user_engagement_score: this.calculateEngagementScore(analyticsData),
        conversation_satisfaction: analyticsData.satisfaction_score || 0,
        task_completion_rate: analyticsData.task_completion_rate || 0,
 
        // Technical metrics
        errors_count: analyticsData.errors?.length || 0,
        warnings_count: analyticsData.warnings?.length || 0,
        recovery_attempts: analyticsData.recovery_attempts || 0,
 
        measured_at: new Date().toISOString()
      });
 
      // Generate insights for the conversation
      await this.generateConversationInsights(conversationId, analyticsData);
 
      console.log(`✅ Analytics processed for conversation: ${conversationId}`);
 
    } catch (error) {
      console.error(`Failed to process analytics for conversation ${conversationId}:`, error);
      throw error;
    }
  }
 
  /**
   * Calculate engagement score based on various factors
   */
  private calculateEngagementScore(analyticsData: AnalyticsData): number {
    let score = 0;
 
    // User participation indicators
    Iif (analyticsData.user_speech_time && analyticsData.user_speech_time > 0) {
      score += 30; // User spoke during conversation
    }
 
    Iif (analyticsData.interaction_count && analyticsData.interaction_count > 2) {
      score += 25; // Multiple interactions
    }
 
    Iif (analyticsData.session_duration && analyticsData.session_duration > 30) {
      score += 25; // Reasonable conversation duration
    }
 
    Iif (analyticsData.completion_rate && analyticsData.completion_rate > 0.5) {
      score += 20; // Task completion
    }
 
    return Math.min(score, 100);
  }
 
  /**
   * Calculate technical performance score
   */
  private calculateTechnicalScore(analyticsData: AnalyticsData): number {
    let score = 100;
 
    // Deduct for technical issues
    Iif (analyticsData.connection_quality && analyticsData.connection_quality < 0.8) {
      score -= 20;
    }
 
    Iif (analyticsData.audio_quality && analyticsData.audio_quality < 0.8) {
      score -= 15;
    }
 
    Iif (analyticsData.video_quality && analyticsData.video_quality < 0.8) {
      score -= 10;
    }
 
    Iif (analyticsData.latency_ms && analyticsData.latency_ms > 500) {
      score -= 15;
    }
 
    Iif (analyticsData.errors && analyticsData.errors.length > 0) {
      score -= analyticsData.errors.length * 5;
    }
 
    return Math.max(score, 0);
  }
 
  /**
   * Calculate overall performance rating
   */
  private calculatePerformanceRating(analyticsData: AnalyticsData): 'excellent' | 'good' | 'fair' | 'poor' {
    const technicalScore = this.calculateTechnicalScore(analyticsData);
    const engagementScore = this.calculateEngagementScore(analyticsData);
    const overallScore = (technicalScore + engagementScore) / 2;
 
    Iif (overallScore >= 90) return 'excellent';
    Iif (overallScore >= 75) return 'good';
    Iif (overallScore >= 60) return 'fair';
    return 'poor';
  }
 
  /**
   * Generate improvement suggestions based on analytics
   */
  private generateImprovementSuggestions(analyticsData: AnalyticsData): string[] {
    const suggestions: string[] = [];
 
    // Technical improvements
    Iif (analyticsData.connection_quality && analyticsData.connection_quality < 0.8) {
      suggestions.push('Improve network connection stability');
    }
 
    Iif (analyticsData.audio_quality && analyticsData.audio_quality < 0.8) {
      suggestions.push('Check microphone settings and audio configuration');
    }
 
    Iif (analyticsData.video_quality && analyticsData.video_quality < 0.8) {
      suggestions.push('Optimize video settings for better quality');
    }
 
    Iif (analyticsData.latency_ms && analyticsData.latency_ms > 500) {
      suggestions.push('Reduce network latency for better real-time interaction');
    }
 
    // Engagement improvements
    Iif (analyticsData.user_speech_time && analyticsData.user_speech_time < 10) {
      suggestions.push('Encourage more user participation in conversations');
    }
 
    Iif (analyticsData.completion_rate && analyticsData.completion_rate < 0.5) {
      suggestions.push('Review conversation flow to improve task completion');
    }
 
    Iif (analyticsData.session_duration && analyticsData.session_duration < 30) {
      suggestions.push('Consider extending conversation duration for better engagement');
    }
 
    // Error-related improvements
    Iif (analyticsData.errors && analyticsData.errors.length > 0) {
      suggestions.push('Address technical errors to improve conversation stability');
    }
 
    Iif (analyticsData.recovery_attempts && analyticsData.recovery_attempts > 2) {
      suggestions.push('Implement better error prevention mechanisms');
    }
 
    return suggestions;
  }
 
  /**
   * Identify success indicators from analytics
   */
  private identifySuccessIndicators(analyticsData: AnalyticsData): string[] {
    const indicators: string[] = [];
 
    Iif (analyticsData.completion_rate && analyticsData.completion_rate > 0.8) {
      indicators.push('High task completion rate');
    }
 
    Iif (analyticsData.satisfaction_score && analyticsData.satisfaction_score > 4.0) {
      indicators.push('High user satisfaction');
    }
 
    Iif (analyticsData.user_speech_time && analyticsData.user_speech_time > 60) {
      indicators.push('Strong user engagement');
    }
 
    Iif (analyticsData.connection_quality && analyticsData.connection_quality > 0.9) {
      indicators.push('Excellent connection quality');
    }
 
    Iif (analyticsData.audio_quality && analyticsData.audio_quality > 0.9) {
      indicators.push('High audio quality');
    }
 
    Iif (analyticsData.errors && analyticsData.errors.length === 0) {
      indicators.push('Error-free conversation');
    }
 
    Iif (analyticsData.session_duration && analyticsData.session_duration > 120) {
      indicators.push('Extended conversation duration');
    }
 
    return indicators;
  }
 
  /**
   * Generate comprehensive conversation insights
   */
  private async generateConversationInsights(conversationId: string, analyticsData: AnalyticsData): Promise<void> {
    try {
      const engagementScore = this.calculateEngagementScore(analyticsData);
      const technicalScore = this.calculateTechnicalScore(analyticsData);
      const overallScore = (engagementScore + technicalScore) / 2;
 
      const insights: ConversationInsights = {
        performance_rating: this.calculatePerformanceRating(analyticsData),
        improvement_suggestions: this.generateImprovementSuggestions(analyticsData),
        success_indicators: this.identifySuccessIndicators(analyticsData),
        engagement_score: engagementScore,
        technical_score: technicalScore,
        overall_score: overallScore
      };
 
      // Store insights in database
      await this.db.storeConversationInsights(conversationId, insights);
 
      console.log(`✅ Insights generated for conversation: ${conversationId}`, {
        rating: insights.performance_rating,
        overall_score: insights.overall_score,
        suggestions_count: insights.improvement_suggestions.length,
        success_indicators_count: insights.success_indicators.length
      });
 
    } catch (error) {
      console.error(`Failed to generate insights for conversation ${conversationId}:`, error);
    }
  }
 
  /**
   * Get analytics summary for a conversation
   */
  async getConversationAnalyticsSummary(conversationId: string): Promise<any> {
    try {
      const conversation = await this.db.getConversationById(conversationId);
      Iif (!conversation) {
        throw new Error(`Conversation ${conversationId} not found`);
      }
 
      // This would typically query analytics from database
      // For now, return a placeholder summary
      return {
        conversation_id: conversationId,
        status: conversation.status,
        duration_seconds: conversation.duration_seconds,
        participant_count: conversation.participant_count,
        // analytics would be fetched from database
        analytics: {
          engagement_score: 85,
          technical_score: 92,
          overall_score: 88.5,
          performance_rating: 'good'
        }
      };
 
    } catch (error) {
      console.error(`Failed to get analytics summary for conversation ${conversationId}:`, error);
      throw error;
    }
  }
 
  /**
   * Get customer analytics aggregation
   */
  async getCustomerAnalytics(customerId: string, timeRange: { start: string; end: string }): Promise<any> {
    try {
      // This would typically aggregate analytics from database
      // For now, return a placeholder aggregation
      return {
        customer_id: customerId,
        time_range: timeRange,
        summary: {
          total_conversations: 45,
          average_duration: 125,
          average_engagement_score: 82,
          average_technical_score: 88,
          success_rate: 0.89
        },
        trends: {
          engagement_trend: 'increasing',
          technical_performance_trend: 'stable',
          conversation_volume_trend: 'increasing'
        }
      };
 
    } catch (error) {
      console.error(`Failed to get customer analytics for ${customerId}:`, error);
      throw error;
    }
  }
 
  /**
   * Get platform-wide analytics dashboard data
   */
  async getPlatformAnalytics(timeRange: { start: string; end: string }): Promise<any> {
    try {
      // This would typically aggregate all customer analytics
      // For now, return a placeholder dashboard
      return {
        time_range: timeRange,
        overview: {
          total_conversations: 1250,
          total_customers: 25,
          average_duration: 135,
          platform_engagement_score: 84,
          platform_technical_score: 89
        },
        performance_distribution: {
          excellent: 35,
          good: 45,
          fair: 15,
          poor: 5
        },
        top_issues: [
          'Network connectivity',
          'Audio quality',
          'User engagement'
        ],
        trending_metrics: {
          engagement_improvement: 5.2,
          technical_stability: 2.1,
          customer_satisfaction: 4.3
        }
      };
 
    } catch (error) {
      console.error('Failed to get platform analytics:', error);
      throw error;
    }
  }
}
 
export default ConversationAnalyticsService;