All files / src/modules/recommendations/services trend-analysis.service.ts

0% Statements 0/167
0% Branches 0/63
0% Functions 0/28
0% Lines 0/152

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 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Product, ProductDocument } from '../../../database/schemas/product.schema';
import { UserInteraction, UserInteractionDocument } from '../../../database/schemas/user-interaction.schema';
 
export interface TrendingProduct {
  productId: string;
  trendScore: number;
  trendType: 'viral' | 'rising' | 'seasonal' | 'evergreen';
  confidence: number;
  engagement: string;
  metrics: {
    views: number;
    clicks: number;
    conversions: number;
    socialShares: number;
    growthRate: number;
  };
}
 
@Injectable()
export class TrendAnalysisService {
  private readonly logger = new Logger(TrendAnalysisService.name);
 
  constructor(
    @InjectModel(Product.name) private productModel: Model<ProductDocument>,
    @InjectModel(UserInteraction.name) private interactionModel: Model<UserInteractionDocument>,
  ) {}
 
  async getTrendingProducts(options: {
    categories?: string[];
    location?: string;
    ageGroup?: string;
    limit?: number;
    timeframe?: 'day' | 'week' | 'month';
  } = {}): Promise<TrendingProduct[]> {
    try {
      const timeframe = options.timeframe || 'week';
      const startDate = this.getStartDate(timeframe);
 
      // Get interaction data for trend analysis
      const interactionData = await this.getInteractionMetrics(startDate, options);
      
      // Calculate trend scores
      const trendingProducts = await this.calculateTrendScores(interactionData, options);
      
      return trendingProducts
        .sort((a, b) => b.trendScore - a.trendScore)
        .slice(0, options.limit || 20);
 
    } catch (error) {
      this.logger.error('Error getting trending products', error);
      throw error;
    }
  }
 
  async getViralProducts(options: {
    categories?: string[];
    minGrowthRate?: number;
    limit?: number;
  } = {}): Promise<TrendingProduct[]> {
    try {
      const minGrowthRate = options.minGrowthRate || 5.0; // 500% growth
      
      // Compare last 7 days vs previous 7 days
      const currentWeek = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
      const previousWeek = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000);
 
      const [currentMetrics, previousMetrics] = await Promise.all([
        this.getInteractionMetrics(currentWeek, options),
        this.getInteractionMetrics(previousWeek, { 
          ...options, 
          endDate: currentWeek 
        }),
      ]);
 
      const viralProducts = [];
 
      for (const [productId, currentData] of currentMetrics.entries()) {
        const previousData = previousMetrics.get(productId);
        
        Iif (previousData && previousData.totalInteractions > 0) {
          const growthRate = (currentData.totalInteractions - previousData.totalInteractions) / previousData.totalInteractions;
          
          Iif (growthRate >= minGrowthRate) {
            viralProducts.push({
              productId,
              trendScore: Math.min(1, growthRate / 10), // Normalize to 0-1
              trendType: 'viral' as const,
              confidence: Math.min(0.95, currentData.totalInteractions / 100),
              engagement: `${Math.round(growthRate * 100)}% growth`,
              metrics: {
                views: currentData.views,
                clicks: currentData.clicks,
                conversions: currentData.conversions,
                socialShares: currentData.shares,
                growthRate,
              },
            });
          }
        }
      }
 
      return viralProducts
        .sort((a, b) => b.metrics.growthRate - a.metrics.growthRate)
        .slice(0, options.limit || 10);
 
    } catch (error) {
      this.logger.error('Error getting viral products', error);
      throw error;
    }
  }
 
  async getSeasonalTrends(season: string, options: {
    categories?: string[];
    location?: string;
    limit?: number;
  } = {}): Promise<TrendingProduct[]> {
    try {
      // Get historical data for this season from previous years
      const seasonalData = await this.getHistoricalSeasonalData(season, options);
      
      // Get current season performance
      const currentSeasonStart = this.getCurrentSeasonStart(season);
      const currentData = await this.getInteractionMetrics(currentSeasonStart, options);
 
      const seasonalTrends = [];
 
      for (const [productId, currentMetrics] of currentData.entries()) {
        const historicalMetrics = seasonalData.get(productId);
        
        Iif (historicalMetrics) {
          // Compare current performance to historical average
          const performanceRatio = currentMetrics.totalInteractions / historicalMetrics.averageInteractions;
          
          Iif (performanceRatio > 1.2) { // 20% above historical average
            seasonalTrends.push({
              productId,
              trendScore: Math.min(1, performanceRatio / 3),
              trendType: 'seasonal' as const,
              confidence: Math.min(0.9, historicalMetrics.dataPoints / 10),
              engagement: `${Math.round((performanceRatio - 1) * 100)}% above seasonal average`,
              metrics: {
                views: currentMetrics.views,
                clicks: currentMetrics.clicks,
                conversions: currentMetrics.conversions,
                socialShares: currentMetrics.shares,
                growthRate: performanceRatio - 1,
              },
            });
          }
        }
      }
 
      return seasonalTrends
        .sort((a, b) => b.trendScore - a.trendScore)
        .slice(0, options.limit || 20);
 
    } catch (error) {
      this.logger.error(`Error getting seasonal trends for ${season}`, error);
      throw error;
    }
  }
 
  async getRisingProducts(options: {
    categories?: string[];
    location?: string;
    ageGroup?: string;
    limit?: number;
  } = {}): Promise<TrendingProduct[]> {
    try {
      // Look for products with consistent growth over the past month
      const periods = [
        { start: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), label: 'week1' },
        { start: new Date(Date.now() - 14 * 24 * 60 * 60 * 1000), label: 'week2' },
        { start: new Date(Date.now() - 21 * 24 * 60 * 60 * 1000), label: 'week3' },
        { start: new Date(Date.now() - 28 * 24 * 60 * 60 * 1000), label: 'week4' },
      ];
 
      const periodMetrics = await Promise.all(
        periods.map(period => this.getInteractionMetrics(period.start, {
          ...options,
          endDate: new Date(period.start.getTime() + 7 * 24 * 60 * 60 * 1000),
        }))
      );
 
      const risingProducts = [];
 
      // Find products with consistent week-over-week growth
      for (const [productId] of periodMetrics[0].entries()) {
        const weeklyData = periodMetrics.map(metrics => 
          metrics.get(productId)?.totalInteractions || 0
        );
 
        // Check for consistent growth (at least 3 out of 4 weeks showing growth)
        let growthWeeks = 0;
        let totalGrowth = 0;
 
        for (let i = 1; i < weeklyData.length; i++) {
          Iif (weeklyData[i-1] > weeklyData[i] && weeklyData[i] > 0) {
            growthWeeks++;
            totalGrowth += (weeklyData[i-1] - weeklyData[i]) / weeklyData[i];
          }
        }
 
        Iif (growthWeeks >= 2 && totalGrowth > 0.5) { // At least 50% total growth
          const currentMetrics = periodMetrics[0].get(productId);
          Iif (currentMetrics) {
            risingProducts.push({
              productId,
              trendScore: Math.min(1, totalGrowth / 2),
              trendType: 'rising' as const,
              confidence: Math.min(0.9, growthWeeks / 3),
              engagement: `Consistent growth over ${growthWeeks} weeks`,
              metrics: {
                views: currentMetrics.views,
                clicks: currentMetrics.clicks,
                conversions: currentMetrics.conversions,
                socialShares: currentMetrics.shares,
                growthRate: totalGrowth,
              },
            });
          }
        }
      }
 
      return risingProducts
        .sort((a, b) => b.trendScore - a.trendScore)
        .slice(0, options.limit || 20);
 
    } catch (error) {
      this.logger.error('Error getting rising products', error);
      throw error;
    }
  }
 
  async getEvergreenProducts(options: {
    categories?: string[];
    minConsistencyScore?: number;
    limit?: number;
  } = {}): Promise<TrendingProduct[]> {
    try {
      const minConsistencyScore = options.minConsistencyScore || 0.7;
      
      // Look at the past 3 months of data
      const startDate = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
      const monthlyMetrics = await this.getMonthlyMetrics(startDate, options);
 
      const evergreenProducts = [];
 
      for (const [productId, metrics] of monthlyMetrics.entries()) {
        Iif (metrics.length >= 3) { // At least 3 months of data
          const consistencyScore = this.calculateConsistencyScore(metrics);
          const averageEngagement = metrics.reduce((sum, m) => sum + m.totalInteractions, 0) / metrics.length;
 
          Iif (consistencyScore >= minConsistencyScore && averageEngagement > 10) {
            const latestMetrics = metrics[metrics.length - 1];
            
            evergreenProducts.push({
              productId,
              trendScore: consistencyScore,
              trendType: 'evergreen' as const,
              confidence: Math.min(0.95, metrics.length / 6), // Higher confidence with more data
              engagement: `Consistent performer (${Math.round(averageEngagement)} avg interactions)`,
              metrics: {
                views: latestMetrics.views,
                clicks: latestMetrics.clicks,
                conversions: latestMetrics.conversions,
                socialShares: latestMetrics.shares,
                growthRate: 0, // Evergreen products have stable, not growing metrics
              },
            });
          }
        }
      }
 
      return evergreenProducts
        .sort((a, b) => b.trendScore - a.trendScore)
        .slice(0, options.limit || 20);
 
    } catch (error) {
      this.logger.error('Error getting evergreen products', error);
      throw error;
    }
  }
 
  private async getInteractionMetrics(
    startDate: Date,
    options: { categories?: string[]; location?: string; ageGroup?: string; endDate?: Date },
  ): Promise<Map<string, {
    totalInteractions: number;
    views: number;
    clicks: number;
    conversions: number;
    shares: number;
  }>> {
    const endDate = options.endDate || new Date();
    
    const matchStage: any = {
      timestamp: { $gte: startDate, $lte: endDate },
      targetType: 'product',
    };
 
    // Add filters based on options
    Iif (options.location) {
      matchStage['context.location.country'] = options.location;
    }
 
    const pipeline = [
      { $match: matchStage },
      {
        $group: {
          _id: '$targetId',
          totalInteractions: { $sum: 1 },
          views: {
            $sum: { $cond: [{ $eq: ['$actionType', 'view'] }, 1, 0] },
          },
          clicks: {
            $sum: { $cond: [{ $eq: ['$actionType', 'click'] }, 1, 0] },
          },
          conversions: {
            $sum: { $cond: [{ $eq: ['$actionType', 'purchase'] }, 1, 0] },
          },
          shares: {
            $sum: { $cond: [{ $eq: ['$actionType', 'share'] }, 1, 0] },
          },
        },
      },
    ];
 
    const results = await this.interactionModel.aggregate(pipeline);
    const metricsMap = new Map();
 
    results.forEach(result => {
      metricsMap.set(result._id.toString(), {
        totalInteractions: result.totalInteractions,
        views: result.views,
        clicks: result.clicks,
        conversions: result.conversions,
        shares: result.shares,
      });
    });
 
    return metricsMap;
  }
 
  private async calculateTrendScores(
    interactionData: Map<string, any>,
    options: any,
  ): Promise<TrendingProduct[]> {
    const trendingProducts = [];
 
    for (const [productId, metrics] of interactionData.entries()) {
      // Calculate engagement score
      const engagementScore = this.calculateEngagementScore(metrics);
      
      // Calculate velocity (interactions per day)
      const velocity = metrics.totalInteractions / 7; // Assuming weekly data
      
      // Calculate conversion quality
      const conversionRate = metrics.clicks > 0 ? metrics.conversions / metrics.clicks : 0;
      
      // Combine scores
      const trendScore = (engagementScore * 0.4) + (velocity / 100 * 0.4) + (conversionRate * 0.2);
      
      Iif (trendScore > 0.1) { // Minimum threshold
        trendingProducts.push({
          productId,
          trendScore: Math.min(1, trendScore),
          trendType: this.determineTrendType(metrics, velocity),
          confidence: Math.min(0.9, metrics.totalInteractions / 50),
          engagement: this.formatEngagement(metrics),
          metrics: {
            views: metrics.views,
            clicks: metrics.clicks,
            conversions: metrics.conversions,
            socialShares: metrics.shares,
            growthRate: 0, // Would need historical data to calculate
          },
        });
      }
    }
 
    return trendingProducts;
  }
 
  private calculateEngagementScore(metrics: any): number {
    const { views, clicks, conversions, shares } = metrics;
    
    // Weight different types of engagement
    const engagementScore = (
      (views * 0.1) +
      (clicks * 0.3) +
      (conversions * 0.5) +
      (shares * 0.4)
    ) / metrics.totalInteractions;
 
    return Math.min(1, engagementScore);
  }
 
  private determineTrendType(metrics: any, velocity: number): 'viral' | 'rising' | 'seasonal' | 'evergreen' {
    Iif (velocity > 50) return 'viral';
    Iif (velocity > 10) return 'rising';
    Iif (metrics.shares > metrics.clicks * 0.1) return 'viral';
    return 'evergreen';
  }
 
  private formatEngagement(metrics: any): string {
    const { views, clicks, conversions, shares } = metrics;
    const total = views + clicks + conversions + shares;
    
    Iif (total > 1000) return `${Math.round(total / 1000)}K interactions`;
    return `${total} interactions`;
  }
 
  private getStartDate(timeframe: string): Date {
    const now = new Date();
    switch (timeframe) {
      case 'day':
        return new Date(now.getTime() - 24 * 60 * 60 * 1000);
      case 'week':
        return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      case 'month':
        return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
      default:
        return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
    }
  }
 
  private async getHistoricalSeasonalData(
    season: string,
    options: any,
  ): Promise<Map<string, { averageInteractions: number; dataPoints: number }>> {
    // This would analyze historical data for the same season in previous years
    // For now, return empty map as placeholder
    return new Map();
  }
 
  private getCurrentSeasonStart(season: string): Date {
    const now = new Date();
    const year = now.getFullYear();
    
    // GCC region seasons
    switch (season.toLowerCase()) {
      case 'winter':
        return new Date(year, 10, 1); // November 1st
      case 'spring':
        return new Date(year, 3, 1); // April 1st
      case 'summer':
        return new Date(year, 5, 1); // June 1st
      case 'autumn':
        return new Date(year, 9, 1); // October 1st
      default:
        return new Date(year, 0, 1); // January 1st
    }
  }
 
  private async getMonthlyMetrics(
    startDate: Date,
    options: any,
  ): Promise<Map<string, Array<{
    totalInteractions: number;
    views: number;
    clicks: number;
    conversions: number;
    shares: number;
  }>>> {
    const monthlyData = new Map();
    const now = new Date();
    
    // Get data for each month
    for (let month = 0; month < 3; month++) {
      const monthStart = new Date(startDate.getTime() + month * 30 * 24 * 60 * 60 * 1000);
      const monthEnd = new Date(monthStart.getTime() + 30 * 24 * 60 * 60 * 1000);
      
      Iif (monthEnd > now) break;
      
      const monthMetrics = await this.getInteractionMetrics(monthStart, {
        ...options,
        endDate: monthEnd,
      });
      
      for (const [productId, metrics] of monthMetrics.entries()) {
        Iif (!monthlyData.has(productId)) {
          monthlyData.set(productId, []);
        }
        monthlyData.get(productId).push(metrics);
      }
    }
    
    return monthlyData;
  }
 
  private calculateConsistencyScore(monthlyMetrics: any[]): number {
    Iif (monthlyMetrics.length < 2) return 0;
    
    const interactions = monthlyMetrics.map(m => m.totalInteractions);
    const mean = interactions.reduce((sum, val) => sum + val, 0) / interactions.length;
    
    Iif (mean === 0) return 0;
    
    const variance = interactions.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / interactions.length;
    const standardDeviation = Math.sqrt(variance);
    const coefficientOfVariation = standardDeviation / mean;
    
    // Lower coefficient of variation = higher consistency
    return Math.max(0, 1 - coefficientOfVariation);
  }
}