import { apiClient } from '../api-client'; import type { ApiResponse, PaginatedResponse, BehavioralEvent, DashboardData, ProductAffinity, CustomerJourneyStep, SearchQuery, CartAbandonment, ConversionFunnel, CustomerSegmentation, CampaignPerformance, DeviceAnalytics, LocationAnalytics, EventStats, EventQueryParams, DateRangeParams, } from '../types'; class AnalyticsClient { private cache: Map = new Map(); private cacheTTL = 300000; // 5 minutes /** * Get cached data or fetch from API */ private async getCached( key: string, fetcher: () => Promise, ttl: number = this.cacheTTL ): Promise { const cached = this.cache.get(key); if (cached && Date.now() - cached.timestamp < ttl) { return cached.data; } const data = await fetcher(); this.cache.set(key, { data, timestamp: Date.now() }); return data; } /** * Clear cache */ public clearCache(key?: string): void { if (key) { this.cache.delete(key); } else { this.cache.clear(); } } /** * Get comprehensive dashboard data */ public async getDashboard(params?: DateRangeParams): Promise> { const queryString = new URLSearchParams(params as any).toString(); const cacheKey = `dashboard:${queryString}`; return this.getCached(cacheKey, () => apiClient.get>(`/api/behavioral/dashboard?${queryString}`) ); } /** * Get behavioral events with filtering and pagination */ public async getEvents( params?: EventQueryParams ): Promise>> { const queryString = new URLSearchParams(params as any).toString(); return apiClient.get>>( `/api/behavioral/events?${queryString}` ); } /** * Get event statistics */ public async getEventStats(params?: DateRangeParams): Promise> { const queryString = new URLSearchParams(params as any).toString(); const cacheKey = `stats:${queryString}`; return this.getCached(cacheKey, () => apiClient.get>(`/api/behavioral/stats?${queryString}`) ); } /** * Get products frequently viewed together */ public async getProductAffinity( productId: number, limit: number = 10 ): Promise> { const cacheKey = `product-affinity:${productId}:${limit}`; return this.getCached(cacheKey, () => apiClient.get>( `/api/behavioral/products/affinity?product_id=${productId}&limit=${limit}` ) ); } /** * Get complete customer journey for a session */ public async getCustomerJourney( sessionId: string ): Promise> { const cacheKey = `customer-journey:${sessionId}`; return this.getCached( cacheKey, () => apiClient.get>( `/api/behavioral/customer-journey?session_id=${sessionId}` ), 180000 // 3 minutes ); } /** * Get most popular search queries */ public async getTopSearches( params?: DateRangeParams & { limit?: number } ): Promise> { const queryString = new URLSearchParams(params as any).toString(); const cacheKey = `top-searches:${queryString}`; return this.getCached(cacheKey, () => apiClient.get>(`/api/behavioral/search/top?${queryString}`) ); } /** * Get cart abandonment rate and statistics */ public async getCartAbandonment( params?: DateRangeParams ): Promise> { const queryString = new URLSearchParams(params as any).toString(); const cacheKey = `cart-abandonment:${queryString}`; return this.getCached(cacheKey, () => apiClient.get>( `/api/behavioral/cart/abandonment?${queryString}` ) ); } /** * Get conversion funnel (views -> cart -> checkout -> order) */ public async getConversionFunnel( params?: DateRangeParams ): Promise> { const queryString = new URLSearchParams(params as any).toString(); const cacheKey = `conversion-funnel:${queryString}`; return this.getCached(cacheKey, () => apiClient.get>( `/api/behavioral/funnel/conversion?${queryString}` ) ); } /** * Get customer segmentation by engagement level */ public async getCustomerSegmentation( params?: DateRangeParams ): Promise> { const queryString = new URLSearchParams(params as any).toString(); const cacheKey = `customer-segmentation:${queryString}`; return this.getCached(cacheKey, () => apiClient.get>( `/api/behavioral/customers/segmentation?${queryString}` ) ); } /** * Get performance metrics for a specific marketing campaign */ public async getCampaignPerformance( campaign: string, params?: DateRangeParams ): Promise> { const queryString = new URLSearchParams({ ...params, campaign } as any).toString(); const cacheKey = `campaign-performance:${queryString}`; return this.getCached(cacheKey, () => apiClient.get>( `/api/behavioral/campaigns/performance?${queryString}` ) ); } /** * Get analytics by device type, browser, and platform */ public async getDeviceAnalytics( params?: DateRangeParams ): Promise> { const queryString = new URLSearchParams(params as any).toString(); const cacheKey = `device-analytics:${queryString}`; return this.getCached(cacheKey, () => apiClient.get>( `/api/behavioral/device-analytics?${queryString}` ) ); } /** * Get analytics by country and city */ public async getLocationAnalytics( params?: DateRangeParams ): Promise> { const queryString = new URLSearchParams(params as any).toString(); const cacheKey = `location-analytics:${queryString}`; return this.getCached(cacheKey, () => apiClient.get>( `/api/behavioral/location-analytics?${queryString}` ) ); } /** * Helper: Get today's date range */ public getTodayRange(): DateRangeParams { const today = new Date().toISOString().split('T')[0]; return { start_date: today, end_date: today }; } /** * Helper: Get last N days date range */ public getLastNDaysRange(days: number): DateRangeParams { const endDate = new Date(); const startDate = new Date(); startDate.setDate(startDate.getDate() - days); return { start_date: startDate.toISOString().split('T')[0], end_date: endDate.toISOString().split('T')[0], }; } /** * Helper: Get this month's date range */ public getThisMonthRange(): DateRangeParams { const now = new Date(); const startDate = new Date(now.getFullYear(), now.getMonth(), 1); const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0); return { start_date: startDate.toISOString().split('T')[0], end_date: endDate.toISOString().split('T')[0], }; } /** * Helper: Get last month's date range */ public getLastMonthRange(): DateRangeParams { const now = new Date(); const startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1); const endDate = new Date(now.getFullYear(), now.getMonth(), 0); return { start_date: startDate.toISOString().split('T')[0], end_date: endDate.toISOString().split('T')[0], }; } /** * Batch fetch multiple analytics endpoints */ public async getBatchAnalytics(params?: DateRangeParams) { const [ dashboard, stats, cartAbandonment, conversionFunnel, segmentation, deviceAnalytics, locationAnalytics, ] = await Promise.all([ this.getDashboard(params), this.getEventStats(params), this.getCartAbandonment(params), this.getConversionFunnel(params), this.getCustomerSegmentation(params), this.getDeviceAnalytics(params), this.getLocationAnalytics(params), ]); return { dashboard: dashboard.data, stats: stats.data, cartAbandonment: cartAbandonment.data, conversionFunnel: conversionFunnel.data, segmentation: segmentation.data, deviceAnalytics: deviceAnalytics.data, locationAnalytics: locationAnalytics.data, }; } } export const analyticsClient = new AnalyticsClient();