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 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 16x 15x 15x 15x 15x 14x 14x 14x 14x 14x 16x 15x 15x 6x 6x 15x 14x 14x 14x 14x 14x 16x 1x 1x 1x 16x 1x 1x 1x 1x 1x 57x 57x 57x 57x 57x 57x 57x 56x 56x 56x 56x 57x 1x 1x 55x 55x 57x 57x 26x 26x 57x 57x 6x 6x 57x 57x 5x 5x 57x 57x 4x 4x 57x 57x 4x 4x 4x 57x 57x 6x 6x 57x 57x 57x 57x 3x 3x 3x 57x 57x 1x 57x 55x 55x 57x 1x 1x 1x 1x 2x 2x 1x 55x 55x 55x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 13x 14x 1x 1x 1x 1x 1x 12x 12x 14x 1x 1x 1x 1x 1x 11x 11x 14x 1x 1x 1x 1x 1x 10x 10x 14x 1x 1x 1x 1x 1x 9x 9x 9x 9x 14x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 14x 1x 1x 1x 1x 1x 6x 6x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 14x 1x 1x 1x 1x 1x 4x 4x 4x 14x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 14x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 14x 1x 1x 1x 1x 1x 14x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 8x 8x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 6x 6x 6x 6x 6x 6x 6x 6x 6x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 7x 7x 7x 7x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 6x 6x 6x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 3x 3x 1x 1x 1x 3x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 1x 1x 15x 15x 15x 15x 15x 15x 15x 14x 14x 15x 13x 13x 15x 1x 1x 1x 1x 12x 12x 15x 1x 1x 11x 11x 15x 1x 1x 10x 10x 15x 6x 6x 6x 6x 6x 15x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 10x 10x 10x 10x 6x 10x 10x 2x 2x 2x 10x 10x 1x 1x 1x 10x 10x 1x 10x 1x 1x 29x 29x 29x 29x 29x 29x 29x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 29x 29x 25x 25x 29x 1x 1x 6x 6x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 5x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 5x 6x 4x 4x 6x 1x 1x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 5x 8x 8x 1x 1x 1x 7x 7x 7x 4x 5x 3x 3x 3x 5x 6x 6x 6x 6x 6x 3x 3x 3x 5x 2x 2x 5x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 6x 6x 6x 3x 3x 3x 5x 1x 1x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 1x 1x 6x 6x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 37x 37x 37x 31x 37x 37x 3x 2x 2x 37x 37x 2x 1x 1x 37x 37x 37x 37x 37x 1x 37x 1x 1x 6x 3x 3x 3x 6x 1x 1x 2x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import type {
CartItem,
PromotionWithRelations,
ApplicablePromotion,
DiscountResult,
PromoCodeResult,
StackedPromotions,
ConditionContext } from "./types";
import {
isPromotionActive,
isPromotionUsageLimitReached,
calculateDiscount,
calculateCartTotal,
getCartItemCount,
evaluateAllConditions,
getApplicableTier,
sortByPriority,
normalizePromoCode,
formatDiscount } from "./utils";
const LOG_CATEGORY = "PROMOTION_ENGINE";
/**
* Core promotion calculation engine
*/
export class PromotionEngine {
/**
* Find all applicable promotions for a cart
*/
async findApplicablePromotions(
cart: CartItem[],
userId?: number
): Promise<ApplicablePromotion[]> {
if (cart.length === 0) return [];
try {
// Get all active promotions
const promotions = await this.getActivePromotions();
const applicablePromotions: ApplicablePromotion[] = [];
// Build condition context
const context = await this.buildConditionContext(cart, userId);
for (const promotion of promotions) {
const result = await this.evaluatePromotion(promotion, cart, context, userId);
if (result) {
applicablePromotions.push(result);
}
}
// Sort by priority
const sorted = sortByPriority(applicablePromotions.map((p) => ({ ...p, priority: p.promotion.priority })));
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return sorted.map(({ priority, ...rest }) => rest as ApplicablePromotion);
} catch (error) {
logger.error("Error finding applicable promotions", error instanceof Error ? error : new Error(String(error)), { category: LOG_CATEGORY });
return [];
}
}
/**
* Calculate discount for a specific promotion
*/
calculateDiscount(promotion: PromotionWithRelations, cart: CartItem[]): DiscountResult {
const result: DiscountResult = {
totalDiscount: 0,
itemDiscounts: new Map(),
freeItems: [],
freeShipping: false};
if (cart.length === 0) return result;
const cartTotal = calculateCartTotal(cart);
// Check minimum purchase
if (promotion.minimumPurchase && cartTotal < promotion.minimumPurchase) {
return result;
}
switch (promotion.type) {
case "PERCENTAGE_OFF":
case "FIXED_AMOUNT_OFF":
this.calculateStandardDiscount(promotion, cart, result);
break;
case "BOGO":
this.calculateBogoDiscount(promotion, cart, result);
break;
case "BUNDLE":
this.calculateBundleDiscount(promotion, cart, result);
break;
case "TIERED":
this.calculateTieredDiscount(promotion, cart, result);
break;
case "FREE_SHIPPING":
result.freeShipping = true;
result.savingsMessage = "Free shipping applied!";
break;
case "FREE_GIFT":
this.calculateFreeGiftDiscount(promotion, cart, result);
break;
case "FLASH_SALE":
case "SEASONAL":
case "FIRST_PURCHASE":
// These use standard discount calculation
this.calculateStandardDiscount(promotion, cart, result);
break;
default:
break;
}
// Apply maximum discount cap if set
if (promotion.maximumDiscount && result.totalDiscount > promotion.maximumDiscount) {
const ratio = promotion.maximumDiscount / result.totalDiscount;
result.totalDiscount = promotion.maximumDiscount;
// Scale down item discounts proportionally
for (const [productId, discount] of result.itemDiscounts) {
result.itemDiscounts.set(productId, Math.round(discount * ratio * 100) / 100);
}
}
return result;
}
/**
* Apply a promo code to cart
*/
async applyPromoCode(
code: string,
cart: CartItem[],
userId?: number
): Promise<PromoCodeResult> {
const normalizedCode = normalizePromoCode(code);
try {
// Find the promo code
const promoCode = await prisma.promoCode.findUnique({
where: { code: normalizedCode },
include: {
promotion: {
include: {
targetProducts: { include: { product: true } },
targetCategories: { include: { category: true } },
conditions: true,
bogoConfig: { include: { getProduct: true, getCategory: true } },
bundleConfig: { include: { products: { include: { product: true } } } },
freeGiftConfig: { include: { giftProduct: true } },
tieredConfig: { include: { tiers: true } },
flashSaleConfig: true}}}});
if (!promoCode) {
return {
success: false,
error: "Invalid promo code",
errorCode: "INVALID_CODE"};
}
// Check if code is active
if (!promoCode.isActive) {
return {
success: false,
error: "This promo code is no longer active",
errorCode: "INACTIVE"};
}
// Check code expiration
if (promoCode.expiresAt && new Date() > promoCode.expiresAt) {
return {
success: false,
error: "This promo code has expired",
errorCode: "EXPIRED"};
}
// Check code usage limit
if (promoCode.usageLimit && promoCode.usageCount >= promoCode.usageLimit) {
return {
success: false,
error: "This promo code has reached its usage limit",
errorCode: "USAGE_LIMIT_REACHED"};
}
const promotion = promoCode.promotion as PromotionWithRelations;
// Check if promotion is active
if (!isPromotionActive(promotion)) {
const now = new Date();
if (now < new Date(promotion.startDate)) {
return {
success: false,
error: "This promotion has not started yet",
errorCode: "NOT_STARTED"};
}
return {
success: false,
error: "This promotion has expired",
errorCode: "EXPIRED"};
}
// Check promotion usage limit
if (isPromotionUsageLimitReached(promotion)) {
return {
success: false,
error: "This promotion has reached its usage limit",
errorCode: "USAGE_LIMIT_REACHED"};
}
// Check per-customer limit
if (userId && promotion.perCustomerLimit) {
const userUsageCount = await prisma.promotionUsage.count({
where: {
promotionId: promotion.id,
userId}});
if (userUsageCount >= promotion.perCustomerLimit) {
return {
success: false,
error: "You have already used this promotion the maximum number of times",
errorCode: "ALREADY_USED"};
}
}
// Check minimum purchase
const cartTotal = calculateCartTotal(cart);
if (promotion.minimumPurchase && cartTotal < promotion.minimumPurchase) {
return {
success: false,
error: `Minimum purchase of $${promotion.minimumPurchase.toFixed(2)} required`,
errorCode: "MINIMUM_NOT_MET"};
}
// Check conditions
const context = await this.buildConditionContext(cart, userId);
if (promotion.conditions && promotion.conditions.length > 0) {
if (!evaluateAllConditions(promotion.conditions, context)) {
return {
success: false,
error: "This promo code cannot be applied to your current cart",
errorCode: "NOT_APPLICABLE"};
}
}
// Calculate discount
const discount = this.calculateDiscount(promotion, cart);
if (discount.totalDiscount === 0 && !discount.freeShipping && (!discount.freeItems || discount.freeItems.length === 0)) {
return {
success: false,
error: "This promo code cannot be applied to items in your cart",
errorCode: "NOT_APPLICABLE"};
}
return {
success: true,
promotion,
discount};
} catch (error) {
logger.error("Error applying promo code", error instanceof Error ? error : new Error(String(error)), { category: LOG_CATEGORY, code });
return {
success: false,
error: "An error occurred while applying the promo code"};
}
}
/**
* Validate promotion conditions
*/
async validateConditions(
promotion: PromotionWithRelations,
cart: CartItem[],
userId?: number
): Promise<boolean> {
if (!promotion.conditions || promotion.conditions.length === 0) {
return true;
}
const context = await this.buildConditionContext(cart, userId);
return evaluateAllConditions(promotion.conditions, context);
}
/**
* Get best non-stackable promotion
*/
getBestPromotion(promotions: ApplicablePromotion[]): ApplicablePromotion | null {
const nonStackable = promotions.filter((p) => !p.promotion.stackable);
if (nonStackable.length === 0) return null;
return nonStackable.reduce((best, current) =>
current.discountAmount > best.discountAmount ? current : best
);
}
/**
* Stack compatible promotions
*/
stackPromotions(promotions: ApplicablePromotion[], cart: CartItem[]): StackedPromotions {
const result: StackedPromotions = {
promotions: [],
totalDiscount: 0,
itemDiscounts: new Map(),
freeItems: [],
freeShipping: false,
savingsBreakdown: []};
if (promotions.length === 0) return result;
// Separate stackable and non-stackable
const stackable = promotions.filter((p) => p.promotion.stackable);
const nonStackable = promotions.filter((p) => !p.promotion.stackable);
// Get best non-stackable
const bestNonStackable = this.getBestPromotion(nonStackable);
// Combine best non-stackable with all stackable
const combined = bestNonStackable ? [bestNonStackable, ...stackable] : stackable;
// Sort by priority
const sortedWithPriority = sortByPriority(combined.map((p) => ({ ...p, priority: p.promotion.priority })));
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const sorted = sortedWithPriority.map(({ priority, ...rest }) => rest as ApplicablePromotion);
// Track which items have been discounted
const discountedItems = new Map<number, number>();
for (const applicable of sorted) {
// Recalculate discount with remaining cart value
const remainingCart = cart.map((item) => ({
...item,
price: item.price - (discountedItems.get(item.productId) || 0) / item.quantity}));
const discount = this.calculateDiscount(applicable.promotion, remainingCart);
if (discount.totalDiscount > 0 || discount.freeShipping || (discount.freeItems && discount.freeItems.length > 0)) {
result.promotions.push(applicable);
result.totalDiscount += discount.totalDiscount;
// Merge item discounts
for (const [productId, amount] of discount.itemDiscounts) {
const existing = result.itemDiscounts.get(productId) || 0;
result.itemDiscounts.set(productId, existing + amount);
discountedItems.set(productId, (discountedItems.get(productId) || 0) + amount);
}
// Merge free items
if (discount.freeItems) {
result.freeItems.push(...discount.freeItems);
}
// Set free shipping
if (discount.freeShipping) {
result.freeShipping = true;
}
// Add to savings breakdown
result.savingsBreakdown.push({
promotionId: applicable.promotion.id,
promotionName: applicable.promotion.name,
displayName: applicable.promotion.displayName || undefined,
discountAmount: discount.totalDiscount,
type: applicable.promotion.type});
}
}
return result;
}
/**
* Record promotion usage
*/
async recordUsage(
promotionId: number,
userId: number,
orderId: number,
discountAmount: number,
promoCodeId?: number
): Promise<void> {
try {
await prisma.$transaction(async (tx) => {
// Create usage record
await tx.promotionUsage.create({
data: {
promotionId,
userId,
orderId,
discountAmount,
promoCodeId}});
// Increment promotion usage count
await tx.promotion.update({
where: { id: promotionId },
data: { usageCount: { increment: 1 } }});
// Increment promo code usage count if applicable
if (promoCodeId) {
await tx.promoCode.update({
where: { id: promoCodeId },
data: { usageCount: { increment: 1 } }});
}
});
} catch (error) {
logger.error("Error recording promotion usage", error instanceof Error ? error : new Error(String(error)), { category: LOG_CATEGORY, promotionId, userId, orderId });
throw error;
}
}
// ============= Private Methods =============
private async getActivePromotions(): Promise<PromotionWithRelations[]> {
const now = new Date();
return prisma.promotion.findMany({
where: {
isActive: true,
startDate: { lte: now },
endDate: { gte: now }},
include: {
targetProducts: { include: { product: true } },
targetCategories: { include: { category: true } },
conditions: true,
bogoConfig: { include: { getProduct: true, getCategory: true } },
bundleConfig: { include: { products: { include: { product: true } } } },
freeGiftConfig: { include: { giftProduct: true } },
tieredConfig: { include: { tiers: true } },
flashSaleConfig: true},
orderBy: { priority: "desc" }}) as Promise<PromotionWithRelations[]>;
}
private async buildConditionContext(
cart: CartItem[],
userId?: number
): Promise<ConditionContext> {
const context: ConditionContext = {
cart,
cartTotal: calculateCartTotal(cart),
itemCount: getCartItemCount(cart),
dayOfWeek: new Date().getDay(),
timeOfDay: new Date().getHours()};
if (userId) {
context.userId = userId;
// Check if first purchase
const orderCount = await prisma.order.count({
where: { userId, status: { not: "CANCELLED" } }});
context.isFirstPurchase = orderCount === 0;
// Get customer segments (if any segment system is implemented)
// context.customerSegments = await this.getCustomerSegments(userId);
}
return context;
}
private async evaluatePromotion(
promotion: PromotionWithRelations,
cart: CartItem[],
context: ConditionContext,
userId?: number
): Promise<ApplicablePromotion | null> {
// Check if promotion is active
if (!isPromotionActive(promotion)) return null;
// Check usage limit
if (isPromotionUsageLimitReached(promotion)) return null;
// Check per-customer limit
if (userId && promotion.perCustomerLimit) {
const userUsageCount = await prisma.promotionUsage.count({
where: { promotionId: promotion.id, userId }});
if (userUsageCount >= promotion.perCustomerLimit) return null;
}
// Check minimum purchase
if (promotion.minimumPurchase && context.cartTotal < promotion.minimumPurchase) {
return null;
}
// Check conditions
if (promotion.conditions && promotion.conditions.length > 0) {
if (!evaluateAllConditions(promotion.conditions, context)) return null;
}
// Check if promotion applies to any items in cart
if (!this.promotionAppliesToCart(promotion, cart)) return null;
// Calculate discount
const discount = this.calculateDiscount(promotion, cart);
// Only return if there's actual benefit
if (discount.totalDiscount === 0 && !discount.freeShipping && (!discount.freeItems || discount.freeItems.length === 0)) {
return null;
}
const affectedItems = Array.from(discount.itemDiscounts.keys());
return {
promotion,
discountAmount: discount.totalDiscount,
affectedItems,
message: this.getPromotionMessage(promotion, discount),
isAutomatic: true, // All promotions from findApplicable are automatic
};
}
private promotionAppliesToCart(promotion: PromotionWithRelations, cart: CartItem[]): boolean {
switch (promotion.targetType) {
case "ALL_PRODUCTS":
case "CART_TOTAL":
case "SHIPPING":
return true;
case "SPECIFIC_PRODUCTS":
if (!promotion.targetProducts || promotion.targetProducts.length === 0) return false;
const targetProductIds = promotion.targetProducts.map((tp) => tp.productId);
return cart.some((item) => targetProductIds.includes(item.productId));
case "SPECIFIC_CATEGORIES":
if (!promotion.targetCategories || promotion.targetCategories.length === 0) return false;
const targetCategoryIds = promotion.targetCategories.map((tc) => tc.categoryId);
return cart.some((item) => targetCategoryIds.includes(item.categoryId));
default:
return false;
}
}
private calculateStandardDiscount(
promotion: PromotionWithRelations,
cart: CartItem[],
result: DiscountResult
): void {
const applicableItems = this.getApplicableItems(promotion, cart);
for (const item of applicableItems) {
const itemTotal = item.price * item.quantity;
const discount = calculateDiscount(
itemTotal,
promotion.discountType,
promotion.discountValue,
promotion.maximumDiscount
);
if (discount > 0) {
result.itemDiscounts.set(item.productId, discount);
result.totalDiscount += discount;
}
}
if (result.totalDiscount > 0) {
result.savingsMessage = `Save ${formatDiscount(promotion.discountType, promotion.discountValue)}`;
}
}
private calculateBogoDiscount(
promotion: PromotionWithRelations,
cart: CartItem[],
result: DiscountResult
): void {
const bogoConfig = promotion.bogoConfig;
if (!bogoConfig) return;
const { buyQuantity, getQuantity, discountPercent, getProductId } = bogoConfig;
const applicableItems = this.getApplicableItems(promotion, cart);
for (const item of applicableItems) {
// Calculate how many "sets" can be formed
const sets = Math.floor(item.quantity / (buyQuantity + getQuantity));
if (sets === 0) continue;
// Determine the "get" product price
let getPrice = item.price; // Default to same product
// Check if there's a specific get product with price info
const bogoWithProduct = bogoConfig as { getProduct?: { price?: number } };
if (getProductId && bogoWithProduct.getProduct) {
getPrice = bogoWithProduct.getProduct.price || item.price;
}
// Calculate discount
const freeItemsCount = sets * getQuantity;
const discount = (getPrice * freeItemsCount * discountPercent) / 100;
result.itemDiscounts.set(item.productId, discount);
result.totalDiscount += discount;
}
if (result.totalDiscount > 0) {
result.savingsMessage = `Buy ${buyQuantity} Get ${getQuantity} ${discountPercent === 100 ? "Free" : `${discountPercent}% Off`}`;
}
}
private calculateBundleDiscount(
promotion: PromotionWithRelations,
cart: CartItem[],
result: DiscountResult
): void {
const bundleConfig = promotion.bundleConfig;
if (!bundleConfig || !bundleConfig.products) return;
// Check if all bundle products are in cart with required quantities
const bundleProducts = bundleConfig.products;
let bundleSets = Infinity;
for (const bp of bundleProducts) {
const cartItem = cart.find((item) => item.productId === bp.productId);
if (!cartItem) {
bundleSets = 0;
break;
}
const sets = Math.floor(cartItem.quantity / bp.quantity);
bundleSets = Math.min(bundleSets, sets);
}
if (bundleSets === 0 || bundleSets === Infinity) return;
// Calculate original price of bundle
let originalBundlePrice = 0;
for (const bp of bundleProducts) {
const cartItem = cart.find((item) => item.productId === bp.productId);
if (cartItem) {
originalBundlePrice += cartItem.price * bp.quantity;
}
}
// Calculate discount
let discount = 0;
if (bundleConfig.bundlePrice) {
// Fixed bundle price
discount = (originalBundlePrice - bundleConfig.bundlePrice) * bundleSets;
} else {
// Percentage/fixed discount on bundle
discount = calculateDiscount(
originalBundlePrice * bundleSets,
promotion.discountType,
promotion.discountValue,
promotion.maximumDiscount
);
}
if (discount > 0) {
// Distribute discount across bundle items
for (const bp of bundleProducts) {
const itemShare = (bp.product.price * bp.quantity) / originalBundlePrice;
result.itemDiscounts.set(bp.productId, discount * itemShare);
}
result.totalDiscount = discount;
result.savingsMessage = `Bundle savings: $${discount.toFixed(2)}`;
}
}
private calculateTieredDiscount(
promotion: PromotionWithRelations,
cart: CartItem[],
result: DiscountResult
): void {
const tieredConfig = promotion.tieredConfig;
if (!tieredConfig || !tieredConfig.tiers) return;
const applicableItems = this.getApplicableItems(promotion, cart);
const totalQuantity = applicableItems.reduce((sum, item) => sum + item.quantity, 0);
const applicableTier = getApplicableTier(tieredConfig.tiers, totalQuantity);
if (!applicableTier) return;
// Apply tier discount to applicable items
for (const item of applicableItems) {
const itemTotal = item.price * item.quantity;
const discount = calculateDiscount(
itemTotal,
applicableTier.discountType,
applicableTier.discountValue,
promotion.maximumDiscount
);
if (discount > 0) {
result.itemDiscounts.set(item.productId, discount);
result.totalDiscount += discount;
}
}
if (result.totalDiscount > 0) {
result.savingsMessage = `Tier ${applicableTier.minQuantity}+ items: ${formatDiscount(applicableTier.discountType, applicableTier.discountValue)}`;
}
}
private calculateFreeGiftDiscount(
promotion: PromotionWithRelations,
cart: CartItem[],
result: DiscountResult
): void {
const freeGiftConfig = promotion.freeGiftConfig;
if (!freeGiftConfig || !freeGiftConfig.giftProduct) return;
const giftProduct = freeGiftConfig.giftProduct as { id: number; title: string; price: number };
result.freeItems = [
{
productId: giftProduct.id,
productTitle: giftProduct.title,
quantity: freeGiftConfig.giftQuantity,
originalPrice: giftProduct.price * freeGiftConfig.giftQuantity},
];
result.totalDiscount = giftProduct.price * freeGiftConfig.giftQuantity;
result.savingsMessage = `Free gift: ${giftProduct.title}`;
}
private getApplicableItems(promotion: PromotionWithRelations, cart: CartItem[]): CartItem[] {
switch (promotion.targetType) {
case "ALL_PRODUCTS":
case "CART_TOTAL":
return cart;
case "SPECIFIC_PRODUCTS":
if (!promotion.targetProducts) return [];
const targetProductIds = promotion.targetProducts.map((tp) => tp.productId);
return cart.filter((item) => targetProductIds.includes(item.productId));
case "SPECIFIC_CATEGORIES":
if (!promotion.targetCategories) return [];
const targetCategoryIds = promotion.targetCategories.map((tc) => tc.categoryId);
return cart.filter((item) => targetCategoryIds.includes(item.categoryId));
case "SHIPPING":
return []; // Shipping doesn't apply to items
default:
return [];
}
}
private getPromotionMessage(promotion: PromotionWithRelations, discount: DiscountResult): string {
if (promotion.displayName) {
return promotion.displayName;
}
if (discount.freeShipping) {
return "Free Shipping";
}
if (discount.freeItems && discount.freeItems.length > 0) {
return `Free ${discount.freeItems[0].productTitle}`;
}
return formatDiscount(promotion.discountType, promotion.discountValue);
}
}
// Export singleton instance
export const promotionEngine = new PromotionEngine();
|