All files / src/modules/sustainability/services circular-economy.service.ts

0% Statements 0/44
0% Branches 0/7
0% Functions 0/8
0% Lines 0/42

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User, UserDocument } from '../../../database/schemas/user.schema';
import { Product, ProductDocument } from '../../../database/schemas/product.schema';
import { ResaleListing, ResaleListingDocument } from '../../../database/schemas/resale-listing.schema';
 
@Injectable()
export class CircularEconomyService {
  private readonly logger = new Logger(CircularEconomyService.name);
 
  constructor(
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    @InjectModel(Product.name) private productModel: Model<ProductDocument>,
    @InjectModel(ResaleListing.name) private resaleListingModel: Model<ResaleListingDocument>,
  ) {}
 
  async getCircularEconomyOpportunities(userId: string): Promise<{
    resaleValue: Array<{
      productId: string;
      title: string;
      estimatedValue: number;
      condition: string;
      co2SavedByReselling: number;
    }>;
    upcyclingIdeas: Array<{
      productId: string;
      title: string;
      ideas: string[];
      difficulty: string;
      materials: string[];
    }>;
    donationOptions: Array<{
      organization: string;
      acceptedItems: string[];
      impact: string;
      location: string;
    }>;
  }> {
    try {
      // Get user's purchase history to suggest resale opportunities
      const resaleOpportunities = await this.getResaleOpportunities(userId);
      
      // Generate upcycling ideas based on common items
      const upcyclingIdeas = this.generateUpcyclingIdeas();
      
      // Get local donation options
      const donationOptions = this.getDonationOptions();
 
      return {
        resaleValue: resaleOpportunities,
        upcyclingIdeas,
        donationOptions,
      };
 
    } catch (error) {
      this.logger.error(`Error getting circular economy opportunities for user ${userId}`, error);
      throw error;
    }
  }
 
  private async getResaleOpportunities(userId: string): Promise<Array<{
    productId: string;
    title: string;
    estimatedValue: number;
    condition: string;
    co2SavedByReselling: number;
  }>> {
    // This would typically come from user's purchase history
    // For now, we'll return sample data based on popular resale categories
    
    const resaleCategories = ['fashion', 'electronics', 'beauty', 'accessories'];
    const opportunities = [];
 
    for (const category of resaleCategories) {
      const products = await this.productModel
        .find({
          'category.main': category,
          isActive: true,
        })
        .limit(2);
 
      for (const product of products) {
        const originalPrice = product.variants[0]?.price?.current || 0;
        const estimatedResaleValue = this.calculateResaleValue(product, originalPrice);
        
        opportunities.push({
          productId: product._id.toString(),
          title: product.title,
          estimatedValue: estimatedResaleValue,
          condition: this.estimateCondition(product),
          co2SavedByReselling: this.calculateCO2Savings(product),
        });
      }
    }
 
    return opportunities.slice(0, 5);
  }
 
  private generateUpcyclingIdeas(): Array<{
    productId: string;
    title: string;
    ideas: string[];
    difficulty: string;
    materials: string[];
  }> {
    return [
      {
        productId: 'sample-1',
        title: 'Old T-Shirts',
        ideas: [
          'Transform into reusable shopping bags',
          'Create cleaning rags and dusters',
          'Make plant pot holders',
          'Design custom tote bags',
        ],
        difficulty: 'Easy',
        materials: ['scissors', 'needle', 'thread'],
      },
      {
        productId: 'sample-2',
        title: 'Denim Jeans',
        ideas: [
          'Convert to stylish shorts',
          'Create a denim apron',
          'Make storage pockets for organization',
          'Design a unique denim bag',
        ],
        difficulty: 'Medium',
        materials: ['sewing machine', 'scissors', 'measuring tape'],
      },
      {
        productId: 'sample-3',
        title: 'Glass Containers',
        ideas: [
          'Transform into plant terrariums',
          'Create storage jars for kitchen',
          'Make decorative candle holders',
          'Design desk organizers',
        ],
        difficulty: 'Easy',
        materials: ['paint', 'brushes', 'decorative elements'],
      },
      {
        productId: 'sample-4',
        title: 'Old Books',
        ideas: [
          'Create unique wall art displays',
          'Make secret storage boxes',
          'Design bookshelf decorations',
          'Transform into planters for succulents',
        ],
        difficulty: 'Medium',
        materials: ['craft knife', 'glue', 'paint'],
      },
    ];
  }
 
  private getDonationOptions(): Array<{
    organization: string;
    acceptedItems: string[];
    impact: string;
    location: string;
  }> {
    return [
      {
        organization: 'Emirates Red Crescent',
        acceptedItems: ['clothing', 'shoes', 'accessories', 'household items'],
        impact: 'Supports families in need across the UAE',
        location: 'Multiple locations in Dubai and Abu Dhabi',
      },
      {
        organization: 'Crossroads Foundation',
        acceptedItems: ['clothing', 'books', 'toys', 'electronics'],
        impact: 'Provides job training and supports refugees',
        location: 'Dubai and Sharjah centers',
      },
      {
        organization: 'The Salvation Army',
        acceptedItems: ['clothing', 'furniture', 'books', 'household goods'],
        impact: 'Supports homeless and disadvantaged communities',
        location: 'Dubai, Abu Dhabi, and Sharjah',
      },
      {
        organization: 'Local Mosques and Community Centers',
        acceptedItems: ['clothing', 'food items', 'books', 'toys'],
        impact: 'Direct community support and assistance',
        location: 'Neighborhood locations throughout GCC',
      },
      {
        organization: 'Animal Shelters',
        acceptedItems: ['old towels', 'blankets', 'newspapers'],
        impact: 'Provides comfort for rescued animals',
        location: 'Dubai Municipality Animal Shelter and others',
      },
    ];
  }
 
  private calculateResaleValue(product: ProductDocument, originalPrice: number): number {
    const category = product.category.main.toLowerCase();
    
    // Resale value percentages by category
    const resaleRates = {
      fashion: 0.3, // 30% of original price
      electronics: 0.4, // 40% of original price
      beauty: 0.2, // 20% of original price (if unopened)
      accessories: 0.35, // 35% of original price
      home: 0.25, // 25% of original price
    };
 
    const baseRate = resaleRates[category] || 0.25;
    
    // Adjust based on brand popularity (simplified)
    let brandMultiplier = 1.0;
    const popularBrands = ['nike', 'adidas', 'zara', 'h&m', 'apple', 'samsung'];
    Iif (popularBrands.includes(product.brand.toLowerCase())) {
      brandMultiplier = 1.2;
    }
 
    return Math.round(originalPrice * baseRate * brandMultiplier);
  }
 
  private estimateCondition(product: ProductDocument): string {
    // This would typically be based on purchase date and usage data
    // For now, we'll return a reasonable estimate
    const conditions = ['excellent', 'good', 'fair'];
    return conditions[Math.floor(Math.random() * conditions.length)];
  }
 
  private calculateCO2Savings(product: ProductDocument): number {
    const category = product.category.main.toLowerCase();
    
    // Estimated CO2 savings by extending product lifecycle through resale
    const co2Savings = {
      fashion: 8.5, // kg CO2e saved
      electronics: 25.0, // kg CO2e saved
      beauty: 2.0, // kg CO2e saved
      accessories: 3.5, // kg CO2e saved
      home: 15.0, // kg CO2e saved
    };
 
    return co2Savings[category] || 5.0;
  }
}