@lyxa.ai/marketing 1.0.38 → 1.0.41

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.
Files changed (107) hide show
  1. package/dist/lib/index.d.ts +89 -9
  2. package/dist/lib/index.d.ts.map +1 -1
  3. package/dist/lib/modules/coupon/routers/coupon.router.d.ts +4 -0
  4. package/dist/lib/modules/coupon/routers/coupon.router.d.ts.map +1 -1
  5. package/dist/lib/modules/coupon/services/coupon.service.d.ts +3 -0
  6. package/dist/lib/modules/coupon/services/coupon.service.d.ts.map +1 -1
  7. package/dist/lib/modules/coupon/services/coupon.service.js +111 -6
  8. package/dist/lib/modules/coupon/services/coupon.service.js.map +1 -1
  9. package/dist/lib/modules/coupon/services/custom-coupon.service.d.ts +28 -2
  10. package/dist/lib/modules/coupon/services/custom-coupon.service.d.ts.map +1 -1
  11. package/dist/lib/modules/coupon/services/custom-coupon.service.js +13 -33
  12. package/dist/lib/modules/coupon/services/custom-coupon.service.js.map +1 -1
  13. package/dist/lib/modules/coupon/services/helper.service.d.ts +30 -2
  14. package/dist/lib/modules/coupon/services/helper.service.d.ts.map +1 -1
  15. package/dist/lib/modules/coupon/services/helper.service.js +112 -4
  16. package/dist/lib/modules/coupon/services/helper.service.js.map +1 -1
  17. package/dist/lib/modules/coupon/services/individual-store-coupon.service.d.ts +29 -3
  18. package/dist/lib/modules/coupon/services/individual-store-coupon.service.d.ts.map +1 -1
  19. package/dist/lib/modules/coupon/services/individual-store-coupon.service.js +10 -62
  20. package/dist/lib/modules/coupon/services/individual-store-coupon.service.js.map +1 -1
  21. package/dist/lib/modules/coupon/services/patterns/repository/CouponRepository.d.ts.map +1 -1
  22. package/dist/lib/modules/coupon/services/patterns/repository/CouponRepository.js +16 -6
  23. package/dist/lib/modules/coupon/services/patterns/repository/CouponRepository.js.map +1 -1
  24. package/dist/lib/modules/coupon/services/referral-code-coupon.service.d.ts +9 -0
  25. package/dist/lib/modules/coupon/services/referral-code-coupon.service.d.ts.map +1 -1
  26. package/dist/lib/modules/coupon/services/referral-code-coupon.service.js +96 -29
  27. package/dist/lib/modules/coupon/services/referral-code-coupon.service.js.map +1 -1
  28. package/dist/lib/modules/coupon/services/shops-categories-coupon.service.d.ts +29 -3
  29. package/dist/lib/modules/coupon/services/shops-categories-coupon.service.d.ts.map +1 -1
  30. package/dist/lib/modules/coupon/services/shops-categories-coupon.service.js +10 -63
  31. package/dist/lib/modules/coupon/services/shops-categories-coupon.service.js.map +1 -1
  32. package/dist/lib/modules/coupon/validations/coupon.validation.d.ts +13 -0
  33. package/dist/lib/modules/coupon/validations/coupon.validation.d.ts.map +1 -1
  34. package/dist/lib/modules/coupon/validations/coupon.validation.js +6 -14
  35. package/dist/lib/modules/coupon/validations/coupon.validation.js.map +1 -1
  36. package/dist/lib/modules/deal-setting/services/deal-setting.service.d.ts.map +1 -1
  37. package/dist/lib/modules/deal-setting/services/deal-setting.service.js +4 -4
  38. package/dist/lib/modules/deal-setting/services/deal-setting.service.js.map +1 -1
  39. package/dist/lib/modules/marketing/patterns/repository/MarketingMetricsRepository.d.ts +39 -0
  40. package/dist/lib/modules/marketing/patterns/repository/MarketingMetricsRepository.d.ts.map +1 -0
  41. package/dist/lib/modules/marketing/patterns/repository/MarketingMetricsRepository.js +539 -0
  42. package/dist/lib/modules/marketing/patterns/repository/MarketingMetricsRepository.js.map +1 -0
  43. package/dist/lib/modules/marketing/routers/marketing.router.d.ts +85 -9
  44. package/dist/lib/modules/marketing/routers/marketing.router.d.ts.map +1 -1
  45. package/dist/lib/modules/marketing/routers/marketing.router.js +26 -8
  46. package/dist/lib/modules/marketing/routers/marketing.router.js.map +1 -1
  47. package/dist/lib/modules/marketing/services/marketing.service.d.ts +2 -8
  48. package/dist/lib/modules/marketing/services/marketing.service.d.ts.map +1 -1
  49. package/dist/lib/modules/marketing/services/marketing.service.js +35 -354
  50. package/dist/lib/modules/marketing/services/marketing.service.js.map +1 -1
  51. package/dist/lib/modules/marketing/services/product-marketing.service.d.ts +1 -0
  52. package/dist/lib/modules/marketing/services/product-marketing.service.d.ts.map +1 -1
  53. package/dist/lib/modules/marketing/services/product-marketing.service.js +4 -0
  54. package/dist/lib/modules/marketing/services/product-marketing.service.js.map +1 -1
  55. package/dist/lib/modules/marketing/services/synchronize-product-marketing.service.d.ts.map +1 -1
  56. package/dist/lib/modules/marketing/services/synchronize-product-marketing.service.js +28 -7
  57. package/dist/lib/modules/marketing/services/synchronize-product-marketing.service.js.map +1 -1
  58. package/dist/lib/modules/marketing/validations/buy1-get1-marketing.validation.d.ts +12 -12
  59. package/dist/lib/modules/marketing/validations/discount-marketing.validation.d.ts +12 -12
  60. package/dist/lib/modules/marketing/validations/marketing.validation.d.ts +106 -1
  61. package/dist/lib/modules/marketing/validations/marketing.validation.d.ts.map +1 -1
  62. package/dist/lib/modules/marketing/validations/marketing.validation.js +31 -1
  63. package/dist/lib/modules/marketing/validations/marketing.validation.js.map +1 -1
  64. package/dist/lib/modules/punch-marketing-history/services/punch-marketing-history.service.d.ts.map +1 -1
  65. package/dist/lib/modules/punch-marketing-history/services/punch-marketing-history.service.js +19 -1
  66. package/dist/lib/modules/punch-marketing-history/services/punch-marketing-history.service.js.map +1 -1
  67. package/dist/lib/utility/utils.d.ts +3 -0
  68. package/dist/lib/utility/utils.d.ts.map +1 -0
  69. package/dist/lib/utility/utils.js +31 -0
  70. package/dist/lib/utility/utils.js.map +1 -0
  71. package/dist/types/index.d.ts +89 -9
  72. package/dist/types/index.d.ts.map +1 -1
  73. package/dist/types/modules/coupon/routers/coupon.router.d.ts +4 -0
  74. package/dist/types/modules/coupon/routers/coupon.router.d.ts.map +1 -1
  75. package/dist/types/modules/coupon/services/coupon.service.d.ts +3 -0
  76. package/dist/types/modules/coupon/services/coupon.service.d.ts.map +1 -1
  77. package/dist/types/modules/coupon/services/custom-coupon.service.d.ts +28 -2
  78. package/dist/types/modules/coupon/services/custom-coupon.service.d.ts.map +1 -1
  79. package/dist/types/modules/coupon/services/helper.service.d.ts +30 -2
  80. package/dist/types/modules/coupon/services/helper.service.d.ts.map +1 -1
  81. package/dist/types/modules/coupon/services/individual-store-coupon.service.d.ts +29 -3
  82. package/dist/types/modules/coupon/services/individual-store-coupon.service.d.ts.map +1 -1
  83. package/dist/types/modules/coupon/services/patterns/repository/CouponRepository.d.ts.map +1 -1
  84. package/dist/types/modules/coupon/services/referral-code-coupon.service.d.ts +57 -0
  85. package/dist/types/modules/coupon/services/referral-code-coupon.service.d.ts.map +1 -1
  86. package/dist/types/modules/coupon/services/shops-categories-coupon.service.d.ts +29 -3
  87. package/dist/types/modules/coupon/services/shops-categories-coupon.service.d.ts.map +1 -1
  88. package/dist/types/modules/coupon/validations/coupon.validation.d.ts +13 -0
  89. package/dist/types/modules/coupon/validations/coupon.validation.d.ts.map +1 -1
  90. package/dist/types/modules/deal-setting/services/deal-setting.service.d.ts.map +1 -1
  91. package/dist/types/modules/marketing/patterns/repository/MarketingMetricsRepository.d.ts +39 -0
  92. package/dist/types/modules/marketing/patterns/repository/MarketingMetricsRepository.d.ts.map +1 -0
  93. package/dist/types/modules/marketing/routers/marketing.router.d.ts +85 -9
  94. package/dist/types/modules/marketing/routers/marketing.router.d.ts.map +1 -1
  95. package/dist/types/modules/marketing/services/marketing.service.d.ts +2 -8
  96. package/dist/types/modules/marketing/services/marketing.service.d.ts.map +1 -1
  97. package/dist/types/modules/marketing/services/product-marketing.service.d.ts +1 -0
  98. package/dist/types/modules/marketing/services/product-marketing.service.d.ts.map +1 -1
  99. package/dist/types/modules/marketing/services/synchronize-product-marketing.service.d.ts.map +1 -1
  100. package/dist/types/modules/marketing/validations/buy1-get1-marketing.validation.d.ts +12 -12
  101. package/dist/types/modules/marketing/validations/discount-marketing.validation.d.ts +12 -12
  102. package/dist/types/modules/marketing/validations/marketing.validation.d.ts +106 -1
  103. package/dist/types/modules/marketing/validations/marketing.validation.d.ts.map +1 -1
  104. package/dist/types/modules/punch-marketing-history/services/punch-marketing-history.service.d.ts.map +1 -1
  105. package/dist/types/utility/utils.d.ts +15 -0
  106. package/dist/types/utility/utils.d.ts.map +1 -0
  107. package/package.json +2 -2
@@ -0,0 +1,539 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __metadata = (this && this.__metadata) || function (k, v) {
42
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.marketingMetricsRepository = exports.MarketingMetricsRepository = void 0;
46
+ const typedi_1 = __importStar(require("typedi"));
47
+ const dayjs_1 = require("@lyxa.ai/core/dist/utilities/dayjs");
48
+ const typegoose_1 = require("@typegoose/typegoose");
49
+ const models_1 = require("@lyxa.ai/core/dist/libraries/mongo/models");
50
+ const enum_1 = require("@lyxa.ai/core/dist/utilities/enum");
51
+ const product_marketing_service_1 = require("../../../marketing/services/product-marketing.service");
52
+ const enum_2 = require("@lyxa.ai/core/dist/utilities/enum");
53
+ const error_common_1 = require("@lyxa.ai/core/dist/utilities/error-common");
54
+ const time_1 = require("@lyxa.ai/core/dist/utilities/time");
55
+ const utils_1 = require("../../../../utility/utils");
56
+ let MarketingMetricsRepository = class MarketingMetricsRepository {
57
+ model;
58
+ orderModel;
59
+ constructor() {
60
+ this.model = models_1.MarketingModel;
61
+ this.orderModel = models_1.RegularOrderModel;
62
+ }
63
+ calculateMarketingSpendPerOrder(order) {
64
+ const spendMap = new Map();
65
+ const addSpend = (marketingId, amount) => {
66
+ if (!amount || amount <= 0)
67
+ return;
68
+ spendMap.set(marketingId, (spendMap.get(marketingId) ?? 0) + amount);
69
+ };
70
+ for (const lineItem of order.lineItems ?? []) {
71
+ for (const marketingId of lineItem.marketings ?? []) {
72
+ const snap = lineItem.calculationSnap ?? {};
73
+ addSpend(marketingId._id, (Number(snap.itemDiscountByCompany) || 0) +
74
+ (Number(snap.itemDiscountByShop) || 0) +
75
+ (Number(snap.b1g1DiscountByCompany) || 0) +
76
+ (Number(snap.b1g1DiscountByShop) || 0));
77
+ }
78
+ }
79
+ if (order.adjustedFinance?.freeDelivery) {
80
+ for (const marketingId of order.marketings ?? []) {
81
+ addSpend(marketingId._id, (order.adjustedFinance.freeDelivery.companyCut ?? 0) +
82
+ (order.adjustedFinance.freeDelivery.shopCut ?? 0));
83
+ }
84
+ }
85
+ if (order.adjustedFinance?.pricing?.punchMarketingDiscount) {
86
+ for (const marketingId of order.marketings ?? []) {
87
+ addSpend(marketingId._id, order.adjustedFinance.pricing.punchMarketingDiscount);
88
+ }
89
+ }
90
+ return spendMap;
91
+ }
92
+ async calculateMarketingSpent(marketingId, duration) {
93
+ const marketing = await this.model.findById(marketingId).lean();
94
+ if (!marketing) {
95
+ (0, error_common_1.notFoundError)('Marketing not found');
96
+ }
97
+ const calculators = {
98
+ [enum_2.MarketingType.FREE_DELIVERY]: () => this.calculateFreeDeliverySpent(marketingId, duration),
99
+ [enum_2.MarketingType.DISCOUNT]: () => this.calculateItemBasedSpent(marketingId, duration),
100
+ [enum_2.MarketingType.BUY1GET1]: () => this.calculateItemBasedSpent(marketingId, duration),
101
+ [enum_2.MarketingType.PUNCH_MARKETING]: () => this.calculatePunchMarketingSpent(marketingId, duration),
102
+ [enum_2.MarketingType.FEATURED]: function () {
103
+ return Promise.resolve(marketing.amount || 0);
104
+ },
105
+ };
106
+ const amount = calculators[marketing.marketingType] ? await calculators[marketing.marketingType]() : 0;
107
+ return {
108
+ amount,
109
+ marketingType: marketing.marketingType,
110
+ };
111
+ }
112
+ async calculateItemBasedSpent(marketingId, duration) {
113
+ const pipeline = [
114
+ this.buildBaseMatch(marketingId, duration),
115
+ {
116
+ $lookup: {
117
+ from: 'lineItems',
118
+ localField: 'cart',
119
+ foreignField: 'cart',
120
+ as: 'lineItems',
121
+ },
122
+ },
123
+ { $unwind: '$lineItems' },
124
+ {
125
+ $group: {
126
+ _id: null,
127
+ totalSpent: {
128
+ $sum: {
129
+ $add: [
130
+ { $ifNull: ['$lineItems.calculationSnap.itemDiscountByCompany', 0] },
131
+ { $ifNull: ['$lineItems.calculationSnap.itemDiscountByShop', 0] },
132
+ { $ifNull: ['$lineItems.calculationSnap.b1g1DiscountByCompany', 0] },
133
+ { $ifNull: ['$lineItems.calculationSnap.b1g1DiscountByShop', 0] },
134
+ ],
135
+ },
136
+ },
137
+ },
138
+ },
139
+ ];
140
+ return this.runAggregateAndGetTotal(pipeline, 'totalSpent');
141
+ }
142
+ async calculateFreeDeliverySpent(marketingId, duration) {
143
+ const pipeline = [
144
+ this.buildBaseMatch(marketingId, duration),
145
+ {
146
+ $group: {
147
+ _id: null,
148
+ totalSpent: {
149
+ $sum: {
150
+ $add: [
151
+ { $ifNull: ['$adjustedFinance.freeDelivery.companyCut', 0] },
152
+ { $ifNull: ['$adjustedFinance.freeDelivery.shopCut', 0] },
153
+ ],
154
+ },
155
+ },
156
+ },
157
+ },
158
+ ];
159
+ return this.runAggregateAndGetTotal(pipeline, 'totalSpent');
160
+ }
161
+ async calculatePunchMarketingSpent(marketingId, duration) {
162
+ const pipeline = [
163
+ this.buildBaseMatch(marketingId, duration),
164
+ {
165
+ $group: {
166
+ _id: null,
167
+ totalSpent: {
168
+ $sum: {
169
+ $ifNull: ['$adjustedFinance.pricing.punchMarketingDiscount', 0],
170
+ },
171
+ },
172
+ },
173
+ },
174
+ ];
175
+ return this.runAggregateAndGetTotal(pipeline, 'totalSpent');
176
+ }
177
+ buildBaseMatch(marketingId, duration) {
178
+ return {
179
+ $match: {
180
+ marketings: marketingId,
181
+ status: { $ne: enum_1.RegularOrderStatus.CANCELLED },
182
+ ...(duration && {
183
+ processedAt: {
184
+ $gte: duration.start,
185
+ $lte: duration.end,
186
+ },
187
+ }),
188
+ },
189
+ };
190
+ }
191
+ async runAggregateAndGetTotal(pipeline, field) {
192
+ const [result] = await this.orderModel.aggregate(pipeline);
193
+ return result?.[field] ?? 0;
194
+ }
195
+ async getMetrics(marketingId) {
196
+ const marketing = await this.model.findById(marketingId).lean();
197
+ if (!marketing) {
198
+ (0, error_common_1.notFoundError)('Marketing not found');
199
+ }
200
+ const currentDuration = { start: marketing.duration.start, end: (0, dayjs_1.dayjs)().toDate() };
201
+ const previousDuration = {
202
+ start: (0, dayjs_1.dayjs)(marketing.duration.start).subtract((0, dayjs_1.dayjs)().diff(marketing.duration.start)).toDate(),
203
+ end: marketing.duration.start,
204
+ };
205
+ let metrics = {};
206
+ if ([enum_2.MarketingType.DISCOUNT, enum_2.MarketingType.BUY1GET1].includes(marketing.marketingType)) {
207
+ metrics.numberOfItems = await this.getMarketingItemCount(marketingId);
208
+ }
209
+ metrics.orderIncreaseWithDiscount = await this.calculateOrderIncreaseWithDiscount(marketingId, marketing.shop._id, currentDuration, previousDuration);
210
+ metrics.customerIncreaseWithDiscount = await this.calculateCustomerIncreaseWithDiscount(marketingId, marketing.shop._id, currentDuration, previousDuration);
211
+ return metrics;
212
+ }
213
+ async getMarketingItemCount(marketingId) {
214
+ const result = await product_marketing_service_1.productMarketingService.countDocuments({ marketing: marketingId });
215
+ return result ?? 0;
216
+ }
217
+ async calculateOrderIncreaseWithDiscount(marketingId, shopId, currentDuration, previousDuration) {
218
+ const [currentOrders, previousOrders] = await Promise.all([
219
+ this.orderModel.countDocuments({
220
+ createdAt: {
221
+ $gte: currentDuration.start,
222
+ $lte: currentDuration.end,
223
+ },
224
+ marketings: marketingId,
225
+ shop: shopId,
226
+ }),
227
+ this.orderModel.countDocuments({
228
+ createdAt: {
229
+ $gte: previousDuration.start,
230
+ $lte: previousDuration.end,
231
+ },
232
+ shop: shopId,
233
+ }),
234
+ ]);
235
+ return this.calculateIncrease(currentOrders, previousOrders);
236
+ }
237
+ async calculateCustomerIncreaseWithDiscount(marketingId, shopId, currentDuration, previousDuration) {
238
+ const [currentNewCustomers, previousNewCustomers] = await Promise.all([
239
+ this.getNewCustomersForShop(shopId, currentDuration, { marketings: marketingId }),
240
+ this.getNewCustomersForShop(shopId, previousDuration),
241
+ ]);
242
+ return this.calculateIncrease(currentNewCustomers, previousNewCustomers);
243
+ }
244
+ calculateIncrease(current, previous) {
245
+ const count = current - previous;
246
+ const percentageIncrease = previous === 0 ? (current > 0 ? 100 : 0) : (count / previous) * 100;
247
+ return {
248
+ count,
249
+ percentageIncrease,
250
+ };
251
+ }
252
+ async getNewCustomersForShop(shopId, duration, extraMatch = {}) {
253
+ const customersInPeriod = await this.orderModel.distinct('user', {
254
+ createdAt: {
255
+ $gte: duration.start,
256
+ $lte: duration.end,
257
+ },
258
+ shop: shopId,
259
+ ...extraMatch,
260
+ });
261
+ if (customersInPeriod.length === 0) {
262
+ return 0;
263
+ }
264
+ const existingCustomers = await this.orderModel.distinct('user', {
265
+ shop: shopId,
266
+ createdAt: { $lt: duration.start },
267
+ user: { $in: customersInPeriod },
268
+ });
269
+ return customersInPeriod.length - existingCustomers.length;
270
+ }
271
+ async getOrdersGraph(data) {
272
+ const dateFormat = data.type === enum_1.GraphType.MONTHLY ? '%Y-%m' : '%Y-%m-%d';
273
+ const pipeline = [
274
+ this.buildBaseMatch(new typegoose_1.mongoose.Types.ObjectId(data.marketingId), {
275
+ start: data.startDate,
276
+ end: data.endDate,
277
+ }),
278
+ {
279
+ $project: {
280
+ date: {
281
+ $dateToString: {
282
+ format: dateFormat,
283
+ date: '$processedAt',
284
+ timezone: time_1.LyxaTimezone,
285
+ },
286
+ },
287
+ },
288
+ },
289
+ {
290
+ $group: {
291
+ _id: '$date',
292
+ orders: { $sum: 1 },
293
+ },
294
+ },
295
+ {
296
+ $sort: { _id: 1 },
297
+ },
298
+ {
299
+ $project: {
300
+ _id: 0,
301
+ date: '$_id',
302
+ orders: 1,
303
+ },
304
+ },
305
+ ];
306
+ const results = await this.orderModel.aggregate(pipeline).allowDiskUse(true).exec();
307
+ const graphData = (0, utils_1.fillMissingPeriods)(results, data.startDate, data.endDate, data.type, {
308
+ orders: 0,
309
+ });
310
+ return graphData;
311
+ }
312
+ async getCustomersGraph(data) {
313
+ const marketing = await this.model.findById(data.marketingId).select('shop').lean();
314
+ if (!marketing) {
315
+ (0, error_common_1.notFoundError)('Marketing not found');
316
+ }
317
+ const shopId = marketing.shop._id;
318
+ const oldUsers = await this.orderModel.distinct('user', {
319
+ shop: shopId,
320
+ status: enum_1.RegularOrderStatus.DELIVERED,
321
+ processedAt: { $lt: data.startDate },
322
+ });
323
+ const dateFormat = data.type === enum_1.GraphType.MONTHLY ? '%Y-%m' : '%Y-%m-%d';
324
+ const pipeline = [
325
+ {
326
+ $match: {
327
+ orderType: enum_1.OrderType.REGULAR,
328
+ status: enum_1.RegularOrderStatus.DELIVERED,
329
+ shop: shopId,
330
+ marketings: new typegoose_1.mongoose.Types.ObjectId(data.marketingId),
331
+ processedAt: { $gte: data.startDate, $lte: data.endDate },
332
+ user: { $nin: oldUsers },
333
+ },
334
+ },
335
+ { $sort: { processedAt: 1 } },
336
+ {
337
+ $group: {
338
+ _id: '$user',
339
+ firstOrderDate: { $first: '$processedAt' },
340
+ },
341
+ },
342
+ {
343
+ $project: {
344
+ date: {
345
+ $dateToString: {
346
+ format: dateFormat,
347
+ date: '$firstOrderDate',
348
+ timezone: time_1.LyxaTimezone,
349
+ },
350
+ },
351
+ },
352
+ },
353
+ {
354
+ $group: {
355
+ _id: '$date',
356
+ users: { $sum: 1 },
357
+ },
358
+ },
359
+ { $sort: { _id: 1 } },
360
+ {
361
+ $project: {
362
+ _id: 0,
363
+ date: '$_id',
364
+ users: 1,
365
+ },
366
+ },
367
+ ];
368
+ const results = await this.orderModel.aggregate(pipeline).allowDiskUse(true).exec();
369
+ return (0, utils_1.fillMissingPeriods)(results, data.startDate, data.endDate, data.type, {
370
+ users: 0,
371
+ });
372
+ }
373
+ async getAmountSpentGraph(data) {
374
+ const marketing = await this.model.findById(data.marketingId).lean();
375
+ if (!marketing) {
376
+ (0, error_common_1.notFoundError)('Marketing not found');
377
+ }
378
+ const marketingId = new typegoose_1.mongoose.Types.ObjectId(data.marketingId);
379
+ const dateFormat = data.type === enum_1.GraphType.MONTHLY ? '%Y-%m' : '%Y-%m-%d';
380
+ let pipeline = null;
381
+ if ([enum_2.MarketingType.DISCOUNT, enum_2.MarketingType.BUY1GET1].includes(marketing.marketingType)) {
382
+ pipeline = [
383
+ this.buildBaseMatch(marketingId, {
384
+ start: data.startDate,
385
+ end: data.endDate,
386
+ }),
387
+ {
388
+ $lookup: {
389
+ from: 'lineItems',
390
+ localField: 'cart',
391
+ foreignField: 'cart',
392
+ as: 'lineItems',
393
+ },
394
+ },
395
+ { $unwind: '$lineItems' },
396
+ {
397
+ $match: {
398
+ 'lineItems.marketings': marketingId,
399
+ },
400
+ },
401
+ {
402
+ $project: {
403
+ date: {
404
+ $dateToString: {
405
+ format: dateFormat,
406
+ date: '$processedAt',
407
+ timezone: time_1.LyxaTimezone,
408
+ },
409
+ },
410
+ amount: {
411
+ $add: [
412
+ {
413
+ $cond: [
414
+ marketing.isAppliedByCompany,
415
+ { $ifNull: ['$lineItems.calculationSnap.itemDiscountByCompany', 0] },
416
+ { $ifNull: ['$lineItems.calculationSnap.itemDiscountByShop', 0] },
417
+ ],
418
+ },
419
+ {
420
+ $cond: [
421
+ marketing.isAppliedByCompany,
422
+ { $ifNull: ['$lineItems.calculationSnap.b1g1DiscountByCompany', 0] },
423
+ { $ifNull: ['$lineItems.calculationSnap.b1g1DiscountByShop', 0] },
424
+ ],
425
+ },
426
+ ],
427
+ },
428
+ },
429
+ },
430
+ {
431
+ $group: {
432
+ _id: '$date',
433
+ amount: { $sum: '$amount' },
434
+ },
435
+ },
436
+ { $sort: { _id: 1 } },
437
+ {
438
+ $project: {
439
+ _id: 0,
440
+ date: '$_id',
441
+ amount: 1,
442
+ },
443
+ },
444
+ ];
445
+ }
446
+ else if (marketing.marketingType === enum_2.MarketingType.FREE_DELIVERY) {
447
+ pipeline = [
448
+ this.buildBaseMatch(marketingId, {
449
+ start: data.startDate,
450
+ end: data.endDate,
451
+ }),
452
+ {
453
+ $project: {
454
+ date: {
455
+ $dateToString: {
456
+ format: dateFormat,
457
+ date: '$processedAt',
458
+ timezone: time_1.LyxaTimezone,
459
+ },
460
+ },
461
+ amount: {
462
+ $cond: [
463
+ marketing.isAppliedByCompany,
464
+ { $ifNull: ['$adjustedFinance.freeDelivery.companyCut', 0] },
465
+ { $ifNull: ['$adjustedFinance.freeDelivery.shopCut', 0] },
466
+ ],
467
+ },
468
+ },
469
+ },
470
+ {
471
+ $group: {
472
+ _id: '$date',
473
+ amount: { $sum: '$amount' },
474
+ },
475
+ },
476
+ { $sort: { _id: 1 } },
477
+ {
478
+ $project: {
479
+ _id: 0,
480
+ date: '$_id',
481
+ amount: 1,
482
+ },
483
+ },
484
+ ];
485
+ }
486
+ else if (marketing.marketingType === enum_2.MarketingType.PUNCH_MARKETING) {
487
+ pipeline = [
488
+ this.buildBaseMatch(marketingId, {
489
+ start: data.startDate,
490
+ end: data.endDate,
491
+ }),
492
+ {
493
+ $project: {
494
+ date: {
495
+ $dateToString: {
496
+ format: dateFormat,
497
+ date: '$processedAt',
498
+ timezone: time_1.LyxaTimezone,
499
+ },
500
+ },
501
+ amount: {
502
+ $ifNull: ['$adjustedFinance.pricing.punchMarketingDiscount', 0],
503
+ },
504
+ },
505
+ },
506
+ {
507
+ $group: {
508
+ _id: '$date',
509
+ amount: { $sum: '$amount' },
510
+ },
511
+ },
512
+ { $sort: { _id: 1 } },
513
+ {
514
+ $project: {
515
+ _id: 0,
516
+ date: '$_id',
517
+ amount: 1,
518
+ },
519
+ },
520
+ ];
521
+ }
522
+ if (!pipeline) {
523
+ return (0, utils_1.fillMissingPeriods)([], data.startDate, data.endDate, data.type, {
524
+ amount: 0,
525
+ });
526
+ }
527
+ const results = await this.orderModel.aggregate(pipeline).allowDiskUse(true).exec();
528
+ return (0, utils_1.fillMissingPeriods)(results, data.startDate, data.endDate, data.type, {
529
+ amount: 0,
530
+ });
531
+ }
532
+ };
533
+ exports.MarketingMetricsRepository = MarketingMetricsRepository;
534
+ exports.MarketingMetricsRepository = MarketingMetricsRepository = __decorate([
535
+ (0, typedi_1.Service)(),
536
+ __metadata("design:paramtypes", [])
537
+ ], MarketingMetricsRepository);
538
+ exports.marketingMetricsRepository = typedi_1.default.get(MarketingMetricsRepository);
539
+ //# sourceMappingURL=MarketingMetricsRepository.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MarketingMetricsRepository.js","sourceRoot":"/","sources":["modules/marketing/patterns/repository/MarketingMetricsRepository.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAA4C;AAC5C,8DAA2D;AAC3D,oDAA+E;AAC/E,sEAOmD;AAQnD,4DAA6F;AAC7F,qGAAgG;AAChG,4DAAkE;AAClE,4EAA0E;AAE1E,4DAAiE;AACjE,0CAAoD;AAG7C,IAAM,0BAA0B,GAAhC,MAAM,0BAA0B;IAC9B,KAAK,CAAiD;IACtD,UAAU,CAA2D;IAE7E;QACC,IAAI,CAAC,KAAK,GAAG,uBAAgE,CAAC;QAC9E,IAAI,CAAC,UAAU,GAAG,0BAA6E,CAAC;IACjG,CAAC;IAEM,+BAA+B,CACrC,KAA2E;QAE3E,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAmC,CAAC;QAE5D,MAAM,QAAQ,GAAG,CAAC,WAAoC,EAAE,MAAc,EAAE,EAAE;YACzE,IAAI,CAAC,MAAM,IAAI,MAAM,IAAI,CAAC;gBAAE,OAAO;YACnC,QAAQ,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC;QACtE,CAAC,CAAC;QAKF,KAAK,MAAM,QAAQ,IAAI,KAAK,CAAC,SAAS,IAAI,EAAE,EAAE,CAAC;YAC9C,KAAK,MAAM,WAAW,IAAI,QAAQ,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC;gBACrD,MAAM,IAAI,GAAG,QAAQ,CAAC,eAAe,IAAI,EAAE,CAAC;gBAC5C,QAAQ,CACP,WAAW,CAAC,GAAG,EACf,CAAC,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;oBACxC,CAAC,MAAM,CAA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AAM,OAAO,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QAEpF,OAAO,IAAA,0BAAkB,EAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,EAAE;YAC3E,MAAM,EAAE,CAAC;SACT,CAAC,CAAC;IACJ,CAAC;CACD,CAAA;AAloBY,gEAA0B;qCAA1B,0BAA0B;IADtC,IAAA,gBAAO,GAAE;;GACG,0BAA0B,CAkoBtC;AAEY,QAAA,0BAA0B,GAAG,gBAAS,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC","sourcesContent":["import Container, { Service } from 'typedi';\nimport { dayjs } from '@lyxa.ai/core/dist/utilities/dayjs';\nimport { DocumentType, mongoose, ReturnModelType } from '@typegoose/typegoose';\nimport {\n\tFeaturedMarketing,\n\tLineItem,\n\tMarketingModel,\n\tMarketing as Model,\n\tRegularOrder,\n\tRegularOrderModel,\n} from '@lyxa.ai/core/dist/libraries/mongo/models';\nimport {\n\tIncreaseDuringDiscountDTO,\n\tMarketingGraphInputDTO,\n\tMarketingMetricsDTO,\n\tMarketingOrdersGraphOutputDTO,\n} from '@modules/marketing/validations';\nimport { SoftDeleteModel } from '@lyxa.ai/core/dist/libraries/mongo/plugins/soft-delete-plugin';\nimport { GraphType, OrderType, RegularOrderStatus } from '@lyxa.ai/core/dist/utilities/enum';\nimport { productMarketingService } from '@modules/marketing/services/product-marketing.service';\nimport { MarketingType } from '@lyxa.ai/core/dist/utilities/enum';\nimport { notFoundError } from '@lyxa.ai/core/dist/utilities/error-common';\nimport { Duration } from '@lyxa.ai/core/dist/libraries/mongo/models/shared/duration.model';\nimport { LyxaTimezone } from '@lyxa.ai/core/dist/utilities/time';\nimport { fillMissingPeriods } from '@utility/utils';\n\n@Service()\nexport class MarketingMetricsRepository {\n\tprivate model: typeof MarketingModel & SoftDeleteModel<Model>;\n\tprivate orderModel: typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\n\n\tconstructor() {\n\t\tthis.model = MarketingModel as typeof MarketingModel & SoftDeleteModel<Model>;\n\t\tthis.orderModel = RegularOrderModel as typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\n\t}\n\n\tpublic calculateMarketingSpendPerOrder(\n\t\torder: DocumentType<RegularOrder> & { lineItems: DocumentType<LineItem>[] }\n\t): Map<mongoose.Types.ObjectId, number> {\n\t\tconst spendMap = new Map<mongoose.Types.ObjectId, number>();\n\n\t\tconst addSpend = (marketingId: mongoose.Types.ObjectId, amount: number) => {\n\t\t\tif (!amount || amount <= 0) return;\n\t\t\tspendMap.set(marketingId, (spendMap.get(marketingId) ?? 0) + amount);\n\t\t};\n\n\t\t/**\n\t\t * ITEM-BASED (DISCOUNT / B1G1)\n\t\t */\n\t\tfor (const lineItem of order.lineItems ?? []) {\n\t\t\tfor (const marketingId of lineItem.marketings ?? []) {\n\t\t\t\tconst snap = lineItem.calculationSnap ?? {};\n\t\t\t\taddSpend(\n\t\t\t\t\tmarketingId._id,\n\t\t\t\t\t(Number(snap.itemDiscountByCompany) || 0) +\n\t\t\t\t\t\t(Number(snap.itemDiscountByShop) || 0) +\n\t\t\t\t\t\t(Number(snap.b1g1DiscountByCompany) || 0) +\n\t\t\t\t\t\t(Number(snap.b1g1DiscountByShop) || 0)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * FREE DELIVERY\n\t\t */\n\t\tif (order.adjustedFinance?.freeDelivery) {\n\t\t\tfor (const marketingId of order.marketings ?? []) {\n\t\t\t\taddSpend(\n\t\t\t\t\tmarketingId._id,\n\t\t\t\t\t(order.adjustedFinance.freeDelivery.companyCut ?? 0) +\n\t\t\t\t\t\t(order.adjustedFinance.freeDelivery.shopCut ?? 0)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * PUNCH MARKETING\n\t\t */\n\t\tif (order.adjustedFinance?.pricing?.punchMarketingDiscount) {\n\t\t\tfor (const marketingId of order.marketings ?? []) {\n\t\t\t\taddSpend(marketingId._id, order.adjustedFinance.pricing.punchMarketingDiscount);\n\t\t\t}\n\t\t}\n\n\t\treturn spendMap;\n\t}\n\n\tpublic async calculateMarketingSpent(\n\t\tmarketingId: mongoose.Types.ObjectId,\n\t\tduration?: Duration\n\t): Promise<{ amount: number; marketingType: MarketingType }> {\n\t\tconst marketing = await this.model.findById(marketingId).lean();\n\n\t\tif (!marketing) {\n\t\t\tnotFoundError('Marketing not found');\n\t\t}\n\n\t\tconst calculators: Record<MarketingType, () => Promise<number>> = {\n\t\t\t[MarketingType.FREE_DELIVERY]: () => this.calculateFreeDeliverySpent(marketingId, duration),\n\n\t\t\t[MarketingType.DISCOUNT]: () => this.calculateItemBasedSpent(marketingId, duration),\n\n\t\t\t[MarketingType.BUY1GET1]: () => this.calculateItemBasedSpent(marketingId, duration),\n\n\t\t\t[MarketingType.PUNCH_MARKETING]: () => this.calculatePunchMarketingSpent(marketingId, duration),\n\t\t\t[MarketingType.FEATURED]: function (): Promise<number> {\n\t\t\t\treturn Promise.resolve((marketing as DocumentType<FeaturedMarketing>).amount || 0);\n\t\t\t},\n\t\t};\n\n\t\tconst amount = calculators[marketing.marketingType] ? await calculators[marketing.marketingType]() : 0;\n\n\t\treturn {\n\t\t\tamount,\n\t\t\tmarketingType: marketing.marketingType,\n\t\t};\n\t}\n\n\tprivate async calculateItemBasedSpent(\n\t\tmarketingId: mongoose.Types.ObjectId,\n\t\tduration?: Duration\n\t): Promise<number> {\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\tthis.buildBaseMatch(marketingId, duration),\n\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'lineItems',\n\t\t\t\t\tlocalField: 'cart',\n\t\t\t\t\tforeignField: 'cart',\n\t\t\t\t\tas: 'lineItems',\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ $unwind: '$lineItems' },\n\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: null,\n\t\t\t\t\ttotalSpent: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$add: [\n\t\t\t\t\t\t\t\t{ $ifNull: ['$lineItems.calculationSnap.itemDiscountByCompany', 0] },\n\t\t\t\t\t\t\t\t{ $ifNull: ['$lineItems.calculationSnap.itemDiscountByShop', 0] },\n\t\t\t\t\t\t\t\t{ $ifNull: ['$lineItems.calculationSnap.b1g1DiscountByCompany', 0] },\n\t\t\t\t\t\t\t\t{ $ifNull: ['$lineItems.calculationSnap.b1g1DiscountByShop', 0] },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\n\t\treturn this.runAggregateAndGetTotal(pipeline, 'totalSpent');\n\t}\n\n\tprivate async calculateFreeDeliverySpent(\n\t\tmarketingId: mongoose.Types.ObjectId,\n\t\tduration?: Duration\n\t): Promise<number> {\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\tthis.buildBaseMatch(marketingId, duration),\n\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: null,\n\t\t\t\t\ttotalSpent: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$add: [\n\t\t\t\t\t\t\t\t{ $ifNull: ['$adjustedFinance.freeDelivery.companyCut', 0] },\n\t\t\t\t\t\t\t\t{ $ifNull: ['$adjustedFinance.freeDelivery.shopCut', 0] },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\n\t\treturn this.runAggregateAndGetTotal(pipeline, 'totalSpent');\n\t}\n\n\tprivate async calculatePunchMarketingSpent(\n\t\tmarketingId: mongoose.Types.ObjectId,\n\t\tduration?: Duration\n\t): Promise<number> {\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\tthis.buildBaseMatch(marketingId, duration),\n\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: null,\n\t\t\t\t\ttotalSpent: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$ifNull: ['$adjustedFinance.pricing.punchMarketingDiscount', 0],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\n\t\treturn this.runAggregateAndGetTotal(pipeline, 'totalSpent');\n\t}\n\n\tprivate buildBaseMatch(\n\t\tmarketingId: mongoose.Types.ObjectId,\n\t\tduration?: Duration\n\t): mongoose.PipelineStage.Match {\n\t\treturn {\n\t\t\t$match: {\n\t\t\t\tmarketings: marketingId,\n\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t...(duration && {\n\t\t\t\t\tprocessedAt: {\n\t\t\t\t\t\t$gte: duration.start,\n\t\t\t\t\t\t$lte: duration.end,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate async runAggregateAndGetTotal(pipeline: mongoose.PipelineStage[], field: string): Promise<number> {\n\t\tconst [result] = await this.orderModel.aggregate(pipeline);\n\t\treturn result?.[field] ?? 0;\n\t}\n\n\tpublic async getMetrics(marketingId: mongoose.Types.ObjectId): Promise<MarketingMetricsDTO> {\n\t\tconst marketing = await this.model.findById(marketingId).lean();\n\n\t\tif (!marketing) {\n\t\t\tnotFoundError('Marketing not found');\n\t\t}\n\n\t\t//TODO: fix current end and previous start\n\n\t\tconst currentDuration = { start: marketing.duration.start, end: dayjs().toDate() };\n\t\tconst previousDuration = {\n\t\t\tstart: dayjs(marketing.duration.start).subtract(dayjs().diff(marketing.duration.start)).toDate(),\n\t\t\tend: marketing.duration.start,\n\t\t};\n\n\t\tlet metrics: MarketingMetricsDTO = {};\n\n\t\tif ([MarketingType.DISCOUNT, MarketingType.BUY1GET1].includes(marketing.marketingType)) {\n\t\t\tmetrics.numberOfItems = await this.getMarketingItemCount(marketingId);\n\t\t}\n\n\t\tmetrics.orderIncreaseWithDiscount = await this.calculateOrderIncreaseWithDiscount(\n\t\t\tmarketingId,\n\t\t\tmarketing.shop._id,\n\t\t\tcurrentDuration,\n\t\t\tpreviousDuration\n\t\t);\n\t\tmetrics.customerIncreaseWithDiscount = await this.calculateCustomerIncreaseWithDiscount(\n\t\t\tmarketingId,\n\t\t\tmarketing.shop._id,\n\t\t\tcurrentDuration,\n\t\t\tpreviousDuration\n\t\t);\n\n\t\treturn metrics;\n\t}\n\n\tprivate async getMarketingItemCount(marketingId: mongoose.Types.ObjectId): Promise<number> {\n\t\tconst result = await productMarketingService.countDocuments({ marketing: marketingId });\n\t\treturn result ?? 0;\n\t}\n\n\tprivate async calculateOrderIncreaseWithDiscount(\n\t\tmarketingId: mongoose.Types.ObjectId,\n\t\tshopId: mongoose.Types.ObjectId,\n\t\tcurrentDuration: Duration,\n\t\tpreviousDuration: Duration\n\t): Promise<IncreaseDuringDiscountDTO> {\n\t\tconst [currentOrders, previousOrders] = await Promise.all([\n\t\t\tthis.orderModel.countDocuments({\n\t\t\t\tcreatedAt: {\n\t\t\t\t\t$gte: currentDuration.start,\n\t\t\t\t\t$lte: currentDuration.end,\n\t\t\t\t},\n\t\t\t\tmarketings: marketingId, // marketing must be applied\n\t\t\t\tshop: shopId,\n\t\t\t}),\n\t\t\tthis.orderModel.countDocuments({\n\t\t\t\tcreatedAt: {\n\t\t\t\t\t$gte: previousDuration.start,\n\t\t\t\t\t$lte: previousDuration.end,\n\t\t\t\t},\n\t\t\t\tshop: shopId,\n\t\t\t}),\n\t\t]);\n\n\t\treturn this.calculateIncrease(currentOrders, previousOrders);\n\t}\n\n\tprivate async calculateCustomerIncreaseWithDiscount(\n\t\tmarketingId: mongoose.Types.ObjectId,\n\t\tshopId: mongoose.Types.ObjectId,\n\t\tcurrentDuration: Duration,\n\t\tpreviousDuration: Duration\n\t): Promise<IncreaseDuringDiscountDTO> {\n\t\tconst [currentNewCustomers, previousNewCustomers] = await Promise.all([\n\t\t\tthis.getNewCustomersForShop(shopId, currentDuration, { marketings: marketingId }),\n\t\t\tthis.getNewCustomersForShop(shopId, previousDuration),\n\t\t]);\n\n\t\treturn this.calculateIncrease(currentNewCustomers, previousNewCustomers);\n\t}\n\n\tprivate calculateIncrease(current: number, previous: number): IncreaseDuringDiscountDTO {\n\t\tconst count = current - previous;\n\n\t\tconst percentageIncrease = previous === 0 ? (current > 0 ? 100 : 0) : (count / previous) * 100;\n\n\t\treturn {\n\t\t\tcount,\n\t\t\tpercentageIncrease,\n\t\t};\n\t}\n\n\tprivate async getNewCustomersForShop(\n\t\tshopId: mongoose.Types.ObjectId,\n\t\tduration: Duration,\n\t\textraMatch: Record<string, any> = {}\n\t): Promise<number> {\n\t\t// Customers who ordered during the period\n\t\tconst customersInPeriod = await this.orderModel.distinct('user', {\n\t\t\tcreatedAt: {\n\t\t\t\t$gte: duration.start,\n\t\t\t\t$lte: duration.end,\n\t\t\t},\n\t\t\tshop: shopId,\n\t\t\t...extraMatch,\n\t\t});\n\n\t\tif (customersInPeriod.length === 0) {\n\t\t\treturn 0;\n\t\t}\n\n\t\t// Customers who had ordered from this shop BEFORE the period\n\t\tconst existingCustomers = await this.orderModel.distinct('user', {\n\t\t\tshop: shopId,\n\t\t\tcreatedAt: { $lt: duration.start },\n\t\t\tuser: { $in: customersInPeriod },\n\t\t});\n\n\t\t// New customers = in period − existing\n\t\treturn customersInPeriod.length - existingCustomers.length;\n\t}\n\n\tpublic async getOrdersGraph(data: MarketingGraphInputDTO): Promise<MarketingOrdersGraphOutputDTO> {\n\t\tconst dateFormat = data.type === GraphType.MONTHLY ? '%Y-%m' : '%Y-%m-%d';\n\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\t// Filter only delivered orders within the given date range\n\t\t\tthis.buildBaseMatch(new mongoose.Types.ObjectId(data.marketingId), {\n\t\t\t\tstart: data.startDate,\n\t\t\t\tend: data.endDate,\n\t\t\t}),\n\n\t\t\t// Extract formatted date from 'processedAt' for grouping\n\t\t\t{\n\t\t\t\t$project: {\n\t\t\t\t\tdate: {\n\t\t\t\t\t\t$dateToString: {\n\t\t\t\t\t\t\tformat: dateFormat,\n\t\t\t\t\t\t\tdate: '$processedAt',\n\t\t\t\t\t\t\ttimezone: LyxaTimezone,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Group by formatted date and count orders\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: '$date',\n\t\t\t\t\torders: { $sum: 1 },\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Sort results chronologically\n\t\t\t{\n\t\t\t\t$sort: { _id: 1 },\n\t\t\t},\n\n\t\t\t// Format the response to match output DTO structure\n\t\t\t{\n\t\t\t\t$project: {\n\t\t\t\t\t_id: 0,\n\t\t\t\t\tdate: '$_id',\n\t\t\t\t\torders: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\n\t\t// Execute aggregation pipeline\n\t\tconst results = await this.orderModel.aggregate(pipeline).allowDiskUse(true).exec();\n\n\t\tconst graphData = fillMissingPeriods(results, data.startDate, data.endDate, data.type, {\n\t\t\torders: 0,\n\t\t});\n\n\t\treturn graphData;\n\t}\n\n\tpublic async getCustomersGraph(data: MarketingGraphInputDTO): Promise<{ date: string; users: number }[]> {\n\t\t// 1️⃣ Get shopId from marketing\n\t\tconst marketing = await this.model.findById(data.marketingId).select('shop').lean();\n\n\t\tif (!marketing) {\n\t\t\tnotFoundError('Marketing not found');\n\t\t}\n\n\t\tconst shopId = marketing.shop._id;\n\n\t\t// 2️⃣ Fetch users who ordered from this shop BEFORE the start date\n\t\tconst oldUsers = await this.orderModel.distinct('user', {\n\t\t\tshop: shopId,\n\t\t\tstatus: RegularOrderStatus.DELIVERED,\n\t\t\tprocessedAt: { $lt: data.startDate },\n\t\t});\n\n\t\tconst dateFormat = data.type === GraphType.MONTHLY ? '%Y-%m' : '%Y-%m-%d';\n\n\t\t// 3️⃣ Aggregation pipeline\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\t// Orders during the period with this marketing\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\torderType: OrderType.REGULAR,\n\t\t\t\t\tstatus: RegularOrderStatus.DELIVERED,\n\t\t\t\t\tshop: shopId,\n\t\t\t\t\tmarketings: new mongoose.Types.ObjectId(data.marketingId),\n\t\t\t\t\tprocessedAt: { $gte: data.startDate, $lte: data.endDate },\n\t\t\t\t\tuser: { $nin: oldUsers }, // 🚫 exclude old users\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Sort so earliest order per user comes first\n\t\t\t{ $sort: { processedAt: 1 } },\n\n\t\t\t// First order per user (new users only)\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: '$user',\n\t\t\t\t\tfirstOrderDate: { $first: '$processedAt' },\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Format date\n\t\t\t{\n\t\t\t\t$project: {\n\t\t\t\t\tdate: {\n\t\t\t\t\t\t$dateToString: {\n\t\t\t\t\t\t\tformat: dateFormat,\n\t\t\t\t\t\t\tdate: '$firstOrderDate',\n\t\t\t\t\t\t\ttimezone: LyxaTimezone,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Group by date\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: '$date',\n\t\t\t\t\tusers: { $sum: 1 },\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Sort chronologically\n\t\t\t{ $sort: { _id: 1 } },\n\n\t\t\t// Shape response\n\t\t\t{\n\t\t\t\t$project: {\n\t\t\t\t\t_id: 0,\n\t\t\t\t\tdate: '$_id',\n\t\t\t\t\tusers: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\n\t\tconst results = await this.orderModel.aggregate(pipeline).allowDiskUse(true).exec();\n\n\t\t// 4️⃣ Fill missing periods\n\t\treturn fillMissingPeriods(results, data.startDate, data.endDate, data.type, {\n\t\t\tusers: 0,\n\t\t});\n\t}\n\n\tpublic async getAmountSpentGraph(\n\t\tdata: MarketingGraphInputDTO\n\t): Promise<{ date: string; amount: number }[]> {\n\t\tconst marketing = await this.model.findById(data.marketingId).lean();\n\n\t\tif (!marketing) {\n\t\t\tnotFoundError('Marketing not found');\n\t\t}\n\n\t\tconst marketingId = new mongoose.Types.ObjectId(data.marketingId);\n\t\tconst dateFormat = data.type === GraphType.MONTHLY ? '%Y-%m' : '%Y-%m-%d';\n\n\t\tlet pipeline: mongoose.PipelineStage[] | null = null;\n\n\t\t/**\n\t\t * ITEM-BASED (DISCOUNT / BUY1GET1)\n\t\t */\n\t\tif ([MarketingType.DISCOUNT, MarketingType.BUY1GET1].includes(marketing.marketingType)) {\n\t\t\tpipeline = [\n\t\t\t\tthis.buildBaseMatch(marketingId, {\n\t\t\t\t\tstart: data.startDate,\n\t\t\t\t\tend: data.endDate,\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\t$lookup: {\n\t\t\t\t\t\tfrom: 'lineItems',\n\t\t\t\t\t\tlocalField: 'cart',\n\t\t\t\t\t\tforeignField: 'cart',\n\t\t\t\t\t\tas: 'lineItems',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ $unwind: '$lineItems' },\n\t\t\t\t{\n\t\t\t\t\t$match: {\n\t\t\t\t\t\t'lineItems.marketings': marketingId,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$project: {\n\t\t\t\t\t\tdate: {\n\t\t\t\t\t\t\t$dateToString: {\n\t\t\t\t\t\t\t\tformat: dateFormat,\n\t\t\t\t\t\t\t\tdate: '$processedAt',\n\t\t\t\t\t\t\t\ttimezone: LyxaTimezone,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tamount: {\n\t\t\t\t\t\t\t$add: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t\t\tmarketing.isAppliedByCompany,\n\t\t\t\t\t\t\t\t\t\t{ $ifNull: ['$lineItems.calculationSnap.itemDiscountByCompany', 0] },\n\t\t\t\t\t\t\t\t\t\t{ $ifNull: ['$lineItems.calculationSnap.itemDiscountByShop', 0] },\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t\t\tmarketing.isAppliedByCompany,\n\t\t\t\t\t\t\t\t\t\t{ $ifNull: ['$lineItems.calculationSnap.b1g1DiscountByCompany', 0] },\n\t\t\t\t\t\t\t\t\t\t{ $ifNull: ['$lineItems.calculationSnap.b1g1DiscountByShop', 0] },\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$group: {\n\t\t\t\t\t\t_id: '$date',\n\t\t\t\t\t\tamount: { $sum: '$amount' },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ $sort: { _id: 1 } },\n\t\t\t\t{\n\t\t\t\t\t$project: {\n\t\t\t\t\t\t_id: 0,\n\t\t\t\t\t\tdate: '$_id',\n\t\t\t\t\t\tamount: 1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\t\t} else if (marketing.marketingType === MarketingType.FREE_DELIVERY) {\n\n\t\t/**\n\t\t * FREE DELIVERY\n\t\t */\n\t\t\tpipeline = [\n\t\t\t\tthis.buildBaseMatch(marketingId, {\n\t\t\t\t\tstart: data.startDate,\n\t\t\t\t\tend: data.endDate,\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\t$project: {\n\t\t\t\t\t\tdate: {\n\t\t\t\t\t\t\t$dateToString: {\n\t\t\t\t\t\t\t\tformat: dateFormat,\n\t\t\t\t\t\t\t\tdate: '$processedAt',\n\t\t\t\t\t\t\t\ttimezone: LyxaTimezone,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tamount: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\tmarketing.isAppliedByCompany,\n\t\t\t\t\t\t\t\t{ $ifNull: ['$adjustedFinance.freeDelivery.companyCut', 0] },\n\t\t\t\t\t\t\t\t{ $ifNull: ['$adjustedFinance.freeDelivery.shopCut', 0] },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$group: {\n\t\t\t\t\t\t_id: '$date',\n\t\t\t\t\t\tamount: { $sum: '$amount' },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ $sort: { _id: 1 } },\n\t\t\t\t{\n\t\t\t\t\t$project: {\n\t\t\t\t\t\t_id: 0,\n\t\t\t\t\t\tdate: '$_id',\n\t\t\t\t\t\tamount: 1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\t\t} else if (marketing.marketingType === MarketingType.PUNCH_MARKETING) {\n\n\t\t/**\n\t\t * PUNCH MARKETING\n\t\t */\n\t\t\tpipeline = [\n\t\t\t\tthis.buildBaseMatch(marketingId, {\n\t\t\t\t\tstart: data.startDate,\n\t\t\t\t\tend: data.endDate,\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\t$project: {\n\t\t\t\t\t\tdate: {\n\t\t\t\t\t\t\t$dateToString: {\n\t\t\t\t\t\t\t\tformat: dateFormat,\n\t\t\t\t\t\t\t\tdate: '$processedAt',\n\t\t\t\t\t\t\t\ttimezone: LyxaTimezone,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tamount: {\n\t\t\t\t\t\t\t$ifNull: ['$adjustedFinance.pricing.punchMarketingDiscount', 0],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$group: {\n\t\t\t\t\t\t_id: '$date',\n\t\t\t\t\t\tamount: { $sum: '$amount' },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ $sort: { _id: 1 } },\n\t\t\t\t{\n\t\t\t\t\t$project: {\n\t\t\t\t\t\t_id: 0,\n\t\t\t\t\t\tdate: '$_id',\n\t\t\t\t\t\tamount: 1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\t\t}\n\n\t\t// If marketing type doesn't produce spend graph → return empty graph\n\t\tif (!pipeline) {\n\t\t\treturn fillMissingPeriods([] as { date: string; amount: number }[], data.startDate, data.endDate, data.type, {\n\t\t\t\tamount: 0,\n\t\t\t});\n\t\t}\n\n\t\tconst results = await this.orderModel.aggregate(pipeline).allowDiskUse(true).exec();\n\n\t\treturn fillMissingPeriods(results, data.startDate, data.endDate, data.type, {\n\t\t\tamount: 0,\n\t\t});\n\t}\n}\n\nexport const marketingMetricsRepository = Container.get(MarketingMetricsRepository);\n"]}