All files / src/modules/coupons/services coupon-validation.service.ts

0% Statements 0/149
0% Branches 0/61
0% Functions 0/22
0% Lines 0/140

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { ConfigService } from '@nestjs/config';
import axios, { AxiosInstance } from 'axios';
import { Coupon, CouponDocument } from '../../../database/schemas/coupon.schema';
import { Product, ProductDocument } from '../../../database/schemas/product.schema';
import { Retailer, RetailerDocument } from '../../../database/schemas/retailer.schema';
 
export interface CouponValidationResult {
  isValid: boolean;
  discountAmount?: number;
  discountType?: string;
  minimumPurchase?: number;
  maximumDiscount?: number;
  errorMessage?: string;
  expiryDate?: Date;
  usageLimit?: {
    total: number;
    remaining: number;
    perUser: number;
  };
  applicableProducts?: string[];
  restrictions?: {
    categories?: string[];
    brands?: string[];
    excludedProducts?: string[];
    regions?: string[];
    userTiers?: string[];
  };
}
 
export interface CouponApplicationResult {
  success: boolean;
  originalPrice: number;
  discountedPrice: number;
  savingsAmount: number;
  couponCode: string;
  discountType: string;
  message: string;
  affiliateUrl?: string;
}
 
@Injectable()
export class CouponValidationService {
  private readonly logger = new Logger(CouponValidationService.name);
  private readonly httpClient: AxiosInstance;
 
  constructor(
    @InjectModel(Coupon.name) private couponModel: Model<CouponDocument>,
    @InjectModel(Product.name) private productModel: Model<ProductDocument>,
    @InjectModel(Retailer.name) private retailerModel: Model<RetailerDocument>,
    private configService: ConfigService,
  ) {
    this.httpClient = axios.create({
      timeout: 10000,
      headers: {
        'User-Agent': 'SavePal/1.0 Coupon Validator',
      },
    });
  }
 
  async validateCoupon(
    couponCode: string,
    retailerId: string,
    productId?: string,
    userId?: string,
    purchaseAmount?: number,
  ): Promise<CouponValidationResult> {
    try {
      // Find coupon in database
      const coupon = await this.couponModel.findOne({
        code: couponCode,
        retailerId,
        status: 'active',
        validFrom: { $lte: new Date() },
        validUntil: { $gte: new Date() },
      }).populate('retailerId');
 
      Iif (!coupon) {
        return {
          isValid: false,
          errorMessage: 'Coupon not found or expired',
        };
      }
 
      // Check usage limits
      const usageLimitCheck = await this.checkUsageLimits(coupon, userId);
      Iif (!usageLimitCheck.valid) {
        return {
          isValid: false,
          errorMessage: usageLimitCheck.message,
        };
      }
 
      // Check minimum purchase requirement
      Iif (purchaseAmount && coupon.minimumPurchase && purchaseAmount < coupon.minimumPurchase) {
        return {
          isValid: false,
          errorMessage: `Minimum purchase of ${coupon.currency} ${coupon.minimumPurchase} required`,
        };
      }
 
      // Check product/category restrictions
      Iif (productId) {
        const productEligibility = await this.checkProductEligibility(coupon, productId);
        Iif (!productEligibility.eligible) {
          return {
            isValid: false,
            errorMessage: productEligibility.message,
          };
        }
      }
 
      // Validate with retailer API if available
      const retailerValidation = await this.validateWithRetailer(coupon, productId, purchaseAmount);
      
      Iif (!retailerValidation.isValid) {
        // Update coupon status if it's no longer valid
        await this.couponModel.findByIdAndUpdate(coupon._id, {
          status: 'expired',
          updatedAt: new Date(),
        });
        
        return retailerValidation;
      }
 
      // Calculate discount amount
      const discountAmount = this.calculateDiscountAmount(
        coupon,
        purchaseAmount || 0,
      );
 
      return {
        isValid: true,
        discountAmount,
        discountType: coupon.discountType,
        minimumPurchase: coupon.minimumPurchase,
        maximumDiscount: coupon.maximumDiscount,
        expiryDate: coupon.validUntil,
        usageLimit: {
          total: coupon.usageLimit.total,
          remaining: coupon.usageLimit.total - coupon.usageLimit.used,
          perUser: coupon.usageLimit.perUser,
        },
        restrictions: {
          categories: coupon.conditions.categories,
          brands: coupon.conditions.brands,
          excludedProducts: coupon.conditions.excludedProducts?.map(id => id.toString()),
          regions: coupon.conditions.regions,
          userTiers: coupon.conditions.userTiers,
        },
      };
    } catch (error) {
      this.logger.error(`Error validating coupon ${couponCode}`, error);
      return {
        isValid: false,
        errorMessage: 'Validation service temporarily unavailable',
      };
    }
  }
 
  async applyCouponToProduct(
    couponCode: string,
    productId: string,
    variantSku: string,
    userId?: string,
  ): Promise<CouponApplicationResult> {
    try {
      const product = await this.productModel.findById(productId);
      Iif (!product) {
        return {
          success: false,
          originalPrice: 0,
          discountedPrice: 0,
          savingsAmount: 0,
          couponCode,
          discountType: '',
          message: 'Product not found',
        };
      }
 
      const variant = product.variants.find(v => v.sku === variantSku);
      Iif (!variant) {
        return {
          success: false,
          originalPrice: 0,
          discountedPrice: 0,
          savingsAmount: 0,
          couponCode,
          discountType: '',
          message: 'Product variant not found',
        };
      }
 
      const originalPrice = variant.price.current;
      const retailerId = variant.retailerSpecific.retailerId.toString();
 
      // Validate coupon
      const validation = await this.validateCoupon(
        couponCode,
        retailerId,
        productId,
        userId,
        originalPrice,
      );
 
      Iif (!validation.isValid) {
        return {
          success: false,
          originalPrice,
          discountedPrice: originalPrice,
          savingsAmount: 0,
          couponCode,
          discountType: validation.discountType || '',
          message: validation.errorMessage || 'Coupon is not valid',
        };
      }
 
      const discountAmount = validation.discountAmount || 0;
      const discountedPrice = Math.max(0, originalPrice - discountAmount);
      const savingsAmount = originalPrice - discountedPrice;
 
      // Generate affiliate URL with coupon pre-applied
      const affiliateUrl = await this.generateAffiliateUrlWithCoupon(
        variant.retailerSpecific.affiliateUrl,
        couponCode,
        retailerId,
      );
 
      return {
        success: true,
        originalPrice,
        discountedPrice,
        savingsAmount,
        couponCode,
        discountType: validation.discountType || '',
        message: `Save ${variant.price.currency} ${savingsAmount.toFixed(2)} with coupon ${couponCode}`,
        affiliateUrl,
      };
    } catch (error) {
      this.logger.error(`Error applying coupon ${couponCode} to product ${productId}`, error);
      return {
        success: false,
        originalPrice: 0,
        discountedPrice: 0,
        savingsAmount: 0,
        couponCode,
        discountType: '',
        message: 'Failed to apply coupon',
      };
    }
  }
 
  async findBestCouponsForProduct(
    productId: string,
    variantSku: string,
    userId?: string,
  ): Promise<CouponApplicationResult[]> {
    try {
      const product = await this.productModel.findById(productId);
      Iif (!product) return [];
 
      const variant = product.variants.find(v => v.sku === variantSku);
      Iif (!variant) return [];
 
      const retailerId = variant.retailerSpecific.retailerId;
 
      // Find all applicable coupons
      const coupons = await this.couponModel.find({
        retailerId,
        status: 'active',
        validFrom: { $lte: new Date() },
        validUntil: { $gte: new Date() },
        $or: [
          { 'conditions.categories': { $in: [product.category.main, product.category.sub] } },
          { 'conditions.brands': product.brand },
          { 'conditions.categories': { $size: 0 } }, // No category restrictions
        ],
      }).sort({ priority: -1, discountValue: -1 });
 
      const results: CouponApplicationResult[] = [];
 
      for (const coupon of coupons) {
        const application = await this.applyCouponToProduct(
          coupon.code,
          productId,
          variantSku,
          userId,
        );
 
        Iif (application.success && application.savingsAmount > 0) {
          results.push(application);
        }
      }
 
      // Sort by savings amount (highest first)
      return results.sort((a, b) => b.savingsAmount - a.savingsAmount);
    } catch (error) {
      this.logger.error(`Error finding best coupons for product ${productId}`, error);
      return [];
    }
  }
 
  async validateBulkCoupons(
    couponCodes: string[],
    retailerId: string,
    productIds?: string[],
    userId?: string,
  ): Promise<Record<string, CouponValidationResult>> {
    const results: Record<string, CouponValidationResult> = {};
 
    await Promise.all(
      couponCodes.map(async (code) => {
        results[code] = await this.validateCoupon(
          code,
          retailerId,
          productIds?.[0],
          userId,
        );
      }),
    );
 
    return results;
  }
 
  private async checkUsageLimits(
    coupon: CouponDocument,
    userId?: string,
  ): Promise<{ valid: boolean; message?: string }> {
    // Check total usage limit
    Iif (coupon.usageLimit.total > 0 && coupon.usageLimit.used >= coupon.usageLimit.total) {
      return {
        valid: false,
        message: 'Coupon usage limit exceeded',
      };
    }
 
    // Check per-user usage limit
    Iif (userId && coupon.usageLimit.perUser > 0) {
      // This would require a separate collection to track user-specific usage
      // For now, we'll assume it's valid
    }
 
    return { valid: true };
  }
 
  private async checkProductEligibility(
    coupon: CouponDocument,
    productId: string,
  ): Promise<{ eligible: boolean; message?: string }> {
    const product = await this.productModel.findById(productId);
    Iif (!product) {
      return {
        eligible: false,
        message: 'Product not found',
      };
    }
 
    // Check excluded products
    Iif (coupon.conditions.excludedProducts?.some(id => id.toString() === productId)) {
      return {
        eligible: false,
        message: 'Product is excluded from this coupon',
      };
    }
 
    // 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 {
          eligible: false,
          message: 'Product category not eligible for this coupon',
        };
      }
    }
 
    // Check brand restrictions
    Iif (coupon.conditions.brands?.length > 0) {
      Iif (!coupon.conditions.brands.includes(product.brand)) {
        return {
          eligible: false,
          message: 'Product brand not eligible for this coupon',
        };
      }
    }
 
    return { eligible: true };
  }
 
  private async validateWithRetailer(
    coupon: CouponDocument,
    productId?: string,
    purchaseAmount?: number,
  ): Promise<CouponValidationResult> {
    try {
      const retailer = coupon.retailerId as any;
      
      // Different validation approaches based on retailer
      switch (retailer.name.toLowerCase()) {
        case 'namshi':
          return this.validateNamshiCoupon(coupon, productId, purchaseAmount);
        case 'noon':
          return this.validateNoonCoupon(coupon, productId, purchaseAmount);
        case 'amazon-uae':
          return this.validateAmazonCoupon(coupon, productId, purchaseAmount);
        default:
          // Generic validation - assume valid if in our database
          return { isValid: true };
      }
    } catch (error) {
      this.logger.error('Error validating with retailer', error);
      // Don't fail validation if retailer API is down
      return { isValid: true };
    }
  }
 
  private async validateNamshiCoupon(
    coupon: CouponDocument,
    productId?: string,
    purchaseAmount?: number,
  ): Promise<CouponValidationResult> {
    // Namshi-specific validation logic
    // This would integrate with Namshi's coupon validation API
    return { isValid: true };
  }
 
  private async validateNoonCoupon(
    coupon: CouponDocument,
    productId?: string,
    purchaseAmount?: number,
  ): Promise<CouponValidationResult> {
    // Noon-specific validation logic
    return { isValid: true };
  }
 
  private async validateAmazonCoupon(
    coupon: CouponDocument,
    productId?: string,
    purchaseAmount?: number,
  ): Promise<CouponValidationResult> {
    // Amazon-specific validation logic
    return { isValid: true };
  }
 
  private calculateDiscountAmount(coupon: CouponDocument, purchaseAmount: number): number {
    switch (coupon.discountType) {
      case 'percentage':
        const percentageDiscount = (purchaseAmount * coupon.discountValue) / 100;
        return coupon.maximumDiscount 
          ? Math.min(percentageDiscount, coupon.maximumDiscount)
          : percentageDiscount;
      
      case 'fixed':
        return coupon.discountValue;
      
      case 'bogo':
        // Buy one get one - assume 50% discount for simplicity
        return purchaseAmount * 0.5;
      
      case 'shipping':
        // Free shipping - return estimated shipping cost
        return 15; // Default shipping cost in AED
      
      default:
        return 0;
    }
  }
 
  private async generateAffiliateUrlWithCoupon(
    originalUrl: string,
    couponCode: string,
    retailerId: string,
  ): Promise<string> {
    try {
      const url = new URL(originalUrl);
      
      // Add coupon parameter based on retailer
      const retailer = await this.retailerModel.findById(retailerId);
      Iif (!retailer) return originalUrl;
 
      switch (retailer.name.toLowerCase()) {
        case 'namshi':
          url.searchParams.set('coupon', couponCode);
          break;
        case 'noon':
          url.searchParams.set('promo_code', couponCode);
          break;
        case 'amazon-uae':
          url.searchParams.set('couponCode', couponCode);
          break;
        default:
          url.searchParams.set('coupon', couponCode);
      }
 
      // Add SavePal tracking parameters
      url.searchParams.set('savepal_coupon', couponCode);
      url.searchParams.set('savepal_applied', 'true');
 
      return url.toString();
    } catch (error) {
      this.logger.error('Error generating affiliate URL with coupon', error);
      return originalUrl;
    }
  }
 
  async recordCouponUsage(
    couponCode: string,
    userId: string,
    productId: string,
    savingsAmount: number,
  ): Promise<void> {
    try {
      await this.couponModel.findOneAndUpdate(
        { code: couponCode },
        {
          $inc: { 'usageLimit.used': 1, 'performance.usageCount': 1, 'performance.savingsGenerated': savingsAmount },
          updatedAt: new Date(),
        },
      );
 
      // Record usage in analytics (would be implemented in analytics service)
      this.logger.log(`Coupon ${couponCode} used by user ${userId} for product ${productId}, saved ${savingsAmount}`);
    } catch (error) {
      this.logger.error('Error recording coupon usage', error);
    }
  }
 
  async getCouponPerformanceMetrics(couponId: string): Promise<{
    usageCount: number;
    savingsGenerated: number;
    conversionRate: number;
    averageSavings: number;
    topProducts: Array<{ productId: string; usageCount: number }>;
  }> {
    try {
      const coupon = await this.couponModel.findById(couponId);
      Iif (!coupon) {
        throw new Error('Coupon not found');
      }
 
      return {
        usageCount: coupon.performance.usageCount,
        savingsGenerated: coupon.performance.savingsGenerated,
        conversionRate: coupon.performance.conversionRate,
        averageSavings: coupon.performance.usageCount > 0 
          ? coupon.performance.savingsGenerated / coupon.performance.usageCount 
          : 0,
        topProducts: [], // Would be calculated from usage analytics
      };
    } catch (error) {
      this.logger.error(`Error getting performance metrics for coupon ${couponId}`, error);
      throw error;
    }
  }
}