All files / src/modules/recommendations/services size-prediction.service.ts

0% Statements 0/160
0% Branches 0/69
0% Functions 0/37
0% Lines 0/154

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 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
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 { UserInteraction, UserInteractionDocument } from '../../../database/schemas/user-interaction.schema';
 
export interface SizePredictionRequest {
  userId: string;
  productId: string;
  brand: string;
  category: string;
}
 
export interface SizePredictionResult {
  recommendedSize: string;
  confidence: number;
  fitType: 'tight' | 'perfect' | 'loose';
  alternatives: Array<{
    size: string;
    fitType: string;
    confidence: number;
  }>;
  reasoning: string;
  factors: Array<{
    factor: string;
    weight: number;
    contribution: string;
  }>;
}
 
export interface BrandSizeMapping {
  brand: string;
  category: string;
  sizeChart: Record<string, {
    measurements: {
      chest?: number;
      waist?: number;
      hips?: number;
      inseam?: number;
      length?: number;
      width?: number;
    };
    fit: 'tight' | 'regular' | 'loose';
  }>;
}
 
@Injectable()
export class SizePredictionService {
  private readonly logger = new Logger(SizePredictionService.name);
 
  // Brand-specific size mappings (in a real system, this would be in the database)
  private readonly brandSizeMappings: Map<string, BrandSizeMapping> = new Map();
 
  constructor(
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    @InjectModel(Product.name) private productModel: Model<ProductDocument>,
    @InjectModel(UserInteraction.name) private interactionModel: Model<UserInteractionDocument>,
  ) {
    this.initializeBrandMappings();
  }
 
  async predictSize(request: SizePredictionRequest): Promise<SizePredictionResult> {
    try {
      this.logger.log(`Predicting size for user ${request.userId}, product ${request.productId}`);
 
      const [user, product] = await Promise.all([
        this.userModel.findById(request.userId),
        this.productModel.findById(request.productId),
      ]);
 
      Iif (!user) {
        throw new Error('User not found');
      }
 
      Iif (!product) {
        throw new Error('Product not found');
      }
 
      // Get user's measurement profile
      const userMeasurements = this.getUserMeasurements(user);
      
      // Get brand-specific sizing information
      const brandMapping = this.getBrandMapping(request.brand, request.category);
      
      // Get user's size history with this brand
      const sizeHistory = await this.getUserSizeHistory(request.userId, request.brand, request.category);
      
      // Predict size using multiple methods
      const predictions = await this.generateSizePredictions({
        userMeasurements,
        brandMapping,
        sizeHistory,
        product,
        category: request.category,
      });
 
      // Combine predictions and calculate confidence
      const finalPrediction = this.combinePredictions(predictions);
 
      return {
        ...finalPrediction,
        reasoning: this.generateSizeReasoning(finalPrediction, predictions),
      };
 
    } catch (error) {
      this.logger.error(`Error predicting size for user ${request.userId}`, error);
      throw error;
    }
  }
 
  async updateSizeFeedback(
    userId: string,
    productId: string,
    actualSize: string,
    fitFeedback: 'too_small' | 'perfect' | 'too_large',
    measurements?: {
      chest?: number;
      waist?: number;
      hips?: number;
    },
  ): Promise<void> {
    try {
      // Store size feedback for future predictions
      const interaction = new this.interactionModel({
        userId,
        sessionId: `size_feedback_${Date.now()}`,
        actionType: 'size_feedback',
        targetType: 'product',
        targetId: productId,
        context: {
          source: 'size_prediction',
          actualSize,
          fitFeedback,
          measurements,
        },
        metadata: {
          feedbackType: 'size_fit',
          accuracy: fitFeedback === 'perfect' ? 1 : 0,
        },
        timestamp: new Date(),
        createdAt: new Date(),
      });
 
      await interaction.save();
 
      // Update user's size profile if measurements provided
      Iif (measurements) {
        await this.updateUserMeasurements(userId, measurements);
      }
 
      this.logger.log(`Updated size feedback for user ${userId}, product ${productId}`);
    } catch (error) {
      this.logger.error(`Error updating size feedback for user ${userId}`, error);
      throw error;
    }
  }
 
  async getBrandSizeGuide(brand: string, category: string): Promise<{
    sizeChart: Record<string, any>;
    fitGuide: string[];
    measurementInstructions: string[];
  }> {
    const mapping = this.getBrandMapping(brand, category);
    
    return {
      sizeChart: mapping?.sizeChart || {},
      fitGuide: this.getFitGuide(brand, category),
      measurementInstructions: this.getMeasurementInstructions(category),
    };
  }
 
  private initializeBrandMappings(): void {
    // Initialize with common GCC brands (this would be loaded from database in production)
    
    // Namshi sizing
    this.brandSizeMappings.set('namshi-women-tops', {
      brand: 'Namshi',
      category: 'women-tops',
      sizeChart: {
        'XS': { measurements: { chest: 82, waist: 66, hips: 90 }, fit: 'regular' },
        'S': { measurements: { chest: 86, waist: 70, hips: 94 }, fit: 'regular' },
        'M': { measurements: { chest: 90, waist: 74, hips: 98 }, fit: 'regular' },
        'L': { measurements: { chest: 94, waist: 78, hips: 102 }, fit: 'regular' },
        'XL': { measurements: { chest: 98, waist: 82, hips: 106 }, fit: 'regular' },
      },
    });
 
    // Zara sizing (tends to run small)
    this.brandSizeMappings.set('zara-women-tops', {
      brand: 'Zara',
      category: 'women-tops',
      sizeChart: {
        'XS': { measurements: { chest: 80, waist: 64, hips: 88 }, fit: 'tight' },
        'S': { measurements: { chest: 84, waist: 68, hips: 92 }, fit: 'tight' },
        'M': { measurements: { chest: 88, waist: 72, hips: 96 }, fit: 'tight' },
        'L': { measurements: { chest: 92, waist: 76, hips: 100 }, fit: 'tight' },
        'XL': { measurements: { chest: 96, waist: 80, hips: 104 }, fit: 'tight' },
      },
    });
 
    // H&M sizing (tends to run large)
    this.brandSizeMappings.set('h&m-women-tops', {
      brand: 'H&M',
      category: 'women-tops',
      sizeChart: {
        'XS': { measurements: { chest: 84, waist: 68, hips: 92 }, fit: 'loose' },
        'S': { measurements: { chest: 88, waist: 72, hips: 96 }, fit: 'loose' },
        'M': { measurements: { chest: 92, waist: 76, hips: 100 }, fit: 'loose' },
        'L': { measurements: { chest: 96, waist: 80, hips: 104 }, fit: 'loose' },
        'XL': { measurements: { chest: 100, waist: 84, hips: 108 }, fit: 'loose' },
      },
    });
 
    // Add more brand mappings...
  }
 
  private getUserMeasurements(user: UserDocument): {
    chest?: number;
    waist?: number;
    hips?: number;
    height?: number;
    weight?: number;
  } {
    return {
      chest: (user.measurements as any)?.chest,
      waist: (user.measurements as any)?.waist,
      hips: (user.measurements as any)?.hips,
      height: user.measurements?.height,
      weight: user.measurements?.weight,
    };
  }
 
  private getBrandMapping(brand: string, category: string): BrandSizeMapping | null {
    const key = `${brand.toLowerCase()}-${category.toLowerCase()}`;
    return this.brandSizeMappings.get(key) || null;
  }
 
  private async getUserSizeHistory(
    userId: string,
    brand: string,
    category: string,
  ): Promise<Array<{
    size: string;
    fitFeedback: string;
    product: string;
    date: Date;
  }>> {
    const sizeInteractions = await this.interactionModel.find({
      userId,
      actionType: 'size_feedback',
      'context.brand': brand,
      'context.category': category,
    }).sort({ timestamp: -1 }).limit(10);
 
    return sizeInteractions.map(interaction => ({
      size: (interaction.context as any).actualSize,
      fitFeedback: (interaction.context as any).fitFeedback,
      product: interaction.targetId.toString(),
      date: interaction.timestamp,
    }));
  }
 
  private async generateSizePredictions(params: {
    userMeasurements: any;
    brandMapping: BrandSizeMapping | null;
    sizeHistory: any[];
    product: ProductDocument;
    category: string;
  }): Promise<Array<{
    method: string;
    size: string;
    confidence: number;
    fitType: string;
    reasoning: string;
  }>> {
    const predictions = [];
 
    // Method 1: Measurement-based prediction
    Iif (params.userMeasurements.chest && params.brandMapping) {
      const measurementPrediction = this.predictByMeasurements(
        params.userMeasurements,
        params.brandMapping,
      );
      predictions.push({
        method: 'measurements',
        ...measurementPrediction,
        reasoning: 'Based on your body measurements and brand size chart',
      });
    }
 
    // Method 2: Size history prediction
    Iif (params.sizeHistory.length > 0) {
      const historyPrediction = this.predictByHistory(params.sizeHistory);
      predictions.push({
        method: 'history',
        ...historyPrediction,
        reasoning: `Based on your previous purchases with ${params.brandMapping?.brand || 'this brand'}`,
      });
    }
 
    // Method 3: Collaborative filtering (users with similar measurements)
    const collaborativePrediction = await this.predictByCollaborativeFiltering(
      params.userMeasurements,
      params.product,
    );
    Iif (collaborativePrediction) {
      predictions.push({
        method: 'collaborative',
        ...collaborativePrediction,
        reasoning: 'Based on users with similar measurements',
      });
    }
 
    // Method 4: Default brand prediction
    Iif (predictions.length === 0 && params.brandMapping) {
      const defaultPrediction = this.getDefaultSizePrediction(params.brandMapping);
      predictions.push({
        method: 'default',
        ...defaultPrediction,
        reasoning: 'Based on average sizing for this brand',
      });
    }
 
    return predictions;
  }
 
  private predictByMeasurements(
    userMeasurements: any,
    brandMapping: BrandSizeMapping,
  ): { size: string; confidence: number; fitType: string } {
    const { chest, waist, hips } = userMeasurements;
    const sizeChart = brandMapping.sizeChart;
 
    let bestMatch = { size: 'M', score: Infinity, fitType: 'regular' };
 
    Object.entries(sizeChart).forEach(([size, sizeInfo]) => {
      let score = 0;
      let measurements = 0;
 
      Iif (chest && sizeInfo.measurements.chest) {
        score += Math.abs(chest - sizeInfo.measurements.chest);
        measurements++;
      }
      Iif (waist && sizeInfo.measurements.waist) {
        score += Math.abs(waist - sizeInfo.measurements.waist);
        measurements++;
      }
      Iif (hips && sizeInfo.measurements.hips) {
        score += Math.abs(hips - sizeInfo.measurements.hips);
        measurements++;
      }
 
      Iif (measurements > 0) {
        score = score / measurements; // Average difference
        Iif (score < bestMatch.score) {
          bestMatch = {
            size,
            score,
            fitType: sizeInfo.fit,
          };
        }
      }
    });
 
    // Calculate confidence based on how close the match is
    const confidence = Math.max(0.3, 1 - (bestMatch.score / 10)); // Normalize score to confidence
 
    return {
      size: bestMatch.size,
      confidence,
      fitType: bestMatch.fitType,
    };
  }
 
  private predictByHistory(
    sizeHistory: any[],
  ): { size: string; confidence: number; fitType: string } {
    // Find the most common size that fit perfectly
    const perfectFits = sizeHistory.filter(h => h.fitFeedback === 'perfect');
    
    Iif (perfectFits.length > 0) {
      const sizeCounts = new Map<string, number>();
      perfectFits.forEach(fit => {
        sizeCounts.set(fit.size, (sizeCounts.get(fit.size) || 0) + 1);
      });
 
      const mostCommonSize = Array.from(sizeCounts.entries())
        .sort(([, a], [, b]) => b - a)[0];
 
      return {
        size: mostCommonSize[0],
        confidence: Math.min(0.9, mostCommonSize[1] / perfectFits.length),
        fitType: 'perfect',
      };
    }
 
    // If no perfect fits, analyze the pattern
    Iif (sizeHistory.length > 0) {
      const lastSize = sizeHistory[0]; // Most recent
      let adjustedSize = lastSize.size;
 
      if (lastSize.fitFeedback === 'too_small') {
        adjustedSize = this.getSizeUp(lastSize.size);
      } else Iif (lastSize.fitFeedback === 'too_large') {
        adjustedSize = this.getSizeDown(lastSize.size);
      }
 
      return {
        size: adjustedSize,
        confidence: 0.6,
        fitType: 'perfect',
      };
    }
 
    return {
      size: 'M',
      confidence: 0.3,
      fitType: 'regular',
    };
  }
 
  private async predictByCollaborativeFiltering(
    userMeasurements: any,
    product: ProductDocument,
  ): Promise<{ size: string; confidence: number; fitType: string } | null> {
    // Find users with similar measurements who bought this product
    const similarUsers = await this.userModel.find({
      'measurements.chest': {
        $gte: (userMeasurements.chest || 90) - 5,
        $lte: (userMeasurements.chest || 90) + 5,
      },
      'measurements.waist': {
        $gte: (userMeasurements.waist || 70) - 5,
        $lte: (userMeasurements.waist || 70) + 5,
      },
    }).limit(20);
 
    Iif (similarUsers.length === 0) return null;
 
    // Get their size feedback for this product
    const sizeFeedback = await this.interactionModel.find({
      userId: { $in: similarUsers.map(u => u._id) },
      targetId: product._id,
      actionType: 'size_feedback',
      'context.fitFeedback': 'perfect',
    });
 
    Iif (sizeFeedback.length === 0) return null;
 
    // Find most common size
    const sizeCounts = new Map<string, number>();
    sizeFeedback.forEach(feedback => {
      const size = (feedback.context as any).actualSize;
      sizeCounts.set(size, (sizeCounts.get(size) || 0) + 1);
    });
 
    const mostCommonSize = Array.from(sizeCounts.entries())
      .sort(([, a], [, b]) => b - a)[0];
 
    return {
      size: mostCommonSize[0],
      confidence: Math.min(0.8, mostCommonSize[1] / sizeFeedback.length),
      fitType: 'perfect',
    };
  }
 
  private getDefaultSizePrediction(
    brandMapping: BrandSizeMapping,
  ): { size: string; confidence: number; fitType: string } {
    // Return medium as default with low confidence
    return {
      size: 'M',
      confidence: 0.4,
      fitType: brandMapping.sizeChart['M']?.fit || 'regular',
    };
  }
 
  private combinePredictions(
    predictions: Array<{
      method: string;
      size: string;
      confidence: number;
      fitType: string;
      reasoning: string;
    }>,
  ): {
    recommendedSize: string;
    confidence: number;
    fitType: 'tight' | 'perfect' | 'loose';
    alternatives: Array<{
      size: string;
      fitType: string;
      confidence: number;
    }>;
    factors: Array<{
      factor: string;
      weight: number;
      contribution: string;
    }>;
  } {
    Iif (predictions.length === 0) {
      return {
        recommendedSize: 'M',
        confidence: 0.3,
        fitType: 'perfect',
        alternatives: [],
        factors: [],
      };
    }
 
    // Weight different prediction methods
    const methodWeights = {
      measurements: 0.4,
      history: 0.3,
      collaborative: 0.2,
      default: 0.1,
    };
 
    // Calculate weighted scores for each size
    const sizeScores = new Map<string, { score: number; fitTypes: string[] }>();
    const factors = [];
 
    predictions.forEach(prediction => {
      const weight = methodWeights[prediction.method] || 0.1;
      const score = prediction.confidence * weight;
 
      const existing = sizeScores.get(prediction.size) || { score: 0, fitTypes: [] };
      existing.score += score;
      existing.fitTypes.push(prediction.fitType);
      sizeScores.set(prediction.size, existing);
 
      factors.push({
        factor: prediction.method,
        weight,
        contribution: `${prediction.reasoning} (confidence: ${Math.round(prediction.confidence * 100)}%)`,
      });
    });
 
    // Get the best size
    const bestSize = Array.from(sizeScores.entries())
      .sort(([, a], [, b]) => b.score - a.score)[0];
 
    const recommendedSize = bestSize[0];
    const confidence = Math.min(0.95, bestSize[1].score);
    
    // Determine fit type (most common among predictions)
    const fitTypeCounts = new Map<string, number>();
    bestSize[1].fitTypes.forEach(fitType => {
      fitTypeCounts.set(fitType, (fitTypeCounts.get(fitType) || 0) + 1);
    });
    
    const fitType = Array.from(fitTypeCounts.entries())
      .sort(([, a], [, b]) => b - a)[0]?.[0] as 'tight' | 'perfect' | 'loose' || 'perfect';
 
    // Generate alternatives
    const alternatives = Array.from(sizeScores.entries())
      .filter(([size]) => size !== recommendedSize)
      .sort(([, a], [, b]) => b.score - a.score)
      .slice(0, 2)
      .map(([size, data]) => ({
        size,
        fitType: data.fitTypes[0] || 'regular',
        confidence: Math.min(0.9, data.score),
      }));
 
    return {
      recommendedSize,
      confidence,
      fitType,
      alternatives,
      factors,
    };
  }
 
  private generateSizeReasoning(
    prediction: any,
    predictions: any[],
  ): string {
    const reasons = predictions
      .filter(p => p.confidence > 0.5)
      .map(p => p.reasoning);
 
    Iif (reasons.length === 0) {
      return `Size ${prediction.recommendedSize} recommended based on general sizing guidelines`;
    }
 
    return `Size ${prediction.recommendedSize} recommended: ${reasons.join('. ')}`;
  }
 
  private getSizeUp(currentSize: string): string {
    const sizeOrder = ['XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL'];
    const currentIndex = sizeOrder.indexOf(currentSize);
    return currentIndex < sizeOrder.length - 1 ? sizeOrder[currentIndex + 1] : currentSize;
  }
 
  private getSizeDown(currentSize: string): string {
    const sizeOrder = ['XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL'];
    const currentIndex = sizeOrder.indexOf(currentSize);
    return currentIndex > 0 ? sizeOrder[currentIndex - 1] : currentSize;
  }
 
  private async updateUserMeasurements(
    userId: string,
    measurements: { chest?: number; waist?: number; hips?: number },
  ): Promise<void> {
    await this.userModel.findByIdAndUpdate(userId, {
      $set: {
        'measurements.chest': measurements.chest,
        'measurements.waist': measurements.waist,
        'measurements.hips': measurements.hips,
        'measurements.lastUpdated': new Date(),
      },
    });
  }
 
  private getFitGuide(brand: string, category: string): string[] {
    return [
      'Measure yourself wearing the undergarments you plan to wear with the item',
      'Use a soft measuring tape and keep it parallel to the floor',
      'Take measurements over bare skin or close-fitting clothes',
      'For the most accurate fit, have someone help you measure',
      'Compare your measurements to the size chart rather than your usual size',
    ];
  }
 
  private getMeasurementInstructions(category: string): string[] {
    const instructions = {
      'tops': [
        'Chest: Measure around the fullest part of your chest',
        'Waist: Measure around your natural waistline',
        'Length: Measure from shoulder to desired hemline',
      ],
      'bottoms': [
        'Waist: Measure around your natural waistline',
        'Hips: Measure around the fullest part of your hips',
        'Inseam: Measure from crotch to desired hem length',
      ],
      'dresses': [
        'Chest: Measure around the fullest part of your chest',
        'Waist: Measure around your natural waistline',
        'Hips: Measure around the fullest part of your hips',
        'Length: Measure from shoulder to desired hemline',
      ],
    };
 
    return instructions[category.toLowerCase()] || instructions['tops'];
  }
}