All files / src/modules/savings/services sustainability.service.ts

0% Statements 0/123
0% Branches 0/34
0% Functions 0/27
0% Lines 0/115

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 512 513 514                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { UserInteraction, UserInteractionDocument } from '../../../database/schemas/user-interaction.schema';
import { Product, ProductDocument } from '../../../database/schemas/product.schema';
 
export interface SustainabilityMetrics {
  userId: string;
  carbonFootprintSaved: number; // kg CO2
  sustainablePurchases: number;
  ecoFriendlyDeals: number;
  sustainabilityScore: number; // 0-100
  monthlyTrend: Array<{
    month: string;
    carbonSaved: number;
    sustainablePurchases: number;
  }>;
  recommendations: string[];
  achievements: Array<{
    type: string;
    title: string;
    description: string;
    earnedAt: Date;
  }>;
}
 
export interface GlobalSustainabilityImpact {
  totalCarbonSaved: number;
  totalSustainablePurchases: number;
  totalUsers: number;
  topEcoFriendlyCategories: Array<{
    category: string;
    impact: number;
    purchases: number;
  }>;
  monthlyTrend: Array<{
    month: string;
    carbonSaved: number;
    users: number;
  }>;
  topSustainableBrands: Array<{
    brand: string;
    sustainabilityScore: number;
    purchases: number;
  }>;
}
 
@Injectable()
export class SustainabilityService {
  private readonly logger = new Logger(SustainabilityService.name);
 
  // Carbon footprint estimates per category (kg CO2 per AED saved)
  private readonly CARBON_IMPACT_FACTORS = {
    fashion: 0.15, // Fashion has high carbon impact
    electronics: 0.25, // Electronics have very high impact
    beauty: 0.08,
    home: 0.12,
    sports: 0.10,
    books: 0.05,
    default: 0.10,
  };
 
  constructor(
    @InjectModel(UserInteraction.name) private userInteractionModel: Model<UserInteractionDocument>,
    @InjectModel(Product.name) private productModel: Model<ProductDocument>,
  ) {}
 
  async getUserSustainabilityMetrics(userId: string): Promise<SustainabilityMetrics> {
    try {
      const [purchases, sustainabilityData] = await Promise.all([
        this.getUserPurchases(userId),
        this.calculateUserSustainabilityData(userId),
      ]);
 
      const carbonFootprintSaved = this.calculateCarbonFootprintSaved(purchases);
      const sustainablePurchases = this.countSustainablePurchases(purchases);
      const ecoFriendlyDeals = this.countEcoFriendlyDeals(purchases);
      const sustainabilityScore = this.calculateSustainabilityScore(purchases);
      const monthlyTrend = await this.getMonthlyTrend(userId);
      const recommendations = this.generateRecommendations(purchases, sustainabilityScore);
      const achievements = this.getSustainabilityAchievements(sustainablePurchases, carbonFootprintSaved);
 
      return {
        userId,
        carbonFootprintSaved,
        sustainablePurchases,
        ecoFriendlyDeals,
        sustainabilityScore,
        monthlyTrend,
        recommendations,
        achievements,
      };
    } catch (error) {
      this.logger.error(`Error getting sustainability metrics for user ${userId}`, error);
      throw error;
    }
  }
 
  async getGlobalSustainabilityImpact(): Promise<GlobalSustainabilityImpact> {
    try {
      const [
        totalImpact,
        categoryImpact,
        monthlyTrend,
        brandImpact,
      ] = await Promise.all([
        this.calculateGlobalImpact(),
        this.getCategoryImpact(),
        this.getGlobalMonthlyTrend(),
        this.getBrandSustainabilityImpact(),
      ]);
 
      return {
        totalCarbonSaved: totalImpact.carbonSaved,
        totalSustainablePurchases: totalImpact.sustainablePurchases,
        totalUsers: totalImpact.users,
        topEcoFriendlyCategories: categoryImpact,
        monthlyTrend,
        topSustainableBrands: brandImpact,
      };
    } catch (error) {
      this.logger.error('Error getting global sustainability impact', error);
      throw error;
    }
  }
 
  private async getUserPurchases(userId: string): Promise<UserInteractionDocument[]> {
    return this.userInteractionModel
      .find({
        userId,
        actionType: 'purchase',
        'metadata.savingsAmount': { $exists: true, $gt: 0 },
      })
      .populate('targetId')
      .sort({ timestamp: -1 });
  }
 
  private async calculateUserSustainabilityData(userId: string): Promise<any> {
    // This would fetch additional sustainability data from a dedicated collection
    return {};
  }
 
  private calculateCarbonFootprintSaved(purchases: UserInteractionDocument[]): number {
    let totalCarbonSaved = 0;
 
    for (const purchase of purchases) {
      const savingsAmount = (purchase.metadata as any)?.savingsAmount || 0;
      const product = purchase.targetId as any; // Would be populated Product
      const category = product?.category?.main?.toLowerCase() || 'default';
      
      const carbonFactor = this.CARBON_IMPACT_FACTORS[category] || this.CARBON_IMPACT_FACTORS.default;
      totalCarbonSaved += savingsAmount * carbonFactor;
    }
 
    return Math.round(totalCarbonSaved * 100) / 100; // Round to 2 decimal places
  }
 
  private countSustainablePurchases(purchases: UserInteractionDocument[]): number {
    return purchases.filter(purchase => {
      const product = purchase.targetId as any;
      return product?.specifications?.sustainability?.rating >= 70; // 70+ sustainability rating
    }).length;
  }
 
  private countEcoFriendlyDeals(purchases: UserInteractionDocument[]): number {
    return purchases.filter(purchase => {
      const product = purchase.targetId as any;
      return product?.specifications?.sustainability?.certifications?.length > 0;
    }).length;
  }
 
  private calculateSustainabilityScore(purchases: UserInteractionDocument[]): number {
    Iif (purchases.length === 0) return 0;
 
    let totalScore = 0;
    let scoredPurchases = 0;
 
    for (const purchase of purchases) {
      const product = purchase.targetId as any;
      const sustainabilityRating = product?.specifications?.sustainability?.rating;
      
      Iif (sustainabilityRating) {
        totalScore += sustainabilityRating;
        scoredPurchases++;
      }
    }
 
    Iif (scoredPurchases === 0) return 50; // Default score
 
    const avgScore = totalScore / scoredPurchases;
    
    // Bonus points for consistent sustainable shopping
    const sustainablePercentage = this.countSustainablePurchases(purchases) / purchases.length;
    const bonusPoints = sustainablePercentage * 20; // Up to 20 bonus points
 
    return Math.min(Math.round(avgScore + bonusPoints), 100);
  }
 
  private async getMonthlyTrend(userId: string): Promise<Array<{
    month: string;
    carbonSaved: number;
    sustainablePurchases: number;
  }>> {
    const pipeline = [
      {
        $match: {
          userId,
          actionType: 'purchase',
          'metadata.savingsAmount': { $exists: true, $gt: 0 },
          timestamp: { $gte: new Date(Date.now() - 12 * 30 * 24 * 60 * 60 * 1000) }, // Last 12 months
        },
      },
      {
        $lookup: {
          from: 'products',
          localField: 'targetId',
          foreignField: '_id',
          as: 'product',
        },
      },
      { $unwind: '$product' },
      {
        $group: {
          _id: {
            $dateToString: { format: '%Y-%m', date: '$timestamp' },
          },
          totalSavings: { $sum: '$metadata.savingsAmount' },
          sustainablePurchases: {
            $sum: {
              $cond: [
                { $gte: ['$product.specifications.sustainability.rating', 70] },
                1,
                0,
              ],
            },
          },
        },
      },
      { $sort: { '_id': 1 as any } },
    ];
 
    const results = await this.userInteractionModel.aggregate(pipeline);
    
    return results.map(r => ({
      month: r._id,
      carbonSaved: this.calculateCarbonFromSavings(r.totalSavings),
      sustainablePurchases: r.sustainablePurchases,
    }));
  }
 
  private generateRecommendations(
    purchases: UserInteractionDocument[],
    sustainabilityScore: number,
  ): string[] {
    const recommendations = [];
 
    if (sustainabilityScore < 30) {
      recommendations.push('Start choosing products with eco-friendly certifications');
      recommendations.push('Look for items with minimal packaging');
      recommendations.push('Consider buying from sustainable brands');
    } else if (sustainabilityScore < 60) {
      recommendations.push('Try to increase your sustainable purchase ratio');
      recommendations.push('Look for locally made products to reduce shipping emissions');
      recommendations.push('Consider second-hand or refurbished items');
    } else if (sustainabilityScore < 80) {
      recommendations.push('You\'re doing great! Consider sharing sustainable deals with friends');
      recommendations.push('Look for products with carbon-neutral shipping');
      recommendations.push('Try to buy in bulk to reduce packaging waste');
    } else {
      recommendations.push('Excellent sustainability practices! You\'re a green shopping champion');
      recommendations.push('Consider becoming a sustainability ambassador');
      recommendations.push('Help others by reviewing eco-friendly products');
    }
 
    // Category-specific recommendations
    const categories = this.getTopCategories(purchases);
    Iif (categories.includes('fashion')) {
      recommendations.push('Look for clothing made from organic or recycled materials');
    }
    Iif (categories.includes('electronics')) {
      recommendations.push('Choose energy-efficient electronics with good longevity');
    }
 
    return recommendations.slice(0, 5); // Return top 5 recommendations
  }
 
  private getSustainabilityAchievements(
    sustainablePurchases: number,
    carbonSaved: number,
  ): Array<{
    type: string;
    title: string;
    description: string;
    earnedAt: Date;
  }> {
    const achievements = [];
 
    Iif (sustainablePurchases >= 1) {
      achievements.push({
        type: 'eco_starter',
        title: 'Eco Starter',
        description: 'Made your first sustainable purchase',
        earnedAt: new Date(),
      });
    }
 
    Iif (sustainablePurchases >= 10) {
      achievements.push({
        type: 'green_shopper',
        title: 'Green Shopper',
        description: 'Made 10 sustainable purchases',
        earnedAt: new Date(),
      });
    }
 
    Iif (carbonSaved >= 10) {
      achievements.push({
        type: 'carbon_saver',
        title: 'Carbon Saver',
        description: 'Saved 10kg of CO2 through smart shopping',
        earnedAt: new Date(),
      });
    }
 
    Iif (sustainablePurchases >= 50) {
      achievements.push({
        type: 'eco_champion',
        title: 'Eco Champion',
        description: 'Made 50 sustainable purchases - you\'re making a real difference!',
        earnedAt: new Date(),
      });
    }
 
    return achievements;
  }
 
  private async calculateGlobalImpact(): Promise<{
    carbonSaved: number;
    sustainablePurchases: number;
    users: number;
  }> {
    const pipeline = [
      {
        $match: {
          actionType: 'purchase',
          'metadata.savingsAmount': { $exists: true, $gt: 0 },
        },
      },
      {
        $lookup: {
          from: 'products',
          localField: 'targetId',
          foreignField: '_id',
          as: 'product',
        },
      },
      { $unwind: '$product' },
      {
        $group: {
          _id: null,
          totalSavings: { $sum: '$metadata.savingsAmount' },
          sustainablePurchases: {
            $sum: {
              $cond: [
                { $gte: ['$product.specifications.sustainability.rating', 70] },
                1,
                0,
              ],
            },
          },
          uniqueUsers: { $addToSet: '$userId' },
        },
      },
    ];
 
    const result = await this.userInteractionModel.aggregate(pipeline);
    const data = result[0] || {};
 
    return {
      carbonSaved: this.calculateCarbonFromSavings(data.totalSavings || 0),
      sustainablePurchases: data.sustainablePurchases || 0,
      users: data.uniqueUsers?.length || 0,
    };
  }
 
  private async getCategoryImpact(): Promise<Array<{
    category: string;
    impact: number;
    purchases: number;
  }>> {
    const pipeline = [
      {
        $match: {
          actionType: 'purchase',
          'metadata.savingsAmount': { $exists: true, $gt: 0 },
        },
      },
      {
        $lookup: {
          from: 'products',
          localField: 'targetId',
          foreignField: '_id',
          as: 'product',
        },
      },
      { $unwind: '$product' },
      {
        $group: {
          _id: '$product.category.main',
          totalSavings: { $sum: '$metadata.savingsAmount' },
          purchases: { $sum: 1 },
        },
      },
      { $sort: { totalSavings: -1 as any } },
      { $limit: 10 },
    ];
 
    const results = await this.userInteractionModel.aggregate(pipeline);
    
    return results.map(r => ({
      category: r._id,
      impact: this.calculateCarbonFromSavings(r.totalSavings),
      purchases: r.purchases,
    }));
  }
 
  private async getGlobalMonthlyTrend(): Promise<Array<{
    month: string;
    carbonSaved: number;
    users: number;
  }>> {
    const pipeline = [
      {
        $match: {
          actionType: 'purchase',
          'metadata.savingsAmount': { $exists: true, $gt: 0 },
          timestamp: { $gte: new Date(Date.now() - 12 * 30 * 24 * 60 * 60 * 1000) },
        },
      },
      {
        $group: {
          _id: {
            $dateToString: { format: '%Y-%m', date: '$timestamp' },
          },
          totalSavings: { $sum: '$metadata.savingsAmount' },
          uniqueUsers: { $addToSet: '$userId' },
        },
      },
      { $sort: { '_id': 1 as any } },
    ];
 
    const results = await this.userInteractionModel.aggregate(pipeline);
    
    return results.map(r => ({
      month: r._id,
      carbonSaved: this.calculateCarbonFromSavings(r.totalSavings),
      users: r.uniqueUsers.length,
    }));
  }
 
  private async getBrandSustainabilityImpact(): Promise<Array<{
    brand: string;
    sustainabilityScore: number;
    purchases: number;
  }>> {
    const pipeline = [
      {
        $match: {
          'specifications.sustainability.rating': { $exists: true, $gte: 50 },
        },
      },
      {
        $group: {
          _id: '$brand',
          avgSustainabilityScore: { $avg: '$specifications.sustainability.rating' },
          purchases: { $sum: '$metrics.conversions' },
        },
      },
      { $sort: { avgSustainabilityScore: -1 as any } },
      { $limit: 10 },
    ];
 
    const results = await this.productModel.aggregate(pipeline);
    
    return results.map(r => ({
      brand: r._id,
      sustainabilityScore: Math.round(r.avgSustainabilityScore),
      purchases: r.purchases || 0,
    }));
  }
 
  private calculateCarbonFromSavings(savingsAmount: number): number {
    // Use average carbon factor for mixed purchases
    return Math.round(savingsAmount * this.CARBON_IMPACT_FACTORS.default * 100) / 100;
  }
 
  private getTopCategories(purchases: UserInteractionDocument[]): string[] {
    const categoryCount = new Map<string, number>();
    
    purchases.forEach(purchase => {
      const product = purchase.targetId as any;
      const category = product?.category?.main?.toLowerCase();
      Iif (category) {
        categoryCount.set(category, (categoryCount.get(category) || 0) + 1);
      }
    });
 
    return Array.from(categoryCount.entries())
      .sort(([, a], [, b]) => b - a)
      .slice(0, 3)
      .map(([category]) => category);
  }
}