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 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 | /**
* Admin API Service
*
* Provides comprehensive admin endpoints for conversation monitoring,
* analytics, customer management, and system oversight.
*/
import type {
Conversation,
ConversationAnalytics,
Customer,
WebhookEvent
} from '@buzztrail/shared-database';
import { ConversationAnalyticsService } from './conversation-analytics.service.js';
export interface TimeRange {
start: string;
end: string;
}
export interface ConversationFilters {
customer_id?: string;
status?: string;
environment?: string;
start_date?: string;
end_date?: string;
page: number;
limit: number;
}
export interface DashboardData {
summary: {
total_conversations: number;
active_conversations: number;
completed_conversations: number;
failed_conversations: number;
average_duration: number;
average_satisfaction: number;
success_rate: number;
};
customer_breakdown: any[];
persona_performance: any[];
error_analysis: any[];
time_series: any[];
insights: string[];
}
export interface CustomerReport {
customer: {
id: string;
name: string;
created_at: string;
};
summary: {
total_conversations: number;
successful_conversations: number;
failed_conversations: number;
total_duration: number;
average_satisfaction: number;
};
conversations: any[];
analytics: any[];
trends: any;
}
export interface DatabaseManager {
getTotalConversations(timeRange: TimeRange): Promise<number>;
getConversationsByStatus(timeRange: TimeRange): Promise<Record<string, number>>;
getConversationsByCustomer(timeRange: TimeRange): Promise<any[]>;
getAverageMetrics(timeRange: TimeRange): Promise<any>;
getTopPerformingPersonas(timeRange: TimeRange): Promise<any[]>;
getErrorAnalysis(timeRange: TimeRange): Promise<any[]>;
getCustomer(customerId: string): Promise<Customer | null>;
getCustomerConversations(customerId: string, timeRange: TimeRange): Promise<Conversation[]>;
getCustomerAnalytics(customerId: string, timeRange: TimeRange): Promise<ConversationAnalytics[]>;
getConversationsWithFilters(filters: ConversationFilters): Promise<{ conversations: Conversation[]; total: number }>;
exportConversationData(conversationId: string, format: string): Promise<string>;
}
/**
* Admin API Controller
*
* Handles all admin-related endpoints for system monitoring and management
*/
export class AdminAPIController {
private db: DatabaseManager;
private analyticsService: ConversationAnalyticsService;
constructor(db: DatabaseManager, analyticsService: ConversationAnalyticsService) {
this.db = db;
this.analyticsService = analyticsService;
}
/**
* Get all conversations with filtering and pagination
*/
async getConversations(filters: ConversationFilters): Promise<{ conversations: Conversation[]; total: number; pagination: any }> {
try {
const result = await this.db.getConversationsWithFilters(filters);
return {
conversations: result.conversations,
total: result.total,
pagination: {
page: filters.page,
limit: filters.limit,
total_pages: Math.ceil(result.total / filters.limit),
has_next: filters.page * filters.limit < result.total,
has_previous: filters.page > 1
}
};
} catch (error) {
console.error('Failed to get conversations:', error);
throw new Error(`Failed to retrieve conversations: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Generate analytics dashboard data
*/
async generateAnalyticsDashboard(timeRange: TimeRange): Promise<DashboardData> {
try {
const [
totalConversations,
conversationsByStatus,
conversationsByCustomer,
averageMetrics,
topPerformingPersonas,
errorAnalysis
] = await Promise.all([
this.db.getTotalConversations(timeRange),
this.db.getConversationsByStatus(timeRange),
this.db.getConversationsByCustomer(timeRange),
this.db.getAverageMetrics(timeRange),
this.db.getTopPerformingPersonas(timeRange),
this.db.getErrorAnalysis(timeRange)
]);
const successRate = this.calculateSuccessRate(conversationsByStatus);
return {
summary: {
total_conversations: totalConversations,
active_conversations: conversationsByStatus.active || 0,
completed_conversations: conversationsByStatus.ended || 0,
failed_conversations: conversationsByStatus.failed || 0,
average_duration: averageMetrics.duration || 0,
average_satisfaction: averageMetrics.satisfaction || 0,
success_rate: successRate
},
customer_breakdown: conversationsByCustomer,
persona_performance: topPerformingPersonas,
error_analysis: errorAnalysis,
time_series: await this.generateTimeSeriesData(timeRange),
insights: await this.generateDashboardInsights(timeRange)
};
} catch (error) {
console.error('Failed to generate analytics dashboard:', error);
throw new Error(`Failed to generate dashboard: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Generate customer report with detailed analytics
*/
async generateCustomerReport(customerId: string, timeRange: TimeRange): Promise<CustomerReport> {
try {
const customer = await this.db.getCustomer(customerId);
Iif (!customer) {
throw new Error(`Customer ${customerId} not found`);
}
const conversations = await this.db.getCustomerConversations(customerId, timeRange);
const analytics = await this.db.getCustomerAnalytics(customerId, timeRange);
return {
customer: {
id: customer.customer_id,
name: customer.customer_name,
created_at: customer.created_at
},
summary: {
total_conversations: conversations.length,
successful_conversations: conversations.filter(c => c.status === 'ended').length,
failed_conversations: conversations.filter(c => c.status === 'failed').length,
total_duration: conversations.reduce((sum, c) => sum + (c.duration_seconds || 0), 0),
average_satisfaction: this.calculateAverageSatisfaction(analytics)
},
conversations: conversations.map(c => ({
id: c.id,
conversation_name: c.conversation_name,
persona_id: c.persona_id,
status: c.status,
duration_seconds: c.duration_seconds,
created_at: c.created_at,
ended_at: c.ended_at,
shutdown_reason: c.shutdown_reason
})),
analytics,
trends: await this.generateCustomerTrends(customerId, timeRange)
};
} catch (error) {
console.error(`Failed to generate customer report for ${customerId}:`, error);
throw new Error(`Failed to generate customer report: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Export conversation data in specified format
*/
async exportConversationData(conversationId: string, format: 'json' | 'csv' = 'json'): Promise<string> {
try {
return await this.db.exportConversationData(conversationId, format);
} catch (error) {
console.error(`Failed to export conversation ${conversationId}:`, error);
throw new Error(`Failed to export conversation data: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Get system health and status
*/
async getSystemStatus(): Promise<any> {
try {
const now = new Date().toISOString();
const last24Hours = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
const recentActivity = await this.db.getTotalConversations({
start: last24Hours,
end: now
});
return {
status: 'healthy',
timestamp: now,
uptime: process.uptime(),
memory_usage: process.memoryUsage(),
recent_activity: {
conversations_24h: recentActivity,
active_customers: 0, // Would be calculated from database
system_errors: 0 // Would be calculated from error logs
},
services: {
database: 'connected',
webhook_handler: 'active',
analytics_processor: 'active',
admin_api: 'active'
}
};
} catch (error) {
console.error('Failed to get system status:', error);
return {
status: 'degraded',
timestamp: new Date().toISOString(),
error: error instanceof Error ? error.message : 'Unknown error'
};
}
}
/**
* Get webhook processing statistics
*/
async getWebhookStats(timeRange: TimeRange): Promise<any> {
try {
// This would typically query webhook events from database
return {
time_range: timeRange,
total_webhooks: 156,
processed_successfully: 148,
failed_processing: 8,
average_processing_time: 250,
retry_count: 12,
event_types: {
'conversation.started': 45,
'conversation.ended': 43,
'participant.joined': 35,
'participant.left': 33
}
};
} catch (error) {
console.error('Failed to get webhook stats:', error);
throw new Error(`Failed to get webhook statistics: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Calculate success rate from conversation status data
*/
private calculateSuccessRate(conversationsByStatus: Record<string, number>): number {
const total = Object.values(conversationsByStatus).reduce((sum, count) => sum + count, 0);
const successful = (conversationsByStatus.ended || 0);
return total > 0 ? Math.round((successful / total) * 100) / 100 : 0;
}
/**
* Calculate average satisfaction from analytics data
*/
private calculateAverageSatisfaction(analytics: ConversationAnalytics[]): number {
Iif (analytics.length === 0) return 0;
const total = analytics.reduce((sum, a) => sum + (a.conversation_satisfaction || 0), 0);
return Math.round((total / analytics.length) * 100) / 100;
}
/**
* Generate time series data for dashboard charts
*/
private async generateTimeSeriesData(timeRange: TimeRange): Promise<any[]> {
try {
// This would typically query database for time-series data
// For now, return mock data
const days = this.getDaysBetween(timeRange.start, timeRange.end);
return days.map((day, index) => ({
date: day,
conversations: Math.floor(Math.random() * 20) + 5,
success_rate: 0.85 + Math.random() * 0.1,
average_duration: 120 + Math.random() * 60
}));
} catch (error) {
console.error('Failed to generate time series data:', error);
return [];
}
}
/**
* Generate dashboard insights
*/
private async generateDashboardInsights(timeRange: TimeRange): Promise<string[]> {
try {
// This would typically analyze trends and generate insights
return [
'Conversation success rate increased by 5% this week',
'Average conversation duration is optimal at 2.5 minutes',
'Peak usage occurs between 2-4 PM EST',
'Audio quality improvements needed for 12% of conversations',
'Customer engagement scores trending upward'
];
} catch (error) {
console.error('Failed to generate dashboard insights:', error);
return [];
}
}
/**
* Generate customer-specific trends
*/
private async generateCustomerTrends(customerId: string, timeRange: TimeRange): Promise<any> {
try {
// This would typically analyze customer-specific data
return {
engagement_trend: 'increasing',
conversation_volume: 'stable',
satisfaction_trend: 'improving',
technical_performance: 'excellent',
growth_rate: 0.15,
retention_score: 0.92
};
} catch (error) {
console.error(`Failed to generate trends for customer ${customerId}:`, error);
return {
engagement_trend: 'unknown',
conversation_volume: 'unknown',
satisfaction_trend: 'unknown',
technical_performance: 'unknown'
};
}
}
/**
* Get default start date (30 days ago)
*/
getDefaultStartDate(): string {
const date = new Date();
date.setDate(date.getDate() - 30);
return date.toISOString();
}
/**
* Get days between two dates for time series
*/
private getDaysBetween(startDate: string, endDate: string): string[] {
const days: string[] = [];
const start = new Date(startDate);
const end = new Date(endDate);
for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
days.push(d.toISOString().split('T')[0]);
}
return days;
}
/**
* Format response with standard admin API structure
*/
formatResponse(data: any, success: boolean = true, message?: string): any {
return {
success,
timestamp: new Date().toISOString(),
message,
data
};
}
/**
* Handle admin API errors consistently
*/
handleError(error: Error, context: string): never {
console.error(`Admin API Error (${context}):`, error);
throw new Error(`${context}: ${error.message}`);
}
}
export default AdminAPIController; |