All files / src/modules/affiliate/processors affiliate.processor.ts

0% Statements 0/136
0% Branches 0/32
0% Functions 0/18
0% Lines 0/129

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
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 { AffiliateLink, AffiliateLinkDocument } from '../../../database/schemas/affiliate-link.schema';
import { Commission, CommissionDocument } from '../../../database/schemas/commission.schema';
import { InfluencerProfile, InfluencerProfileDocument } from '../../../database/schemas/influencer-profile.schema';
import { InfluencerService } from '../services/influencer.service';
 
export interface LinkCleanupJob {
  type: 'link-cleanup';
}
 
export interface MetricsUpdateJob {
  type: 'metrics-update';
  influencerId?: string;
}
 
export interface CommissionProcessingJob {
  type: 'commission-processing';
  commissionId: string;
}
 
export interface PerformanceAnalysisJob {
  type: 'performance-analysis';
  period: 'daily' | 'weekly' | 'monthly';
}
 
@Processor('affiliate-processing')
export class AffiliateProcessor {
  private readonly logger = new Logger(AffiliateProcessor.name);
 
  constructor(
    @InjectModel(AffiliateLink.name) private affiliateLinkModel: Model<AffiliateLinkDocument>,
    @InjectModel(Commission.name) private commissionModel: Model<CommissionDocument>,
    @InjectModel(InfluencerProfile.name) private influencerModel: Model<InfluencerProfileDocument>,
    private influencerService: InfluencerService,
  ) {}
 
  @Process('link-cleanup')
  async handleLinkCleanup(job: Job<LinkCleanupJob>): Promise<void> {
    this.logger.log('Starting affiliate link cleanup job');
 
    try {
      // Remove expired links
      const expiredLinks = await this.affiliateLinkModel.find({
        expiresAt: { $lt: new Date() },
        isActive: true,
      });
 
      for (const link of expiredLinks) {
        link.isActive = false;
        await link.save();
      }
 
      // Clean up old click history (keep only last 90 days)
      const ninetyDaysAgo = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
      
      await this.affiliateLinkModel.updateMany(
        {},
        {
          $pull: {
            clickHistory: {
              timestamp: { $lt: ninetyDaysAgo },
            },
          },
        }
      );
 
      this.logger.log(`Cleaned up ${expiredLinks.length} expired links and old click history`);
    } catch (error) {
      this.logger.error('Error in link cleanup job', error);
      throw error;
    }
  }
 
  @Process('metrics-update')
  async handleMetricsUpdate(job: Job<MetricsUpdateJob>): Promise<void> {
    this.logger.log('Starting metrics update job');
 
    try {
      if (job.data.influencerId) {
        // Update specific influencer metrics
        await this.influencerService.updateInfluencerMetrics(job.data.influencerId);
        this.logger.log(`Updated metrics for influencer ${job.data.influencerId}`);
      } else {
        // Update all active influencer metrics
        const activeInfluencers = await this.influencerModel.find({ status: 'active' });
        
        for (const influencer of activeInfluencers) {
          try {
            await this.influencerService.updateInfluencerMetrics(influencer._id.toString());
          } catch (error) {
            this.logger.error(`Failed to update metrics for influencer ${influencer._id}`, error);
          }
        }
 
        this.logger.log(`Updated metrics for ${activeInfluencers.length} influencers`);
      }
    } catch (error) {
      this.logger.error('Error in metrics update job', error);
      throw error;
    }
  }
 
  @Process('commission-processing')
  async handleCommissionProcessing(job: Job<CommissionProcessingJob>): Promise<void> {
    this.logger.log(`Processing commission ${job.data.commissionId}`);
 
    try {
      const commission = await this.commissionModel.findById(job.data.commissionId);
      Iif (!commission) {
        throw new Error('Commission not found');
      }
 
      // Validate commission data
      Iif (commission.status !== 'pending') {
        this.logger.warn(`Commission ${commission._id} is not in pending status`);
        return;
      }
 
      // Check for potential fraud indicators
      const fraudScore = await this.calculateFraudScore(commission);
      
      Iif (fraudScore > 0.7) {
        commission.status = 'disputed';
        commission.statusHistory = {
          ...commission.statusHistory,
          disputedAt: new Date(),
          reason: `High fraud score: ${fraudScore}`,
        };
        await commission.save();
        
        this.logger.warn(`Commission ${commission._id} flagged for fraud review`);
        return;
      }
 
      // Auto-approve low-risk commissions
      Iif (fraudScore < 0.3 && commission.commissionAmount < 100) {
        commission.status = 'confirmed';
        commission.statusHistory = {
          ...commission.statusHistory,
          confirmedAt: new Date(),
          reason: 'Auto-approved (low risk)',
        };
        await commission.save();
        
        this.logger.log(`Commission ${commission._id} auto-approved`);
      }
 
    } catch (error) {
      this.logger.error(`Error processing commission ${job.data.commissionId}`, error);
      throw error;
    }
  }
 
  @Process('performance-analysis')
  async handlePerformanceAnalysis(job: Job<PerformanceAnalysisJob>): Promise<void> {
    this.logger.log(`Starting ${job.data.period} performance analysis`);
 
    try {
      const dateRange = this.getDateRange(job.data.period);
      
      // Analyze affiliate link performance
      const linkPerformance = await this.analyzeAffiliateLinks(dateRange);
      
      // Analyze commission trends
      const commissionTrends = await this.analyzeCommissions(dateRange);
      
      // Identify top performers
      const topPerformers = await this.identifyTopPerformers(dateRange);
      
      // Generate insights and recommendations
      const insights = this.generateInsights(linkPerformance, commissionTrends, topPerformers);
      
      // Store analysis results (you might want to create a separate collection for this)
      this.logger.log(`Performance analysis completed for ${job.data.period} period`);
      this.logger.log(`Insights generated: ${insights.length} recommendations`);
 
    } catch (error) {
      this.logger.error(`Error in ${job.data.period} performance analysis`, error);
      throw error;
    }
  }
 
  private async calculateFraudScore(commission: CommissionDocument): Promise<number> {
    let score = 0;
 
    try {
      // Check for suspicious patterns
      
      // 1. Multiple commissions from same IP in short time
      const recentCommissions = await this.commissionModel.find({
        'trackingData.ipAddress': commission.trackingData?.ipAddress,
        orderDate: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) },
      });
      
      Iif (recentCommissions.length > 5) {
        score += 0.3;
      }
 
      // 2. Unusually high order value for user
      const userCommissions = await this.commissionModel.find({ userId: commission.userId });
      const averageOrderValue = userCommissions.reduce((sum, c) => sum + c.orderValue, 0) / userCommissions.length;
      
      Iif (commission.orderValue > averageOrderValue * 3) {
        score += 0.2;
      }
 
      // 3. Commission rate higher than expected
      const expectedRate = this.getExpectedCommissionRate(commission.productDetails.category);
      Iif (commission.commissionRate > expectedRate * 1.5) {
        score += 0.2;
      }
 
      // 4. Suspicious user agent or referrer
      Iif (!commission.trackingData?.userAgent || commission.trackingData.userAgent.includes('bot')) {
        score += 0.3;
      }
 
      return Math.min(score, 1.0);
    } catch (error) {
      this.logger.error('Error calculating fraud score', error);
      return 0.5; // Default to medium risk
    }
  }
 
  private getDateRange(period: string): { start: Date; end: Date } {
    const now = new Date();
    const end = new Date(now);
    let start: Date;
 
    switch (period) {
      case 'daily':
        start = new Date(now.getTime() - 24 * 60 * 60 * 1000);
        break;
      case 'weekly':
        start = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
        break;
      case 'monthly':
        start = new Date(now.getFullYear(), now.getMonth(), 1);
        break;
      default:
        start = new Date(now.getTime() - 24 * 60 * 60 * 1000);
    }
 
    return { start, end };
  }
 
  private async analyzeAffiliateLinks(dateRange: { start: Date; end: Date }): Promise<any> {
    const links = await this.affiliateLinkModel.find({
      createdAt: { $gte: dateRange.start, $lte: dateRange.end },
    });
 
    const totalClicks = links.reduce((sum, link) => sum + link.metrics.clicks, 0);
    const totalConversions = links.reduce((sum, link) => sum + link.metrics.conversions, 0);
    const conversionRate = totalClicks > 0 ? (totalConversions / totalClicks) * 100 : 0;
 
    return {
      totalLinks: links.length,
      totalClicks,
      totalConversions,
      conversionRate,
      averageClicksPerLink: links.length > 0 ? totalClicks / links.length : 0,
    };
  }
 
  private async analyzeCommissions(dateRange: { start: Date; end: Date }): Promise<any> {
    const commissions = await this.commissionModel.find({
      orderDate: { $gte: dateRange.start, $lte: dateRange.end },
    });
 
    const totalRevenue = commissions.reduce((sum, c) => sum + c.orderValue, 0);
    const totalCommissions = commissions.reduce((sum, c) => sum + c.commissionAmount, 0);
    const averageOrderValue = commissions.length > 0 ? totalRevenue / commissions.length : 0;
 
    return {
      totalCommissions: commissions.length,
      totalRevenue,
      totalCommissionAmount: totalCommissions,
      averageOrderValue,
      averageCommissionRate: totalRevenue > 0 ? (totalCommissions / totalRevenue) * 100 : 0,
    };
  }
 
  private async identifyTopPerformers(dateRange: { start: Date; end: Date }): Promise<any> {
    // Top performing links
    const topLinks = await this.affiliateLinkModel
      .find({
        createdAt: { $gte: dateRange.start, $lte: dateRange.end },
      })
      .sort({ 'metrics.revenue': -1 })
      .limit(10);
 
    // Top earning users
    const topUsers = await this.commissionModel.aggregate([
      {
        $match: {
          orderDate: { $gte: dateRange.start, $lte: dateRange.end },
        },
      },
      {
        $group: {
          _id: '$userId',
          totalEarnings: { $sum: '$commissionAmount' },
          totalOrders: { $sum: 1 },
        },
      },
      { $sort: { totalEarnings: -1 } },
      { $limit: 10 },
    ]);
 
    return {
      topLinks: topLinks.map(link => ({
        shortCode: link.shortCode,
        clicks: link.metrics.clicks,
        conversions: link.metrics.conversions,
        revenue: link.metrics.revenue,
      })),
      topUsers,
    };
  }
 
  private generateInsights(linkPerformance: any, commissionTrends: any, topPerformers: any): string[] {
    const insights = [];
 
    Iif (linkPerformance.conversionRate < 2) {
      insights.push('Conversion rate is below average. Consider improving link placement and targeting.');
    }
 
    Iif (commissionTrends.averageOrderValue < 50) {
      insights.push('Average order value is low. Focus on promoting higher-value products.');
    }
 
    Iif (topPerformers.topLinks.length > 0) {
      insights.push(`Top performing link has ${topPerformers.topLinks[0].conversions} conversions. Analyze successful patterns.`);
    }
 
    Iif (linkPerformance.averageClicksPerLink < 10) {
      insights.push('Links are not getting enough visibility. Improve marketing and promotion strategies.');
    }
 
    return insights;
  }
 
  private getExpectedCommissionRate(category: string): number {
    const rates = {
      fashion: 5.0,
      beauty: 7.0,
      electronics: 3.0,
      home: 4.0,
      sports: 4.5,
      books: 8.0,
    };
 
    return rates[category.toLowerCase()] || 4.0;
  }
}