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 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 | import { Injectable, Logger } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { ConfigService } from '@nestjs/config'; import { Cron, CronExpression } from '@nestjs/schedule'; import { Coupon, CouponDocument } from '../../../database/schemas/coupon.schema'; import { Product, ProductDocument } from '../../../database/schemas/product.schema'; import { UserSavings, UserSavingsDocument } from '../../../database/schemas/user-savings.schema'; import { AIService } from '../../ai/services/ai.service'; export interface Deal { id: string; type: 'price_drop' | 'coupon_combo' | 'seasonal' | 'flash_sale' | 'bundle' | 'clearance'; title: string; description: string; productId: string; originalPrice: number; dealPrice: number; savingsAmount: number; savingsPercentage: number; currency: string; retailerId: string; coupons?: string[]; validUntil?: Date; urgency: 'low' | 'medium' | 'high' | 'critical'; confidence: number; // 0-100, AI confidence in deal quality tags: string[]; category: string; brand: string; imageUrl?: string; affiliateUrl: string; isExclusive: boolean; stockLevel?: 'high' | 'medium' | 'low' | 'critical'; historicalContext: { lowestPrice: number; averagePrice: number; priceDropFrequency: number; lastSaleDate?: Date; }; aiInsights: { dealQuality: string; priceHistory: string; recommendation: string; bestTimeToBuy: string; }; } export interface DealAlert { userId: string; dealId: string; alertType: 'price_target' | 'back_in_stock' | 'new_coupon' | 'flash_sale'; targetPrice?: number; notificationSent: boolean; createdAt: Date; } @Injectable() export class DealDetectionService { private readonly logger = new Logger(DealDetectionService.name); constructor( @InjectModel(Coupon.name) private couponModel: Model<CouponDocument>, @InjectModel(Product.name) private productModel: Model<ProductDocument>, @InjectModel(UserSavings.name) private userSavingsModel: Model<UserSavingsDocument>, private aiService: AIService, private configService: ConfigService, ) {} // Run deal detection every 2 hours @Cron(CronExpression.EVERY_2_HOURS) async scheduledDealDetection(): Promise<void> { this.logger.log('Starting scheduled deal detection'); await this.detectAllDeals(); } async detectAllDeals(): Promise<{ totalDeals: number; newDeals: number; categories: Record<string, number>; topDeals: Deal[]; }> { try { const [ priceDropDeals, couponComboDeals, seasonalDeals, flashSaleDeals, clearanceDeals, ] = await Promise.all([ this.detectPriceDropDeals(), this.detectCouponComboDeals(), this.detectSeasonalDeals(), this.detectFlashSaleDeals(), this.detectClearanceDeals(), ]); const allDeals = [ ...priceDropDeals, ...couponComboDeals, ...seasonalDeals, ...flashSaleDeals, ...clearanceDeals, ]; // Sort by savings amount and confidence const topDeals = allDeals .sort((a, b) => (b.savingsAmount * b.confidence) - (a.savingsAmount * a.confidence)) .slice(0, 50); // Categorize deals const categories = allDeals.reduce((acc, deal) => { acc[deal.category] = (acc[deal.category] || 0) + 1; return acc; }, {} as Record<string, number>); this.logger.log(`Deal detection completed: ${allDeals.length} deals found`); return { totalDeals: allDeals.length, newDeals: allDeals.length, // All are considered new in this context categories, topDeals, }; } catch (error) { this.logger.error('Error in deal detection', error); throw error; } } async detectPriceDropDeals(): Promise<Deal[]> { try { // Find products with significant price drops in the last 24 hours const products = await this.productModel.aggregate([ { $match: { isActive: true, updatedAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) }, }, }, { $unwind: '$variants', }, { $match: { 'variants.price.discount': { $gte: 20 }, // At least 20% discount }, }, { $limit: 100, }, ]); const deals: Deal[] = []; for (const product of products) { const variant = product.variants; const savingsAmount = variant.price.original - variant.price.current; const savingsPercentage = variant.price.discount; Iif (savingsAmount > 50) { // Minimum 50 AED savings const aiInsights = await this.generateAIInsights(product, 'price_drop'); deals.push({ id: `price_drop_${product._id}_${variant.sku}`, type: 'price_drop', title: `${savingsPercentage}% Off ${product.title}`, description: `Save ${variant.price.currency} ${savingsAmount.toFixed(2)} on this ${product.brand} item`, productId: product._id.toString(), originalPrice: variant.price.original, dealPrice: variant.price.current, savingsAmount, savingsPercentage, currency: variant.price.currency, retailerId: variant.retailerSpecific.retailerId.toString(), urgency: this.calculateUrgency(savingsPercentage, null), confidence: this.calculateConfidence(product, savingsPercentage), tags: ['price_drop', 'limited_time', product.category.main], category: product.category.main, brand: product.brand, imageUrl: product.images[0]?.url, affiliateUrl: variant.retailerSpecific.affiliateUrl, isExclusive: false, stockLevel: this.estimateStockLevel(variant.availability), historicalContext: { lowestPrice: variant.price.current, averagePrice: variant.price.original * 0.9, // Estimate priceDropFrequency: 0.1, // Estimate }, aiInsights, }); } } return deals; } catch (error) { this.logger.error('Error detecting price drop deals', error); return []; } } async detectCouponComboDeals(): Promise<Deal[]> { try { // Find products that can be combined with multiple coupons for maximum savings const activeCoupons = await this.couponModel.find({ status: 'active', validUntil: { $gte: new Date() }, }).populate('retailerId'); const deals: Deal[] = []; const retailerCoupons = new Map<string, CouponDocument[]>(); // Group coupons by retailer activeCoupons.forEach(coupon => { const retailerId = coupon.retailerId.toString(); Iif (!retailerCoupons.has(retailerId)) { retailerCoupons.set(retailerId, []); } retailerCoupons.get(retailerId)!.push(coupon); }); // Find products that can benefit from multiple coupons for (const [retailerId, coupons] of retailerCoupons) { Iif (coupons.length < 2) continue; // Need at least 2 coupons for combo const products = await this.productModel.find({ 'variants.retailerSpecific.retailerId': retailerId, isActive: true, }).limit(20); for (const product of products) { const applicableCoupons = coupons.filter(coupon => this.isCouponApplicableToProduct(coupon, product) ); Iif (applicableCoupons.length >= 2) { const bestCombo = this.findBestCouponCombination(applicableCoupons, product); Iif (bestCombo.totalSavings > 30) { // Minimum 30 AED savings const aiInsights = await this.generateAIInsights(product, 'coupon_combo'); deals.push({ id: `combo_${product._id}_${bestCombo.coupons.map(c => c.code).join('_')}`, type: 'coupon_combo', title: `Stack ${bestCombo.coupons.length} Coupons: ${product.title}`, description: `Combine multiple coupons for maximum savings on ${product.brand}`, productId: product._id.toString(), originalPrice: bestCombo.originalPrice, dealPrice: bestCombo.finalPrice, savingsAmount: bestCombo.totalSavings, savingsPercentage: (bestCombo.totalSavings / bestCombo.originalPrice) * 100, currency: 'AED', retailerId, coupons: bestCombo.coupons.map(c => c.code), validUntil: new Date(Math.min(...bestCombo.coupons.map(c => c.validUntil.getTime()))), urgency: this.calculateUrgency(bestCombo.totalSavings / bestCombo.originalPrice * 100, bestCombo.coupons[0].validUntil), confidence: 85, // High confidence for coupon combos tags: ['coupon_combo', 'stack_savings', product.category.main], category: product.category.main, brand: product.brand, imageUrl: product.images[0]?.url, affiliateUrl: product.variants[0]?.retailerSpecific.affiliateUrl, isExclusive: bestCombo.coupons.some(c => c.isExclusive), historicalContext: { lowestPrice: bestCombo.finalPrice, averagePrice: bestCombo.originalPrice, priceDropFrequency: 0.3, }, aiInsights, }); } } } } return deals; } catch (error) { this.logger.error('Error detecting coupon combo deals', error); return []; } } async detectSeasonalDeals(): Promise<Deal[]> { try { const currentMonth = new Date().getMonth(); const seasonalCategories = this.getSeasonalCategories(currentMonth); const products = await this.productModel.find({ 'category.main': { $in: seasonalCategories }, isActive: true, $or: [ { 'variants.price.discount': { $gte: 15 } }, { 'aiFeatures.seasonality': { $in: this.getCurrentSeason() } }, ], }).limit(50); const deals: Deal[] = []; for (const product of products) { const variant = product.variants[0]; Iif (!variant) continue; const savingsAmount = variant.price.original - variant.price.current; const savingsPercentage = variant.price.discount || 0; Iif (savingsAmount > 25) { const aiInsights = await this.generateAIInsights(product, 'seasonal'); deals.push({ id: `seasonal_${product._id}`, type: 'seasonal', title: `${this.getCurrentSeason()[0]} Sale: ${product.title}`, description: `Perfect for the season - ${product.brand} at a great price`, productId: product._id.toString(), originalPrice: variant.price.original, dealPrice: variant.price.current, savingsAmount, savingsPercentage, currency: variant.price.currency, retailerId: variant.retailerSpecific.retailerId.toString(), urgency: 'medium', confidence: 75, tags: ['seasonal', this.getCurrentSeason()[0].toLowerCase(), product.category.main], category: product.category.main, brand: product.brand, imageUrl: product.images[0]?.url, affiliateUrl: variant.retailerSpecific.affiliateUrl, isExclusive: false, historicalContext: { lowestPrice: variant.price.current, averagePrice: variant.price.original * 0.85, priceDropFrequency: 0.2, }, aiInsights, }); } } return deals; } catch (error) { this.logger.error('Error detecting seasonal deals', error); return []; } } async detectFlashSaleDeals(): Promise<Deal[]> { try { // Look for products with very recent, high discounts (flash sales) const products = await this.productModel.find({ isActive: true, updatedAt: { $gte: new Date(Date.now() - 6 * 60 * 60 * 1000) }, // Last 6 hours 'variants.price.discount': { $gte: 30 }, // At least 30% off }).limit(30); const deals: Deal[] = []; for (const product of products) { const variant = product.variants[0]; Iif (!variant) continue; const savingsAmount = variant.price.original - variant.price.current; const savingsPercentage = variant.price.discount || 0; // Flash sales typically have high discounts and urgency Iif (savingsPercentage >= 40) { const aiInsights = await this.generateAIInsights(product, 'flash_sale'); deals.push({ id: `flash_${product._id}`, type: 'flash_sale', title: `⚡ Flash Sale: ${savingsPercentage}% Off ${product.title}`, description: `Limited time flash sale on ${product.brand} - act fast!`, productId: product._id.toString(), originalPrice: variant.price.original, dealPrice: variant.price.current, savingsAmount, savingsPercentage, currency: variant.price.currency, retailerId: variant.retailerSpecific.retailerId.toString(), validUntil: new Date(Date.now() + 24 * 60 * 60 * 1000), // Assume 24 hours urgency: 'critical', confidence: 90, tags: ['flash_sale', 'limited_time', 'urgent', product.category.main], category: product.category.main, brand: product.brand, imageUrl: product.images[0]?.url, affiliateUrl: variant.retailerSpecific.affiliateUrl, isExclusive: true, stockLevel: 'low', // Flash sales typically have limited stock historicalContext: { lowestPrice: variant.price.current, averagePrice: variant.price.original, priceDropFrequency: 0.05, // Rare }, aiInsights, }); } } return deals; } catch (error) { this.logger.error('Error detecting flash sale deals', error); return []; } } async detectClearanceDeals(): Promise<Deal[]> { try { // Look for products that might be on clearance (old inventory, discontinued) const products = await this.productModel.find({ isActive: true, createdAt: { $lte: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000) }, // Older than 90 days 'variants.price.discount': { $gte: 25 }, 'variants.availability.quantity': { $lte: 10 }, // Low stock }).limit(40); const deals: Deal[] = []; for (const product of products) { const variant = product.variants[0]; Iif (!variant) continue; const savingsAmount = variant.price.original - variant.price.current; const savingsPercentage = variant.price.discount || 0; const aiInsights = await this.generateAIInsights(product, 'clearance'); deals.push({ id: `clearance_${product._id}`, type: 'clearance', title: `Clearance: ${product.title}`, description: `Final clearance pricing on ${product.brand} - while supplies last`, productId: product._id.toString(), originalPrice: variant.price.original, dealPrice: variant.price.current, savingsAmount, savingsPercentage, currency: variant.price.currency, retailerId: variant.retailerSpecific.retailerId.toString(), urgency: 'high', confidence: 70, tags: ['clearance', 'final_sale', 'limited_stock', product.category.main], category: product.category.main, brand: product.brand, imageUrl: product.images[0]?.url, affiliateUrl: variant.retailerSpecific.affiliateUrl, isExclusive: false, stockLevel: 'critical', historicalContext: { lowestPrice: variant.price.current, averagePrice: variant.price.original * 0.8, priceDropFrequency: 0.1, }, aiInsights, }); } return deals; } catch (error) { this.logger.error('Error detecting clearance deals', error); return []; } } private async generateAIInsights(product: any, dealType: string): Promise<Deal['aiInsights']> { try { const prompt = `Analyze this ${dealType} deal for a ${product.category.main} product: Product: ${product.title} Brand: ${product.brand} Original Price: ${product.variants[0]?.price.original} ${product.variants[0]?.price.currency} Current Price: ${product.variants[0]?.price.current} ${product.variants[0]?.price.currency} Discount: ${product.variants[0]?.price.discount}% Provide insights on: 1. Deal quality (excellent/good/fair/poor) 2. Price history context 3. Recommendation for buyers 4. Best time to buy advice Keep responses concise and helpful.`; const aiResponse = await this.aiService.chat({ messages: [{ role: 'user', content: prompt }], maxTokens: 200, temperature: 0.3, }); // Parse AI response into structured insights const lines = aiResponse.message.split('\n').filter(line => line.trim()); return { dealQuality: lines[0] || 'Good deal with solid savings', priceHistory: lines[1] || 'Price has dropped recently', recommendation: lines[2] || 'Recommended for buyers looking for value', bestTimeToBuy: lines[3] || 'Buy now if you need this item', }; } catch (error) { this.logger.error('Error generating AI insights', error); return { dealQuality: 'Good savings opportunity', priceHistory: 'Recent price reduction detected', recommendation: 'Consider purchasing if item matches your needs', bestTimeToBuy: 'Current pricing is favorable', }; } } private calculateUrgency(savingsPercentage: number, expiryDate?: Date): Deal['urgency'] { let urgencyScore = 0; // Savings percentage factor if (savingsPercentage >= 50) urgencyScore += 3; else if (savingsPercentage >= 30) urgencyScore += 2; else Iif (savingsPercentage >= 20) urgencyScore += 1; // Time factor Iif (expiryDate) { const hoursUntilExpiry = (expiryDate.getTime() - Date.now()) / (1000 * 60 * 60); if (hoursUntilExpiry <= 24) urgencyScore += 2; else Iif (hoursUntilExpiry <= 72) urgencyScore += 1; } Iif (urgencyScore >= 4) return 'critical'; Iif (urgencyScore >= 3) return 'high'; Iif (urgencyScore >= 2) return 'medium'; return 'low'; } private calculateConfidence(product: any, savingsPercentage: number): number { let confidence = 50; // Base confidence // Brand factor const popularBrands = ['Nike', 'Adidas', 'Zara', 'H&M', 'Samsung', 'Apple']; Iif (popularBrands.includes(product.brand)) confidence += 20; // Savings factor if (savingsPercentage >= 40) confidence += 20; else if (savingsPercentage >= 25) confidence += 15; else Iif (savingsPercentage >= 15) confidence += 10; // Product metrics factor Iif (product.metrics?.rating >= 4.0) confidence += 10; Iif (product.metrics?.reviewCount >= 50) confidence += 5; return Math.min(confidence, 100); } private isCouponApplicableToProduct(coupon: CouponDocument, product: any): boolean { // Check category restrictions Iif (coupon.conditions.categories?.length > 0) { const hasMatchingCategory = coupon.conditions.categories.some( category => product.category.main === category || product.category.sub === category || product.category.tags.includes(category) ); Iif (!hasMatchingCategory) return false; } // Check brand restrictions Iif (coupon.conditions.brands?.length > 0) { Iif (!coupon.conditions.brands.includes(product.brand)) return false; } // Check excluded products Iif (coupon.conditions.excludedProducts?.some(id => id.toString() === product._id.toString())) { return false; } return true; } private findBestCouponCombination(coupons: CouponDocument[], product: any): { coupons: CouponDocument[]; originalPrice: number; finalPrice: number; totalSavings: number; } { const originalPrice = product.variants[0]?.price.current || 0; let bestCombo = { coupons: [coupons[0]], originalPrice, finalPrice: originalPrice, totalSavings: 0, }; // Try different combinations (simplified - in reality would be more complex) for (let i = 0; i < coupons.length; i++) { for (let j = i + 1; j < coupons.length; j++) { const combo = [coupons[i], coupons[j]]; const { finalPrice, totalSavings } = this.calculateCombinedDiscount(combo, originalPrice); Iif (totalSavings > bestCombo.totalSavings) { bestCombo = { coupons: combo, originalPrice, finalPrice, totalSavings, }; } } } return bestCombo; } private calculateCombinedDiscount(coupons: CouponDocument[], originalPrice: number): { finalPrice: number; totalSavings: number; } { let currentPrice = originalPrice; for (const coupon of coupons) { switch (coupon.discountType) { case 'percentage': const percentageDiscount = (currentPrice * coupon.discountValue) / 100; const maxDiscount = coupon.maximumDiscount || percentageDiscount; currentPrice -= Math.min(percentageDiscount, maxDiscount); break; case 'fixed': currentPrice -= coupon.discountValue; break; case 'shipping': currentPrice -= 15; // Assume 15 AED shipping break; } } const finalPrice = Math.max(0, currentPrice); const totalSavings = originalPrice - finalPrice; return { finalPrice, totalSavings }; } private getSeasonalCategories(month: number): string[] { const seasonalMap = { 0: ['winter_wear', 'coats', 'boots'], // January 1: ['winter_wear', 'valentine_gifts'], // February 2: ['spring_wear', 'light_jackets'], // March 3: ['spring_wear', 'dresses'], // April 4: ['summer_prep', 'swimwear'], // May 5: ['summer_wear', 'sandals'], // June 6: ['summer_wear', 'shorts'], // July 7: ['summer_wear', 'back_to_school'], // August 8: ['fall_wear', 'back_to_school'], // September 9: ['fall_wear', 'boots'], // October 10: ['winter_prep', 'coats'], // November 11: ['winter_wear', 'holiday_gifts'], // December }; return seasonalMap[month] || ['general']; } private getCurrentSeason(): string[] { const month = new Date().getMonth(); Iif (month >= 2 && month <= 4) return ['Spring']; Iif (month >= 5 && month <= 7) return ['Summer']; Iif (month >= 8 && month <= 10) return ['Fall', 'Autumn']; return ['Winter']; } private estimateStockLevel(availability: any): Deal['stockLevel'] { Iif (!availability?.quantity) return 'medium'; Iif (availability.quantity <= 5) return 'critical'; Iif (availability.quantity <= 20) return 'low'; Iif (availability.quantity <= 100) return 'medium'; return 'high'; } async getPersonalizedDeals(userId: string, limit: number = 20): Promise<Deal[]> { try { // Get user preferences and purchase history const userSavings = await this.userSavingsModel.findOne({ userId }); // For now, return general deals - would be personalized based on user data const allDeals = await this.detectAllDeals(); return allDeals.topDeals.slice(0, limit); } catch (error) { this.logger.error(`Error getting personalized deals for user ${userId}`, error); return []; } } async getDealsByCategory(category: string, limit: number = 10): Promise<Deal[]> { try { const allDeals = await this.detectAllDeals(); return allDeals.topDeals .filter(deal => deal.category === category) .slice(0, limit); } catch (error) { this.logger.error(`Error getting deals for category ${category}`, error); return []; } } } |