@jsdev_ninja/core 0.12.6 → 0.12.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,215 @@
1
+ import { describe, it, expect, beforeEach } from "vitest";
2
+ import { DiscountEngine } from "../engine";
3
+ import { DiscountStrategyFactory } from "../factory";
4
+ import { BundleDiscountStrategy } from "../strategies/BundleStrategy";
5
+ import { TDiscount } from "../types";
6
+
7
+ describe("Simple Discount System Tests", () => {
8
+ beforeEach(() => {
9
+ DiscountStrategyFactory.clearStrategies();
10
+ DiscountStrategyFactory.registerStrategy("bundle", new BundleDiscountStrategy());
11
+ });
12
+
13
+ it("should calculate basic bundle discount correctly", () => {
14
+ const cart = [
15
+ {
16
+ amount: 2,
17
+ product: {
18
+ id: "product1",
19
+ price: 10,
20
+ },
21
+ },
22
+ {
23
+ amount: 1,
24
+ product: {
25
+ id: "product2",
26
+ price: 15,
27
+ },
28
+ },
29
+ ];
30
+
31
+ const discounts: TDiscount[] = [
32
+ {
33
+ type: "Discount",
34
+ storeId: "store1",
35
+ companyId: "company1",
36
+ id: "bundle1",
37
+ name: [{ lang: "he", value: "Buy 3 for $25" }],
38
+ active: true,
39
+ startDate: Date.now() - 1000,
40
+ endDate: Date.now() + 1000,
41
+ variant: {
42
+ variantType: "bundle",
43
+ productsId: ["product1", "product2"],
44
+ requiredQuantity: 3,
45
+ bundlePrice: 25,
46
+ },
47
+ conditions: {
48
+ stackable: false,
49
+ },
50
+ },
51
+ ];
52
+
53
+ const result = DiscountEngine.calculateDiscounts(cart, discounts);
54
+
55
+ expect(result.totalDiscount).toBe(10);
56
+ expect(result.appliedDiscounts).toHaveLength(1);
57
+ });
58
+
59
+ it("should not apply inactive discount", () => {
60
+ const cart = [
61
+ {
62
+ amount: 3,
63
+ product: {
64
+ id: "product1",
65
+ price: 10,
66
+ },
67
+ },
68
+ ];
69
+
70
+ const discounts: TDiscount[] = [
71
+ {
72
+ type: "Discount",
73
+ storeId: "store1",
74
+ companyId: "company1",
75
+ id: "bundle1",
76
+ name: [{ lang: "he", value: "Buy 3 for $25" }],
77
+ active: false, // Inactive
78
+ startDate: Date.now() - 1000,
79
+ endDate: Date.now() + 1000,
80
+ variant: {
81
+ variantType: "bundle",
82
+ productsId: ["product1"],
83
+ requiredQuantity: 3,
84
+ bundlePrice: 25,
85
+ },
86
+ conditions: {
87
+ stackable: false,
88
+ },
89
+ },
90
+ ];
91
+
92
+ const result = DiscountEngine.calculateDiscounts(cart, discounts);
93
+
94
+ expect(result.totalDiscount).toBe(0);
95
+ expect(result.appliedDiscounts).toHaveLength(0);
96
+ });
97
+
98
+ it("should not apply discount when not enough items", () => {
99
+ const cart = [
100
+ {
101
+ amount: 2, // Only 2 items, need 3
102
+ product: {
103
+ id: "product1",
104
+ price: 10,
105
+ },
106
+ },
107
+ ];
108
+
109
+ const discounts: TDiscount[] = [
110
+ {
111
+ type: "Discount",
112
+ storeId: "store1",
113
+ companyId: "company1",
114
+ id: "bundle1",
115
+ name: [{ lang: "he", value: "Buy 3 for $25" }],
116
+ active: true,
117
+ startDate: Date.now() - 1000,
118
+ endDate: Date.now() + 1000,
119
+ variant: {
120
+ variantType: "bundle",
121
+ productsId: ["product1"],
122
+ requiredQuantity: 3,
123
+ bundlePrice: 25,
124
+ },
125
+ conditions: {
126
+ stackable: false,
127
+ },
128
+ },
129
+ ];
130
+
131
+ const result = DiscountEngine.calculateDiscounts(cart, discounts);
132
+
133
+ expect(result.totalDiscount).toBe(0);
134
+ expect(result.appliedDiscounts).toHaveLength(0);
135
+ });
136
+
137
+ it("should handle Buy 2 Get 1 Free scenario", () => {
138
+ const cart = [
139
+ {
140
+ amount: 3, // Buy 3 items
141
+ product: {
142
+ id: "product1",
143
+ price: 10, // $10 each
144
+ },
145
+ },
146
+ ];
147
+
148
+ const bogoDiscount: TDiscount = {
149
+ type: "Discount",
150
+ storeId: "store1",
151
+ companyId: "company1",
152
+ id: "bogo",
153
+ name: [{ lang: "he", value: "Buy 2 Get 1 Free" }],
154
+ active: true,
155
+ startDate: Date.now() - 1000,
156
+ endDate: Date.now() + 1000,
157
+ variant: {
158
+ variantType: "bundle",
159
+ productsId: ["product1"],
160
+ requiredQuantity: 3, // Buy 2 + get 1 free = 3 items
161
+ bundlePrice: 20, // Price of 2 items (10 × 2)
162
+ },
163
+ conditions: {
164
+ stackable: false,
165
+ },
166
+ };
167
+
168
+ const result = DiscountEngine.calculateDiscounts(cart, [bogoDiscount]);
169
+
170
+ // Original: 3 × $10 = $30
171
+ // Bundle: 3 items for $20
172
+ // Discount: $10
173
+
174
+ expect(result.totalDiscount).toBe(10);
175
+ expect(result.appliedDiscounts).toHaveLength(1);
176
+ });
177
+
178
+ it("should handle empty cart", () => {
179
+ const cart: Array<{
180
+ amount: number;
181
+ product: {
182
+ id: string;
183
+ price: number;
184
+ };
185
+ }> = [];
186
+
187
+ const discounts: TDiscount[] = [
188
+ {
189
+ type: "Discount",
190
+ storeId: "store1",
191
+ companyId: "company1",
192
+ id: "bundle1",
193
+ name: [{ lang: "he", value: "Buy 3 for $25" }],
194
+ active: true,
195
+ startDate: Date.now() - 1000,
196
+ endDate: Date.now() + 1000,
197
+ variant: {
198
+ variantType: "bundle",
199
+ productsId: ["product1"],
200
+ requiredQuantity: 3,
201
+ bundlePrice: 25,
202
+ },
203
+ conditions: {
204
+ stackable: false,
205
+ },
206
+ },
207
+ ];
208
+
209
+ const result = DiscountEngine.calculateDiscounts(cart, discounts);
210
+
211
+ expect(result.totalDiscount).toBe(0);
212
+ expect(result.appliedDiscounts).toHaveLength(0);
213
+ expect(result.items).toHaveLength(0);
214
+ });
215
+ });
@@ -0,0 +1,69 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import {
3
+ formatCurrency,
4
+ formatCurrencyString,
5
+ ensureNonNegative,
6
+ calculatePercentageDiscount
7
+ } from "../utils";
8
+
9
+ describe("Discount Utils", () => {
10
+ describe("formatCurrency", () => {
11
+ it("should format numbers to 2 decimal places", () => {
12
+ expect(formatCurrency(10)).toBe(10.00);
13
+ expect(formatCurrency(10.123)).toBe(10.12);
14
+ expect(formatCurrency(10.125)).toBe(10.13); // Rounds up
15
+ expect(formatCurrency(10.124)).toBe(10.12); // Rounds down
16
+ expect(formatCurrency(0)).toBe(0.00);
17
+ });
18
+
19
+ it("should return a number type", () => {
20
+ const result = formatCurrency(10.123);
21
+ expect(typeof result).toBe("number");
22
+ });
23
+ });
24
+
25
+ describe("formatCurrencyString", () => {
26
+ it("should format numbers to 2 decimal places as string", () => {
27
+ expect(formatCurrencyString(10)).toBe("10.00");
28
+ expect(formatCurrencyString(10.123)).toBe("10.12");
29
+ expect(formatCurrencyString(10.125)).toBe("10.13");
30
+ expect(formatCurrencyString(0)).toBe("0.00");
31
+ });
32
+
33
+ it("should return a string type", () => {
34
+ const result = formatCurrencyString(10.123);
35
+ expect(typeof result).toBe("string");
36
+ });
37
+ });
38
+
39
+ describe("ensureNonNegative", () => {
40
+ it("should return 0 for negative values", () => {
41
+ expect(ensureNonNegative(-5)).toBe(0.00);
42
+ expect(ensureNonNegative(-0.01)).toBe(0.00);
43
+ });
44
+
45
+ it("should return formatted value for positive values", () => {
46
+ expect(ensureNonNegative(10.123)).toBe(10.12);
47
+ expect(ensureNonNegative(0)).toBe(0.00);
48
+ });
49
+ });
50
+
51
+ describe("calculatePercentageDiscount", () => {
52
+ it("should calculate percentage discount correctly", () => {
53
+ expect(calculatePercentageDiscount(100, 80)).toBe(20.00); // 20% discount
54
+ expect(calculatePercentageDiscount(50, 25)).toBe(50.00); // 50% discount
55
+ expect(calculatePercentageDiscount(100, 100)).toBe(0.00); // No discount
56
+ });
57
+
58
+ it("should handle edge cases", () => {
59
+ expect(calculatePercentageDiscount(0, 0)).toBe(0.00);
60
+ expect(calculatePercentageDiscount(100, 0)).toBe(100.00); // 100% discount
61
+ });
62
+
63
+ it("should return formatted number", () => {
64
+ const result = calculatePercentageDiscount(100, 90.5);
65
+ expect(typeof result).toBe("number");
66
+ expect(result).toBe(9.50); // 9.5% discount
67
+ });
68
+ });
69
+ });
@@ -0,0 +1,129 @@
1
+ import { TDiscount, AppliedDiscount, DiscountContext } from "./types";
2
+ import { DiscountStrategyFactory } from "./factory";
3
+
4
+ export class DiscountEngine {
5
+ static calculateDiscounts(
6
+ cart: Array<{
7
+ amount: number;
8
+ product: {
9
+ id: string;
10
+ price: number;
11
+ };
12
+ }>,
13
+ discounts: TDiscount[],
14
+ user?: Record<string, unknown>
15
+ ): {
16
+ items: Array<{
17
+ amount: number;
18
+ product: {
19
+ id: string;
20
+ price: number;
21
+ };
22
+ originalPrice: number;
23
+ finalPrice: number;
24
+ finalDiscount: number;
25
+ appliedDiscounts: string[];
26
+ }>;
27
+ totalDiscount: number;
28
+ appliedDiscounts: AppliedDiscount[];
29
+ } {
30
+ const context: DiscountContext = {
31
+ cart,
32
+ user,
33
+ appliedDiscounts: [],
34
+ };
35
+
36
+ // Filter active discounts
37
+ const activeDiscounts = this.filterActiveDiscounts(discounts);
38
+
39
+ // Apply discounts
40
+ const appliedDiscounts: AppliedDiscount[] = [];
41
+
42
+ for (const discount of activeDiscounts) {
43
+ const strategy = DiscountStrategyFactory.getStrategy(discount);
44
+ if (!strategy) continue;
45
+
46
+ // Check if discount can be applied
47
+ if (!strategy.canApply(discount, context)) continue;
48
+
49
+ // Check if discount is stackable
50
+ if (!discount.conditions?.stackable && appliedDiscounts.length > 0) continue;
51
+
52
+ // Calculate discount
53
+ const result = strategy.calculate(discount, context);
54
+ if (!result.applicable) continue;
55
+
56
+ // Apply discount
57
+ appliedDiscounts.push({
58
+ discountId: discount.id,
59
+ discountName: discount.name[0]?.value || "Discount",
60
+ discountAmount: Number(result.discountAmount.toFixed(2)),
61
+ affectedItems: result.affectedItems,
62
+ });
63
+
64
+ // Update context for next iteration
65
+ context.appliedDiscounts = appliedDiscounts;
66
+ }
67
+
68
+ // Calculate final prices
69
+ const items = this.calculateFinalPrices(cart, appliedDiscounts);
70
+
71
+ const totalDiscount = appliedDiscounts.reduce((sum, discount) =>
72
+ sum + discount.discountAmount, 0);
73
+
74
+ return {
75
+ items,
76
+ totalDiscount: Number(totalDiscount.toFixed(2)),
77
+ appliedDiscounts,
78
+ };
79
+ }
80
+
81
+ private static filterActiveDiscounts(discounts: TDiscount[]): TDiscount[] {
82
+ const now = Date.now();
83
+ return discounts.filter(discount =>
84
+ discount.active &&
85
+ discount.startDate <= now &&
86
+ discount.endDate >= now
87
+ );
88
+ }
89
+
90
+ private static calculateFinalPrices(
91
+ cart: DiscountContext["cart"],
92
+ appliedDiscounts: AppliedDiscount[]
93
+ ) {
94
+ return cart.map(item => {
95
+ const itemDiscounts = appliedDiscounts.filter(discount =>
96
+ discount.affectedItems.some(affected => affected.productId === item.product.id)
97
+ );
98
+
99
+ const totalItemDiscount = itemDiscounts.reduce((sum, discount) => {
100
+ const affectedItem = discount.affectedItems.find(affected =>
101
+ affected.productId === item.product.id);
102
+ return sum + (affectedItem?.discountAmount || 0);
103
+ }, 0);
104
+
105
+ const discountPerUnit = totalItemDiscount / item.amount;
106
+ const finalPrice = item.product.price - discountPerUnit;
107
+
108
+ return {
109
+ amount: item.amount,
110
+ product: item.product,
111
+ originalPrice: Number(item.product.price.toFixed(2)),
112
+ finalPrice: Number(Math.max(0, finalPrice).toFixed(2)),
113
+ finalDiscount: Number(totalItemDiscount.toFixed(2)),
114
+ appliedDiscounts: itemDiscounts.map(d => d.discountId),
115
+ };
116
+ });
117
+ }
118
+
119
+ static isDiscountActive(discount: TDiscount): boolean {
120
+ const now = Date.now();
121
+ return discount.active &&
122
+ discount.startDate <= now &&
123
+ discount.endDate >= now;
124
+ }
125
+
126
+ static getActiveDiscounts(discounts: TDiscount[]): TDiscount[] {
127
+ return this.filterActiveDiscounts(discounts);
128
+ }
129
+ }
@@ -0,0 +1,25 @@
1
+ import { TDiscount } from "./types";
2
+ import { DiscountStrategy } from "./strategy";
3
+ import { BundleDiscountStrategy } from "./strategies/BundleStrategy";
4
+
5
+ export class DiscountStrategyFactory {
6
+ private static strategies: Map<string, DiscountStrategy> = new Map([
7
+ ["bundle", new BundleDiscountStrategy()],
8
+ ]);
9
+
10
+ static getStrategy(discount: TDiscount): DiscountStrategy | null {
11
+ return this.strategies.get(discount.variant.variantType) || null;
12
+ }
13
+
14
+ static registerStrategy(type: string, strategy: DiscountStrategy): void {
15
+ this.strategies.set(type, strategy);
16
+ }
17
+
18
+ static getRegisteredTypes(): string[] {
19
+ return Array.from(this.strategies.keys());
20
+ }
21
+
22
+ static clearStrategies(): void {
23
+ this.strategies.clear();
24
+ }
25
+ }
@@ -0,0 +1,10 @@
1
+ export * from "./types";
2
+ export * from "./strategy";
3
+ export * from "./factory";
4
+ export * from "./engine";
5
+ export * from "./strategies/BundleStrategy";
6
+ export * from "./utils";
7
+
8
+ // Re-export the main discount schema for backward compatibility
9
+ export { DiscountSchema } from "./types";
10
+ export type { TDiscount } from "./types";
@@ -0,0 +1,123 @@
1
+ import { DiscountStrategy } from "../strategy";
2
+ import { TDiscount, DiscountResult, DiscountContext } from "../types";
3
+
4
+ export class BundleDiscountStrategy implements DiscountStrategy {
5
+ canApply(discount: TDiscount, context: DiscountContext): boolean {
6
+ if (discount.variant.variantType !== "bundle") return false;
7
+
8
+ // Check if discount is active
9
+ if (!this.isDiscountActive(discount)) return false;
10
+
11
+ const { productsId, requiredQuantity } = discount.variant;
12
+
13
+ // Check if cart has enough of the required products
14
+ const totalQuantity = this.getTotalQuantity(context.cart, productsId);
15
+
16
+ return totalQuantity >= requiredQuantity;
17
+ }
18
+
19
+ calculate(discount: TDiscount, context: DiscountContext): DiscountResult {
20
+ if (discount.variant.variantType !== "bundle") {
21
+ return { applicable: false, discountAmount: 0, affectedItems: [] };
22
+ }
23
+
24
+ const { productsId, requiredQuantity, bundlePrice } = discount.variant;
25
+
26
+ // Get applicable items (only the products in the bundle)
27
+ const applicableItems = context.cart.filter(item =>
28
+ productsId.includes(item.product.id));
29
+
30
+ const totalQuantity = this.getTotalQuantity(context.cart, productsId);
31
+ const bundleCount = Math.floor(totalQuantity / requiredQuantity);
32
+
33
+ if (bundleCount === 0) {
34
+ return { applicable: false, discountAmount: 0, affectedItems: [] };
35
+ }
36
+
37
+ // Calculate original price for bundled items
38
+ const originalPrice = this.calculateOriginalPrice(applicableItems);
39
+
40
+ // Calculate discounted price
41
+ const cartTotalQuantity = this.getTotalQuantity(context.cart, productsId);
42
+ const discountedPrice = this.calculateDiscountedPrice(
43
+ originalPrice,
44
+ bundlePrice,
45
+ bundleCount,
46
+ requiredQuantity,
47
+ cartTotalQuantity
48
+ );
49
+
50
+ const totalDiscount = originalPrice - discountedPrice;
51
+
52
+ // Distribute discount proportionally among items
53
+ const affectedItems = this.distributeDiscount(applicableItems, totalDiscount, originalPrice);
54
+
55
+ return {
56
+ applicable: true,
57
+ discountAmount: Number(totalDiscount.toFixed(2)),
58
+ affectedItems,
59
+ };
60
+ }
61
+
62
+ private isDiscountActive(discount: TDiscount): boolean {
63
+ const now = Date.now();
64
+ return discount.active &&
65
+ discount.startDate <= now &&
66
+ discount.endDate >= now;
67
+ }
68
+
69
+ private getTotalQuantity(cart: DiscountContext["cart"], productIds: string[]): number {
70
+ return cart
71
+ .filter(item => productIds.includes(item.product.id))
72
+ .reduce((sum, item) => sum + item.amount, 0);
73
+ }
74
+
75
+ private calculateOriginalPrice(items: DiscountContext["cart"]): number {
76
+ return items.reduce((sum, item) =>
77
+ sum + (item.product.price * item.amount), 0);
78
+ }
79
+
80
+ private calculateDiscountedPrice(
81
+ originalPrice: number,
82
+ bundlePrice: number,
83
+ bundleCount: number,
84
+ requiredQuantity: number,
85
+ totalQuantity: number
86
+ ): number {
87
+ // For bundle discounts, we pay the bundle price for each complete bundle
88
+ // and full price for any remaining items
89
+ const bundledItemsPrice = bundlePrice * bundleCount;
90
+
91
+ // For bundle discounts, we pay bundle price for complete bundles
92
+ // and full price for remaining items
93
+ // Since we're dealing with the total original price, we need to calculate
94
+ // how much of the original price represents the bundled items vs remaining items
95
+ const itemsInBundles = bundleCount * requiredQuantity;
96
+ const remainingItems = Math.max(0, totalQuantity - itemsInBundles);
97
+
98
+ // Calculate the proportion of original price that represents remaining items
99
+ const remainingItemsPrice = (remainingItems / totalQuantity) * originalPrice;
100
+
101
+ return bundledItemsPrice + remainingItemsPrice;
102
+ }
103
+
104
+ private distributeDiscount(
105
+ items: DiscountContext["cart"],
106
+ totalDiscount: number,
107
+ originalPrice: number
108
+ ): DiscountResult["affectedItems"] {
109
+ const discountRatio = totalDiscount / originalPrice;
110
+
111
+ return items.map(item => {
112
+ const itemDiscount = (item.product.price * item.amount) * discountRatio;
113
+
114
+ return {
115
+ productId: item.product.id,
116
+ quantity: item.amount,
117
+ originalPrice: Number(item.product.price.toFixed(2)),
118
+ discountedPrice: Number((item.product.price - (itemDiscount / item.amount)).toFixed(2)),
119
+ discountAmount: Number(itemDiscount.toFixed(2)),
120
+ };
121
+ });
122
+ }
123
+ }