All files / src/modules/sustainability/services sustainability-analytics.service.ts

0% Statements 0/86
0% Branches 0/10
0% Functions 0/10
0% Lines 0/83

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User, UserDocument } from '../../../database/schemas/user.schema';
import { UserInteraction, UserInteractionDocument } from '../../../database/schemas/user-interaction.schema';
import { SustainabilityScore, SustainabilityScoreDocument } from '../../../database/schemas/sustainability-score.schema';
 
@Injectable()
export class SustainabilityAnalyticsService {
  private readonly logger = new Logger(SustainabilityAnalyticsService.name);
 
  constructor(
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    @InjectModel(UserInteraction.name) private userInteractionModel: Model<UserInteractionDocument>,
    @InjectModel(SustainabilityScore.name) private sustainabilityScoreModel: Model<SustainabilityScoreDocument>,
  ) {}
 
  async getUserSustainabilityMetrics(userId: string): Promise<{
    totalCO2Saved: number;
    totalWaterSaved: number;
    totalWasteReduced: number;
    sustainabilityScore: number;
    ecoFriendlyPurchases: number;
    circularEconomyParticipation: number;
  }> {
    try {
      // Get user's purchase interactions
      const purchases = await this.userInteractionModel.find({
        userId,
        actionType: 'purchase',
      });
 
      let totalCO2Saved = 0;
      let totalWaterSaved = 0;
      let totalWasteReduced = 0;
      let ecoFriendlyPurchases = 0;
 
      // Calculate metrics based on purchased products
      for (const purchase of purchases) {
        const sustainabilityScore = await this.sustainabilityScoreModel.findOne({
          productId: purchase.targetId,
          isActive: true,
        });
 
        Iif (sustainabilityScore) {
          // Calculate CO2 savings compared to average product
          const avgCO2 = 20; // kg CO2e for average product
          const productCO2 = sustainabilityScore.carbonFootprint.total;
          const co2Saved = Math.max(0, avgCO2 - productCO2);
          totalCO2Saved += co2Saved;
 
          // Estimate water and waste savings
          Iif (sustainabilityScore.scores.environmental > 60) {
            totalWaterSaved += this.estimateWaterSavings(sustainabilityScore);
            totalWasteReduced += this.estimateWasteSavings(sustainabilityScore);
            ecoFriendlyPurchases++;
          }
        }
      }
 
      // Calculate user's overall sustainability score
      const userSustainabilityScore = this.calculateUserSustainabilityScore(
        purchases.length,
        ecoFriendlyPurchases,
        totalCO2Saved,
      );
 
      // Calculate circular economy participation
      const circularEconomyParticipation = await this.calculateCircularEconomyParticipation(userId);
 
      return {
        totalCO2Saved: Math.round(totalCO2Saved * 100) / 100,
        totalWaterSaved: Math.round(totalWaterSaved),
        totalWasteReduced: Math.round(totalWasteReduced * 100) / 100,
        sustainabilityScore: userSustainabilityScore,
        ecoFriendlyPurchases,
        circularEconomyParticipation,
      };
 
    } catch (error) {
      this.logger.error(`Error getting sustainability metrics for user ${userId}`, error);
      throw error;
    }
  }
 
  async getUserSustainabilityInsights(userId: string): Promise<{
    monthlyTrends: Array<{
      month: string;
      co2Saved: number;
      purchases: number;
      sustainabilityScore: number;
    }>;
    categoryBreakdown: Array<{
      category: string;
      sustainabilityScore: number;
      purchases: number;
      improvement: string;
    }>;
    achievements: Array<{
      title: string;
      description: string;
      earnedAt: Date;
      impact: string;
    }>;
  }> {
    try {
      const monthlyTrends = await this.getMonthlyTrends(userId);
      const categoryBreakdown = await this.getCategoryBreakdown(userId);
      const achievements = await this.getSustainabilityAchievements(userId);
 
      return {
        monthlyTrends,
        categoryBreakdown,
        achievements,
      };
 
    } catch (error) {
      this.logger.error(`Error getting sustainability insights for user ${userId}`, error);
      throw error;
    }
  }
 
  private async getMonthlyTrends(userId: string): Promise<Array<{
    month: string;
    co2Saved: number;
    purchases: number;
    sustainabilityScore: number;
  }>> {
    const sixMonthsAgo = new Date();
    sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
 
    const monthlyData = await this.userInteractionModel.aggregate([
      {
        $match: {
          userId,
          actionType: 'purchase',
          timestamp: { $gte: sixMonthsAgo },
        },
      },
      {
        $group: {
          _id: {
            year: { $year: '$timestamp' },
            month: { $month: '$timestamp' },
          },
          purchases: { $sum: 1 },
          products: { $push: '$targetId' },
        },
      },
      { $sort: { '_id.year': 1, '_id.month': 1 } },
    ]);
 
    const trends = [];
    for (const data of monthlyData) {
      const monthName = new Date(data._id.year, data._id.month - 1).toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
      });
 
      // Calculate average sustainability score for the month
      let totalScore = 0;
      let scoredProducts = 0;
      let totalCO2Saved = 0;
 
      for (const productId of data.products) {
        const sustainabilityScore = await this.sustainabilityScoreModel.findOne({
          productId,
          isActive: true,
        });
 
        Iif (sustainabilityScore) {
          totalScore += sustainabilityScore.scores.overall;
          scoredProducts++;
          
          const avgCO2 = 20;
          const co2Saved = Math.max(0, avgCO2 - sustainabilityScore.carbonFootprint.total);
          totalCO2Saved += co2Saved;
        }
      }
 
      trends.push({
        month: monthName,
        co2Saved: Math.round(totalCO2Saved * 100) / 100,
        purchases: data.purchases,
        sustainabilityScore: scoredProducts > 0 ? Math.round(totalScore / scoredProducts) : 0,
      });
    }
 
    return trends;
  }
 
  private async getCategoryBreakdown(userId: string): Promise<Array<{
    category: string;
    sustainabilityScore: number;
    purchases: number;
    improvement: string;
  }>> {
    // This would require joining with products to get categories
    // For now, return sample data
    return [
      {
        category: 'Fashion',
        sustainabilityScore: 65,
        purchases: 8,
        improvement: 'Consider organic cotton and recycled materials',
      },
      {
        category: 'Beauty',
        sustainabilityScore: 72,
        purchases: 5,
        improvement: 'Look for refillable packaging options',
      },
      {
        category: 'Electronics',
        sustainabilityScore: 58,
        purchases: 2,
        improvement: 'Choose energy-efficient and repairable devices',
      },
      {
        category: 'Home',
        sustainabilityScore: 70,
        purchases: 3,
        improvement: 'Great job choosing sustainable home products!',
      },
    ];
  }
 
  private async getSustainabilityAchievements(userId: string): Promise<Array<{
    title: string;
    description: string;
    earnedAt: Date;
    impact: string;
  }>> {
    const metrics = await this.getUserSustainabilityMetrics(userId);
    const achievements = [];
 
    // Generate achievements based on metrics
    Iif (metrics.totalCO2Saved > 10) {
      achievements.push({
        title: 'Carbon Saver',
        description: 'Saved over 10kg of CO2 through sustainable choices',
        earnedAt: new Date(),
        impact: `${metrics.totalCO2Saved}kg CO2 saved`,
      });
    }
 
    Iif (metrics.ecoFriendlyPurchases > 5) {
      achievements.push({
        title: 'Eco Warrior',
        description: 'Made 5+ eco-friendly purchases',
        earnedAt: new Date(),
        impact: `${metrics.ecoFriendlyPurchases} sustainable products chosen`,
      });
    }
 
    Iif (metrics.sustainabilityScore > 70) {
      achievements.push({
        title: 'Sustainability Champion',
        description: 'Achieved high sustainability score',
        earnedAt: new Date(),
        impact: `${metrics.sustainabilityScore}/100 sustainability score`,
      });
    }
 
    Iif (metrics.totalWaterSaved > 100) {
      achievements.push({
        title: 'Water Guardian',
        description: 'Saved over 100 liters of water',
        earnedAt: new Date(),
        impact: `${metrics.totalWaterSaved}L water saved`,
      });
    }
 
    return achievements;
  }
 
  private estimateWaterSavings(sustainabilityScore: SustainabilityScoreDocument): number {
    // Estimate water savings based on sustainability score
    const baseWaterUsage = 1000; // liters for average product
    const savingsRate = (sustainabilityScore.scores.environmental - 50) / 100;
    return Math.max(0, baseWaterUsage * savingsRate);
  }
 
  private estimateWasteSavings(sustainabilityScore: SustainabilityScoreDocument): number {
    // Estimate waste reduction based on recyclability and materials
    const baseWaste = 2; // kg for average product
    const recyclabilityRate = sustainabilityScore.recyclability.percentage / 100;
    const materialsScore = sustainabilityScore.scores.materials / 100;
    return baseWaste * (recyclabilityRate + materialsScore) / 2;
  }
 
  private calculateUserSustainabilityScore(
    totalPurchases: number,
    ecoFriendlyPurchases: number,
    totalCO2Saved: number,
  ): number {
    Iif (totalPurchases === 0) return 0;
 
    const ecoFriendlyRate = (ecoFriendlyPurchases / totalPurchases) * 100;
    const co2Impact = Math.min(totalCO2Saved * 2, 30); // Cap at 30 points
    
    return Math.round(ecoFriendlyRate * 0.7 + co2Impact * 0.3);
  }
 
  private async calculateCircularEconomyParticipation(userId: string): Promise<number> {
    // This would check for resale listings, donations, etc.
    // For now, return a sample value
    return Math.floor(Math.random() * 100);
  }
}