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 | 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 28x 28x 26x 26x 26x 26x 26x 28x 28x 1x 1x 1x 1x 25x 25x 5x 5x 1x 1x 1x 1x 35x 35x 35x 35x 35x 35x 35x 5x 5x 30x 30x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 1x 1x 7x 7x 1x 1x 1x 1x 32x 32x 32x 32x 32x 32x 32x 29x 29x 3x 3x 1x 1x 1x 1x 83x 83x 83x 1x 1x 1x 1x 22x 22x 22x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 12x 12x 12x 12x 1x 1x 12x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 15x 15x 15x 15x 15x 3x 15x 15x 7x 15x 15x 15x 15x 1x 1x 1x 1x 1x 15x 15x 1x 1x 1x 1x 1x 15x 15x 1x 1x 2x 1x 15x 15x 15x 15x 15x 15x 2x 2x 2x 2x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 1x 1x 7x 7x 7x 7x 7x 6x 6x 8x 8x 6x 6x 1x 1x 1x 1x 30x 30x 27x 27x 3x 3x 1x 1x 1x 1x 3x 3x 3x 1x 1x 1x 1x 3x 3x 2x 2x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 15x 5x 5x 15x 2x 2x 2x 1x 1x 1x 1x 21x 21x 21x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 3x 3x 3x 3x 1x 1x 1x 1x 17x 17x 17x | import { customAlphabet } from "nanoid";
import type {
CartItem,
PromotionWithRelations,
ConditionContext,
ConditionRule,
ConditionType,
ConditionOperator,
GenerateCodesOptions,
GeneratedCode } from "./types";
import type { PromotionCondition, DiscountType } from "@prisma/client";
// Generate unique promo codes
const generateCode = customAlphabet("ABCDEFGHJKLMNPQRSTUVWXYZ23456789", 8);
/**
* Generate a batch of unique promo codes
*/
export function generatePromoCodes(options: GenerateCodesOptions): GeneratedCode[] {
const { promotionId, count, prefix = "", length = 8, usageLimit, expiresAt } = options;
const codes: GeneratedCode[] = [];
const usedCodes = new Set<string>();
for (let i = 0; i < count; i++) {
let code: string;
do {
const randomPart = customAlphabet("ABCDEFGHJKLMNPQRSTUVWXYZ23456789", length)();
code = prefix ? `${prefix}-${randomPart}` : randomPart;
} while (usedCodes.has(code));
usedCodes.add(code);
codes.push({
code,
promotionId,
usageLimit,
expiresAt});
}
return codes;
}
/**
* Generate a single unique promo code
*/
export function generateSingleCode(prefix?: string, length = 8): string {
const randomPart = generateCode().substring(0, length);
return prefix ? `${prefix}-${randomPart}` : randomPart;
}
/**
* Check if a promotion is currently active based on dates
*/
export function isPromotionActive(promotion: PromotionWithRelations): boolean {
if (!promotion.isActive) return false;
const now = new Date();
const startDate = new Date(promotion.startDate);
const endDate = new Date(promotion.endDate);
return now >= startDate && now <= endDate;
}
/**
* Check if a promotion has reached its usage limit
*/
export function isPromotionUsageLimitReached(promotion: PromotionWithRelations): boolean {
if (promotion.usageLimit === null) return false;
return promotion.usageCount >= promotion.usageLimit;
}
/**
* Calculate percentage discount
*/
export function calculatePercentageDiscount(
amount: number,
percentage: number,
maxDiscount?: number | null
): number {
const discount = (amount * percentage) / 100;
if (maxDiscount !== null && maxDiscount !== undefined && discount > maxDiscount) {
return maxDiscount;
}
return Math.round(discount * 100) / 100; // Round to 2 decimal places
}
/**
* Calculate fixed amount discount
*/
export function calculateFixedDiscount(
amount: number,
fixedAmount: number,
maxDiscount?: number | null
): number {
let discount = Math.min(amount, fixedAmount);
if (maxDiscount !== null && maxDiscount !== undefined && discount > maxDiscount) {
discount = maxDiscount;
}
return Math.round(discount * 100) / 100;
}
/**
* Calculate discount based on type
*/
export function calculateDiscount(
amount: number,
discountType: DiscountType,
discountValue: number,
maxDiscount?: number | null
): number {
if (discountType === "PERCENTAGE") {
return calculatePercentageDiscount(amount, discountValue, maxDiscount);
}
return calculateFixedDiscount(amount, discountValue, maxDiscount);
}
/**
* Calculate cart total from items
*/
export function calculateCartTotal(items: CartItem[]): number {
return items.reduce((total, item) => total + item.price * item.quantity, 0);
}
/**
* Get total item count in cart
*/
export function getCartItemCount(items: CartItem[]): number {
return items.reduce((count, item) => count + item.quantity, 0);
}
/**
* Check if cart contains a specific product
*/
export function cartContainsProduct(items: CartItem[], productId: number): boolean {
return items.some((item) => item.productId === productId);
}
/**
* Check if cart contains a product from a specific category
*/
export function cartContainsCategory(items: CartItem[], categoryId: number): boolean {
return items.some((item) => item.categoryId === categoryId);
}
/**
* Get items from cart that belong to specific category
*/
export function getItemsByCategory(items: CartItem[], categoryId: number): CartItem[] {
return items.filter((item) => item.categoryId === categoryId);
}
/**
* Get items from cart that match specific product IDs
*/
export function getItemsByProductIds(items: CartItem[], productIds: number[]): CartItem[] {
return items.filter((item) => productIds.includes(item.productId));
}
/**
* Parse condition value from JSON string
*/
export function parseConditionValue(value: string): string | number | number[] {
try {
return JSON.parse(value);
} catch {
return value;
}
}
/**
* Convert PromotionCondition to ConditionRule
*/
export function toConditionRule(condition: PromotionCondition): ConditionRule {
return {
conditionType: condition.conditionType as ConditionType,
operator: condition.operator as ConditionOperator,
value: parseConditionValue(condition.value)};
}
/**
* Evaluate a single condition against context
*/
export function evaluateCondition(rule: ConditionRule, context: ConditionContext): boolean {
const { conditionType, operator, value } = rule;
switch (conditionType) {
case "min_quantity":
return compareNumbers(context.itemCount, operator, value as number);
case "min_amount":
return compareNumbers(context.cartTotal, operator, value as number);
case "max_amount":
return compareNumbers(context.cartTotal, operator, value as number);
case "includes_product":
const productIds = Array.isArray(value) ? value : [value as number];
const hasProduct = productIds.some((id) =>
context.cart.some((item) => item.productId === id)
);
return operator === "in" ? hasProduct : !hasProduct;
case "includes_category":
const categoryIds = Array.isArray(value) ? value : [value as number];
const hasCategory = categoryIds.some((id) =>
context.cart.some((item) => item.categoryId === id)
);
return operator === "in" ? hasCategory : !hasCategory;
case "excludes_product":
const excludeProductIds = Array.isArray(value) ? value : [value as number];
return !excludeProductIds.some((id) =>
context.cart.some((item) => item.productId === id)
);
case "excludes_category":
const excludeCategoryIds = Array.isArray(value) ? value : [value as number];
return !excludeCategoryIds.some((id) =>
context.cart.some((item) => item.categoryId === id)
);
case "customer_segment":
if (!context.customerSegments) return false;
const segmentIds = Array.isArray(value) ? value : [value as number];
const inSegment = segmentIds.some((id) => context.customerSegments!.includes(id));
return operator === "in" ? inSegment : !inSegment;
case "first_purchase":
// Value comes from DB as string, number, or could be stored as boolean string
const strValue = String(value).toLowerCase();
const expectedFirstPurchase = strValue === "true" || strValue === "1";
return context.isFirstPurchase === expectedFirstPurchase;
case "day_of_week":
if (context.dayOfWeek === undefined) return true;
const days = Array.isArray(value) ? value : [value as number];
return days.includes(context.dayOfWeek);
case "time_of_day":
if (context.timeOfDay === undefined) return true;
const [start, end] = value as number[];
return context.timeOfDay >= start && context.timeOfDay <= end;
case "cart_item_count":
return compareNumbers(context.itemCount, operator, value as number);
default:
return true;
}
}
/**
* Compare numbers using operator
*/
function compareNumbers(a: number, operator: ConditionOperator, b: number): boolean {
switch (operator) {
case "equals":
return a === b;
case "not_equals":
return a !== b;
case "greater_than":
return a > b;
case "less_than":
return a < b;
case "greater_than_or_equal":
return a >= b;
case "less_than_or_equal":
return a <= b;
default:
return true;
}
}
/**
* Evaluate all conditions (AND logic)
*/
export function evaluateAllConditions(
conditions: PromotionCondition[],
context: ConditionContext
): boolean {
if (conditions.length === 0) return true;
return conditions.every((condition) => {
const rule = toConditionRule(condition);
return evaluateCondition(rule, context);
});
}
/**
* Format discount for display
*/
export function formatDiscount(discountType: DiscountType, discountValue: number): string {
if (discountType === "PERCENTAGE") {
return `${discountValue}% off`;
}
return `$${discountValue.toFixed(2)} off`;
}
/**
* Format price for display
*/
export function formatPrice(amount: number): string {
return `$${amount.toFixed(2)}`;
}
/**
* Calculate savings percentage
*/
export function calculateSavingsPercent(originalPrice: number, discountAmount: number): number {
if (originalPrice === 0) return 0;
return Math.round((discountAmount / originalPrice) * 100);
}
/**
* Get applicable tier from tiered promotion based on quantity
*/
export function getApplicableTier(
tiers: { minQuantity: number; discountType: DiscountType; discountValue: number }[],
quantity: number
): { minQuantity: number; discountType: DiscountType; discountValue: number } | null {
// Sort tiers by minQuantity descending
const sortedTiers = [...tiers].sort((a, b) => b.minQuantity - a.minQuantity);
// Find the highest tier that applies
for (const tier of sortedTiers) {
if (quantity >= tier.minQuantity) {
return tier;
}
}
return null;
}
/**
* Sort promotions by priority (higher first)
*/
export function sortByPriority<T extends { priority: number }>(promotions: T[]): T[] {
return [...promotions].sort((a, b) => b.priority - a.priority);
}
/**
* Filter stackable promotions
*/
export function filterStackable<T extends { stackable: boolean }>(promotions: T[]): T[] {
return promotions.filter((p) => p.stackable);
}
/**
* Get the best non-stackable promotion by discount amount
*/
export function getBestNonStackable<T extends { stackable: boolean; discountAmount?: number }>(
promotions: { promotion: T; discountAmount: number }[]
): { promotion: T; discountAmount: number } | 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
);
}
/**
* Check if today is within date range
*/
export function isWithinDateRange(startDate: Date, endDate: Date): boolean {
const now = new Date();
return now >= startDate && now <= endDate;
}
/**
* Calculate days until expiration
*/
export function daysUntilExpiration(endDate: Date): number {
const now = new Date();
const end = new Date(endDate);
const diff = end.getTime() - now.getTime();
return Math.ceil(diff / (1000 * 60 * 60 * 24));
}
/**
* Check if promotion is expiring soon (within N days)
*/
export function isExpiringSoon(endDate: Date, days = 3): boolean {
const remaining = daysUntilExpiration(endDate);
return remaining > 0 && remaining <= days;
}
/**
* Normalize promo code (uppercase, trim)
*/
export function normalizePromoCode(code: string): string {
return code.toUpperCase().trim();
}
|