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 | import { Processor, Process } from '@nestjs/bull'; import { Job } from 'bull'; import { Logger } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { AIRecommendation, AIRecommendationDocument } from '../../../database/schemas/ai-recommendation.schema'; import { VectorSearchService } from '../services/vector-search.service'; import { PersonalizationService } from '../services/personalization.service'; export interface RecommendationOptimizationJob { userId: string; recommendationType: string; timestamp: Date; } export interface EmbeddingGenerationJob { productIds: string[]; priority: 'high' | 'normal' | 'low'; } export interface PersonalizationUpdateJob { userId: string; triggerEvent: string; } @Processor('recommendation-processing') export class RecommendationProcessor { private readonly logger = new Logger(RecommendationProcessor.name); constructor( @InjectModel(AIRecommendation.name) private recommendationModel: Model<AIRecommendationDocument>, private vectorSearchService: VectorSearchService, private personalizationService: PersonalizationService, ) {} @Process('optimize-recommendations') async handleRecommendationOptimization(job: Job<RecommendationOptimizationJob>): Promise<void> { this.logger.log(`Optimizing recommendations for user ${job.data.userId}`); try { // Analyze recent recommendation performance const recentRecommendations = await this.recommendationModel.find({ userId: job.data.userId, createdAt: { $gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) }, // Last 7 days }); // Calculate performance metrics const performanceMetrics = this.calculatePerformanceMetrics(recentRecommendations); // Update user personalization profile based on performance Iif (performanceMetrics.totalRecommendations > 5) { await this.updatePersonalizationWeights(job.data.userId, performanceMetrics); } // Clean up old recommendations await this.cleanupOldRecommendations(job.data.userId); this.logger.log(`Completed recommendation optimization for user ${job.data.userId}`); } catch (error) { this.logger.error(`Error optimizing recommendations for user ${job.data.userId}`, error); throw error; } } @Process('generate-embeddings') async handleEmbeddingGeneration(job: Job<EmbeddingGenerationJob>): Promise<void> { this.logger.log(`Generating embeddings for ${job.data.productIds.length} products`); try { await this.vectorSearchService.batchGenerateEmbeddings(job.data.productIds); this.logger.log(`Completed embedding generation for ${job.data.productIds.length} products`); } catch (error) { this.logger.error(`Error generating embeddings for products`, error); throw error; } } @Process('update-personalization') async handlePersonalizationUpdate(job: Job<PersonalizationUpdateJob>): Promise<void> { this.logger.log(`Updating personalization for user ${job.data.userId}`); try { // Rebuild user profile with latest interaction data await this.personalizationService.buildUserProfile(job.data.userId); this.logger.log(`Completed personalization update for user ${job.data.userId}`); } catch (error) { this.logger.error(`Error updating personalization for user ${job.data.userId}`, error); throw error; } } @Process('daily-maintenance') async handleDailyMaintenance(): Promise<void> { this.logger.log('Starting daily recommendation maintenance'); try { // Clean up expired recommendations const expiredCount = await this.recommendationModel.deleteMany({ expiresAt: { $lt: new Date() }, }); this.logger.log(`Cleaned up ${expiredCount.deletedCount} expired recommendations`); // Update embedding statistics const embeddingStats = await this.vectorSearchService.getProductEmbeddingStats(); this.logger.log(`Embedding stats: ${embeddingStats.productsWithEmbeddings}/${embeddingStats.totalProducts} products have embeddings`); // Identify products needing embedding updates Iif (embeddingStats.productsWithEmbeddings < embeddingStats.totalProducts * 0.9) { this.logger.log('Starting batch embedding update for products without embeddings'); await this.vectorSearchService.updateAllProductEmbeddings(); } this.logger.log('Completed daily recommendation maintenance'); } catch (error) { this.logger.error('Error in daily recommendation maintenance', error); throw error; } } private calculatePerformanceMetrics(recommendations: AIRecommendationDocument[]): { totalRecommendations: number; averageCTR: number; averageConversionRate: number; algorithmPerformance: Map<string, { ctr: number; conversionRate: number; count: number }>; } { const totalRecommendations = recommendations.length; let totalImpressions = 0; let totalClicks = 0; let totalConversions = 0; const algorithmPerformance = new Map<string, { impressions: number; clicks: number; conversions: number; count: number; }>(); recommendations.forEach(rec => { totalImpressions += rec.performance.impressions; totalClicks += rec.performance.clicks; totalConversions += rec.performance.conversions; const existing = algorithmPerformance.get(rec.algorithm) || { impressions: 0, clicks: 0, conversions: 0, count: 0, }; existing.impressions += rec.performance.impressions; existing.clicks += rec.performance.clicks; existing.conversions += rec.performance.conversions; existing.count += 1; algorithmPerformance.set(rec.algorithm, existing); }); const averageCTR = totalImpressions > 0 ? (totalClicks / totalImpressions) * 100 : 0; const averageConversionRate = totalClicks > 0 ? (totalConversions / totalClicks) * 100 : 0; // Calculate algorithm-specific metrics const algorithmMetrics = new Map<string, { ctr: number; conversionRate: number; count: number }>(); algorithmPerformance.forEach((data, algorithm) => { const ctr = data.impressions > 0 ? (data.clicks / data.impressions) * 100 : 0; const conversionRate = data.clicks > 0 ? (data.conversions / data.clicks) * 100 : 0; algorithmMetrics.set(algorithm, { ctr, conversionRate, count: data.count, }); }); return { totalRecommendations, averageCTR, averageConversionRate, algorithmPerformance: algorithmMetrics, }; } private async updatePersonalizationWeights( userId: string, performanceMetrics: any, ): Promise<void> { try { // This would update the user's personalization weights based on what's working // For now, we'll just log the insights const bestAlgorithm = Array.from(performanceMetrics.algorithmPerformance.entries()) .sort(([, a], [, b]) => b.conversionRate - a.conversionRate)[0]; Iif (bestAlgorithm) { this.logger.log(`Best performing algorithm for user ${userId}: ${bestAlgorithm[0]} (${bestAlgorithm[1].conversionRate.toFixed(2)}% conversion rate)`); } // In a full implementation, this would: // 1. Update user preference weights based on successful recommendations // 2. Adjust algorithm selection probabilities // 3. Fine-tune personalization parameters } catch (error) { this.logger.error(`Error updating personalization weights for user ${userId}`, error); } } private async cleanupOldRecommendations(userId: string): Promise<void> { try { // Keep only the last 100 recommendations per user const oldRecommendations = await this.recommendationModel .find({ userId }) .sort({ createdAt: -1 }) .skip(100); Iif (oldRecommendations.length > 0) { const oldIds = oldRecommendations.map(rec => rec._id); await this.recommendationModel.deleteMany({ _id: { $in: oldIds } }); this.logger.log(`Cleaned up ${oldRecommendations.length} old recommendations for user ${userId}`); } } catch (error) { this.logger.error(`Error cleaning up old recommendations for user ${userId}`, error); } } } |