All files / src/modules/sustainability/services eco-recommendation.service.ts

0% Statements 0/77
0% Branches 0/21
0% Functions 0/16
0% Lines 0/73

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Product, ProductDocument } from '../../../database/schemas/product.schema';
import { SustainabilityScore, SustainabilityScoreDocument } from '../../../database/schemas/sustainability-score.schema';
 
@Injectable()
export class EcoRecommendationService {
  private readonly logger = new Logger(EcoRecommendationService.name);
 
  constructor(
    @InjectModel(Product.name) private productModel: Model<ProductDocument>,
    @InjectModel(SustainabilityScore.name) private sustainabilityScoreModel: Model<SustainabilityScoreDocument>,
  ) {}
 
  async getEcoFriendlyAlternatives(productId: string, limit: number = 5): Promise<Array<{
    productId: string;
    title: string;
    sustainabilityScore: number;
    co2Reduction: number;
    reasoning: string;
    priceComparison: {
      original: number;
      alternative: number;
      savings: number;
    };
  }>> {
    try {
      const originalProduct = await this.productModel.findById(productId);
      Iif (!originalProduct) {
        throw new Error('Product not found');
      }
 
      // Find similar products in the same category with better sustainability scores
      const alternatives = await this.productModel.find({
        _id: { $ne: productId },
        'category.main': originalProduct.category.main,
        isActive: true,
      }).limit(limit * 3); // Get more candidates for filtering
 
      const ecoAlternatives = [];
 
      for (const alternative of alternatives) {
        const sustainabilityScore = await this.sustainabilityScoreModel.findOne({
          productId: alternative._id,
          isActive: true,
        });
 
        Iif (sustainabilityScore && sustainabilityScore.scores.overall > 60) {
          const originalPrice = originalProduct.variants[0]?.price?.current || 0;
          const alternativePrice = alternative.variants[0]?.price?.current || 0;
 
          ecoAlternatives.push({
            productId: alternative._id.toString(),
            title: alternative.title,
            sustainabilityScore: sustainabilityScore.scores.overall,
            co2Reduction: this.calculateCO2Reduction(sustainabilityScore),
            reasoning: this.generateRecommendationReasoning(sustainabilityScore),
            priceComparison: {
              original: originalPrice,
              alternative: alternativePrice,
              savings: originalPrice - alternativePrice,
            },
          });
        }
      }
 
      return ecoAlternatives
        .sort((a, b) => b.sustainabilityScore - a.sustainabilityScore)
        .slice(0, limit);
 
    } catch (error) {
      this.logger.error(`Error getting eco-friendly alternatives for product ${productId}`, error);
      throw error;
    }
  }
 
  async getUserSustainabilityRecommendations(userId: string): Promise<{
    ecoFriendlyAlternatives: Array<{
      productId: string;
      title: string;
      sustainabilityScore: number;
      co2Reduction: number;
      reasoning: string;
    }>;
    sustainableBrands: Array<{
      brand: string;
      score: number;
      certifications: string[];
      highlights: string[];
    }>;
    actionItems: Array<{
      action: string;
      impact: string;
      difficulty: 'easy' | 'medium' | 'hard';
      co2Savings: number;
    }>;
  }> {
    try {
      // Get top sustainable products
      const sustainableProducts = await this.getTopSustainableProducts(10);
      
      // Get sustainable brands
      const sustainableBrands = await this.getTopSustainableBrands(5);
      
      // Generate action items
      const actionItems = this.generateSustainabilityActionItems();
 
      return {
        ecoFriendlyAlternatives: sustainableProducts.map(product => ({
          productId: product.productId,
          title: product.title,
          sustainabilityScore: product.sustainabilityScore,
          co2Reduction: product.co2Reduction,
          reasoning: product.reasoning,
        })),
        sustainableBrands,
        actionItems,
      };
 
    } catch (error) {
      this.logger.error(`Error getting sustainability recommendations for user ${userId}`, error);
      throw error;
    }
  }
 
  private async getTopSustainableProducts(limit: number): Promise<Array<{
    productId: string;
    title: string;
    sustainabilityScore: number;
    co2Reduction: number;
    reasoning: string;
  }>> {
    const sustainableScores = await this.sustainabilityScoreModel
      .find({
        isActive: true,
        'scores.overall': { $gte: 70 },
      })
      .populate('productId')
      .sort({ 'scores.overall': -1 })
      .limit(limit);
 
    return sustainableScores.map(score => {
      const product = score.productId as any;
      return {
        productId: product._id.toString(),
        title: product.title,
        sustainabilityScore: score.scores.overall,
        co2Reduction: this.calculateCO2Reduction(score),
        reasoning: this.generateRecommendationReasoning(score),
      };
    });
  }
 
  private async getTopSustainableBrands(limit: number): Promise<Array<{
    brand: string;
    score: number;
    certifications: string[];
    highlights: string[];
  }>> {
    const brandScores = await this.sustainabilityScoreModel.aggregate([
      {
        $match: {
          isActive: true,
          'scores.overall': { $gte: 60 },
        },
      },
      {
        $group: {
          _id: '$brand',
          averageScore: { $avg: '$scores.overall' },
          certifications: { $push: '$certifications' },
          count: { $sum: 1 },
        },
      },
      {
        $match: {
          count: { $gte: 3 }, // At least 3 products
        },
      },
      { $sort: { averageScore: -1 as any } },
      { $limit: limit },
    ]);
 
    return brandScores.map(brand => ({
      brand: brand._id,
      score: Math.round(brand.averageScore),
      certifications: this.extractUniqueCertifications(brand.certifications),
      highlights: this.generateBrandHighlights(brand),
    }));
  }
 
  private generateSustainabilityActionItems(): Array<{
    action: string;
    impact: string;
    difficulty: 'easy' | 'medium' | 'hard';
    co2Savings: number;
  }> {
    return [
      {
        action: 'Choose products with organic or recycled materials',
        impact: 'Reduces manufacturing emissions and waste',
        difficulty: 'easy',
        co2Savings: 2.5,
      },
      {
        action: 'Buy from local or regional brands',
        impact: 'Reduces shipping emissions significantly',
        difficulty: 'easy',
        co2Savings: 5.0,
      },
      {
        action: 'Participate in clothing swaps or resale',
        impact: 'Extends product lifecycle and reduces waste',
        difficulty: 'medium',
        co2Savings: 8.0,
      },
      {
        action: 'Choose quality items that last longer',
        impact: 'Reduces replacement frequency and total consumption',
        difficulty: 'medium',
        co2Savings: 12.0,
      },
      {
        action: 'Support brands with verified sustainability certifications',
        impact: 'Encourages industry-wide sustainable practices',
        difficulty: 'easy',
        co2Savings: 3.0,
      },
    ];
  }
 
  private calculateCO2Reduction(sustainabilityScore: SustainabilityScoreDocument): number {
    // Estimate CO2 reduction based on sustainability score
    const baselineEmissions = 20; // kg CO2e for average product
    const reductionFactor = (sustainabilityScore.scores.overall - 50) / 100;
    return Math.max(0, baselineEmissions * reductionFactor);
  }
 
  private generateRecommendationReasoning(sustainabilityScore: SustainabilityScoreDocument): string {
    const reasons = [];
 
    Iif (sustainabilityScore.scores.materials > 70) {
      reasons.push('sustainable materials');
    }
    Iif (sustainabilityScore.scores.manufacturing > 70) {
      reasons.push('eco-friendly manufacturing');
    }
    Iif (sustainabilityScore.scores.social > 70) {
      reasons.push('ethical labor practices');
    }
    Iif (sustainabilityScore.carbonFootprint.total < 10) {
      reasons.push('low carbon footprint');
    }
    Iif (sustainabilityScore.certifications.length > 0) {
      reasons.push('verified certifications');
    }
 
    Iif (reasons.length === 0) {
      return 'Better overall sustainability score';
    }
 
    return `Recommended for: ${reasons.join(', ')}`;
  }
 
  private extractUniqueCertifications(certificationArrays: any[]): string[] {
    const allCertifications = certificationArrays.flat();
    const uniqueCertifications = new Set();
    
    allCertifications.forEach(certArray => {
      Iif (Array.isArray(certArray)) {
        certArray.forEach(cert => {
          Iif (cert.name) uniqueCertifications.add(cert.name);
        });
      }
    });
 
    return Array.from(uniqueCertifications) as string[];
  }
 
  private generateBrandHighlights(brand: any): string[] {
    const highlights = [];
    
    if (brand.averageScore > 80) {
      highlights.push('Exceptional sustainability leader');
    } else Iif (brand.averageScore > 70) {
      highlights.push('Strong sustainability commitment');
    }
    
    Iif (brand.count > 10) {
      highlights.push('Wide range of sustainable products');
    }
    
    highlights.push(`${brand.count} sustainable products available`);
    
    return highlights;
  }
}