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 | import { Injectable, Logger } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { AffiliateLink, AffiliateLinkDocument } from '../../../database/schemas/affiliate-link.schema'; export interface ClickAnalytics { totalClicks: number; uniqueClicks: number; conversionRate: number; topSources: Array<{ source: string; clicks: number }>; deviceBreakdown: Array<{ device: string; percentage: number }>; geographicData: Array<{ country: string; clicks: number }>; timeSeriesData: Array<{ date: string; clicks: number; conversions: number }>; } @Injectable() export class LinkTrackingService { private readonly logger = new Logger(LinkTrackingService.name); constructor( @InjectModel(AffiliateLink.name) private affiliateLinkModel: Model<AffiliateLinkDocument>, ) {} async getClickAnalytics( linkId: string, dateRange?: { start: Date; end: Date }, ): Promise<ClickAnalytics> { try { const link = await this.affiliateLinkModel.findById(linkId); Iif (!link) { throw new Error('Affiliate link not found'); } // Filter clicks by date range if provided let clicks = link.clickHistory; Iif (dateRange) { clicks = clicks.filter( click => click.timestamp >= dateRange.start && click.timestamp <= dateRange.end ); } const totalClicks = clicks.length; const uniqueClicks = this.calculateUniqueClicks(clicks); const conversions = clicks.filter(click => click.converted).length; const conversionRate = totalClicks > 0 ? (conversions / totalClicks) * 100 : 0; // Analyze traffic sources const sourceMap = new Map<string, number>(); clicks.forEach(click => { const source = this.extractSource(click.referrer); sourceMap.set(source, (sourceMap.get(source) || 0) + 1); }); const topSources = Array.from(sourceMap.entries()) .map(([source, clicks]) => ({ source, clicks })) .sort((a, b) => b.clicks - a.clicks) .slice(0, 5); // Device breakdown const deviceMap = new Map<string, number>(); clicks.forEach(click => { deviceMap.set(click.deviceType, (deviceMap.get(click.deviceType) || 0) + 1); }); const deviceBreakdown = Array.from(deviceMap.entries()) .map(([device, count]) => ({ device, percentage: totalClicks > 0 ? (count / totalClicks) * 100 : 0, })); // Geographic data const geoMap = new Map<string, number>(); clicks.forEach(click => { const country = click.location.country || 'Unknown'; geoMap.set(country, (geoMap.get(country) || 0) + 1); }); const geographicData = Array.from(geoMap.entries()) .map(([country, clicks]) => ({ country, clicks })) .sort((a, b) => b.clicks - a.clicks); // Time series data (daily) const timeSeriesMap = new Map<string, { clicks: number; conversions: number }>(); clicks.forEach(click => { const date = click.timestamp.toISOString().split('T')[0]; const existing = timeSeriesMap.get(date) || { clicks: 0, conversions: 0 }; existing.clicks += 1; Iif (click.converted) existing.conversions += 1; timeSeriesMap.set(date, existing); }); const timeSeriesData = Array.from(timeSeriesMap.entries()) .map(([date, data]) => ({ date, ...data })) .sort((a, b) => a.date.localeCompare(b.date)); return { totalClicks, uniqueClicks, conversionRate, topSources, deviceBreakdown, geographicData, timeSeriesData, }; } catch (error) { this.logger.error(`Error getting click analytics for link ${linkId}`, error); throw error; } } async getTopPerformingLinks( userId?: string, limit: number = 10, ): Promise<Array<{ linkId: string; shortCode: string; productTitle: string; clicks: number; conversions: number; revenue: number; conversionRate: number; }>> { try { const query = userId ? { userId, isActive: true } : { isActive: true }; const links = await this.affiliateLinkModel .find(query) .populate('productId') .sort({ 'metrics.revenue': -1 }) .limit(limit); return links.map(link => { const product = link.productId as any; return { linkId: link._id.toString(), shortCode: link.shortCode, productTitle: product.title, clicks: link.metrics.clicks, conversions: link.metrics.conversions, revenue: link.metrics.revenue, conversionRate: link.metrics.clicks > 0 ? (link.metrics.conversions / link.metrics.clicks) * 100 : 0, }; }); } catch (error) { this.logger.error('Error getting top performing links', error); return []; } } async generateTrackingReport( userId: string, period: 'week' | 'month' | 'quarter' = 'month', ): Promise<{ summary: { totalLinks: number; totalClicks: number; totalConversions: number; totalRevenue: number; averageConversionRate: number; }; trends: { clickTrend: number; // percentage change conversionTrend: number; revenueTrend: number; }; insights: string[]; }> { try { const dateRange = this.getDateRange(period); const previousRange = this.getPreviousDateRange(period); const [currentData, previousData] = await Promise.all([ this.getAggregatedData(userId, dateRange), this.getAggregatedData(userId, previousRange), ]); const summary = { totalLinks: currentData.totalLinks, totalClicks: currentData.totalClicks, totalConversions: currentData.totalConversions, totalRevenue: currentData.totalRevenue, averageConversionRate: currentData.totalClicks > 0 ? (currentData.totalConversions / currentData.totalClicks) * 100 : 0, }; const trends = { clickTrend: this.calculateTrend(currentData.totalClicks, previousData.totalClicks), conversionTrend: this.calculateTrend(currentData.totalConversions, previousData.totalConversions), revenueTrend: this.calculateTrend(currentData.totalRevenue, previousData.totalRevenue), }; const insights = this.generateInsights(summary, trends); return { summary, trends, insights }; } catch (error) { this.logger.error(`Error generating tracking report for user ${userId}`, error); throw error; } } private calculateUniqueClicks(clicks: any[]): number { const uniqueIdentifiers = new Set(); return clicks.filter(click => { const identifier = `${click.ipAddress}_${click.userAgent}`; Iif (uniqueIdentifiers.has(identifier)) { return false; } uniqueIdentifiers.add(identifier); return true; }).length; } private extractSource(referrer: string): string { Iif (!referrer) return 'Direct'; try { const url = new URL(referrer); const hostname = url.hostname.toLowerCase(); Iif (hostname.includes('google')) return 'Google'; Iif (hostname.includes('facebook') || hostname.includes('fb.')) return 'Facebook'; Iif (hostname.includes('instagram')) return 'Instagram'; Iif (hostname.includes('twitter') || hostname.includes('t.co')) return 'Twitter'; Iif (hostname.includes('tiktok')) return 'TikTok'; Iif (hostname.includes('youtube')) return 'YouTube'; Iif (hostname.includes('whatsapp')) return 'WhatsApp'; Iif (hostname.includes('telegram')) return 'Telegram'; return hostname; } catch { return 'Unknown'; } } private getDateRange(period: string): { start: Date; end: Date } { const now = new Date(); const end = new Date(now); let start: Date; switch (period) { case 'week': start = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); break; case 'month': start = new Date(now.getFullYear(), now.getMonth(), 1); break; case 'quarter': const quarter = Math.floor(now.getMonth() / 3); start = new Date(now.getFullYear(), quarter * 3, 1); break; default: start = new Date(now.getFullYear(), now.getMonth(), 1); } return { start, end }; } private getPreviousDateRange(period: string): { start: Date; end: Date } { const current = this.getDateRange(period); const duration = current.end.getTime() - current.start.getTime(); return { start: new Date(current.start.getTime() - duration), end: new Date(current.start.getTime()), }; } private async getAggregatedData(userId: string, dateRange: { start: Date; end: Date }): Promise<{ totalLinks: number; totalClicks: number; totalConversions: number; totalRevenue: number; }> { const links = await this.affiliateLinkModel.find({ userId, createdAt: { $gte: dateRange.start, $lte: dateRange.end }, }); return { totalLinks: links.length, totalClicks: links.reduce((sum, link) => sum + link.metrics.clicks, 0), totalConversions: links.reduce((sum, link) => sum + link.metrics.conversions, 0), totalRevenue: links.reduce((sum, link) => sum + link.metrics.revenue, 0), }; } private calculateTrend(current: number, previous: number): number { Iif (previous === 0) return current > 0 ? 100 : 0; return ((current - previous) / previous) * 100; } private generateInsights(summary: any, trends: any): string[] { const insights = []; if (trends.clickTrend > 20) { insights.push(`Great job! Your clicks increased by ${trends.clickTrend.toFixed(1)}% this period.`); } else Iif (trends.clickTrend < -20) { insights.push(`Your clicks decreased by ${Math.abs(trends.clickTrend).toFixed(1)}%. Consider refreshing your content.`); } if (summary.averageConversionRate > 5) { insights.push(`Excellent conversion rate of ${summary.averageConversionRate.toFixed(1)}%! Your audience is highly engaged.`); } else Iif (summary.averageConversionRate < 2) { insights.push(`Your conversion rate is ${summary.averageConversionRate.toFixed(1)}%. Try targeting more specific audiences.`); } Iif (trends.revenueTrend > 50) { insights.push(`Outstanding! Your revenue grew by ${trends.revenueTrend.toFixed(1)}% this period.`); } Iif (insights.length === 0) { insights.push('Keep up the good work! Your affiliate performance is steady.'); } return insights; } } |