@lyxa.ai/marketing 1.0.31 → 1.0.34

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 (82) hide show
  1. package/dist/lib/index.d.ts +10 -1
  2. package/dist/lib/index.d.ts.map +1 -1
  3. package/dist/lib/index.js.map +1 -1
  4. package/dist/lib/modules/coupon/routers/coupon.router.d.ts +3 -1
  5. package/dist/lib/modules/coupon/routers/coupon.router.d.ts.map +1 -1
  6. package/dist/lib/modules/coupon/routers/coupon.router.js +11 -7
  7. package/dist/lib/modules/coupon/routers/coupon.router.js.map +1 -1
  8. package/dist/lib/modules/coupon/services/coupon.service.d.ts +3 -1
  9. package/dist/lib/modules/coupon/services/coupon.service.d.ts.map +1 -1
  10. package/dist/lib/modules/coupon/services/coupon.service.js +134 -64
  11. package/dist/lib/modules/coupon/services/coupon.service.js.map +1 -1
  12. package/dist/lib/modules/coupon/services/helper.service.d.ts +3 -0
  13. package/dist/lib/modules/coupon/services/helper.service.d.ts.map +1 -1
  14. package/dist/lib/modules/coupon/services/helper.service.js +34 -2
  15. package/dist/lib/modules/coupon/services/helper.service.js.map +1 -1
  16. package/dist/lib/modules/coupon/services/patterns/repository/CouponRepository.d.ts.map +1 -1
  17. package/dist/lib/modules/coupon/services/patterns/repository/CouponRepository.js +27 -46
  18. package/dist/lib/modules/coupon/services/patterns/repository/CouponRepository.js.map +1 -1
  19. package/dist/lib/modules/coupon/services/referral-code-coupon.service.d.ts +1 -1
  20. package/dist/lib/modules/coupon/services/referral-code-coupon.service.d.ts.map +1 -1
  21. package/dist/lib/modules/coupon/services/referral-code-coupon.service.js +9 -3
  22. package/dist/lib/modules/coupon/services/referral-code-coupon.service.js.map +1 -1
  23. package/dist/lib/modules/coupon/services/referral-reward-coupon.service.d.ts.map +1 -1
  24. package/dist/lib/modules/coupon/services/referral-reward-coupon.service.js +6 -0
  25. package/dist/lib/modules/coupon/services/referral-reward-coupon.service.js.map +1 -1
  26. package/dist/lib/modules/coupon/validations/coupon.validation.d.ts +3 -0
  27. package/dist/lib/modules/coupon/validations/coupon.validation.d.ts.map +1 -1
  28. package/dist/lib/modules/coupon/validations/coupon.validation.js +3 -3
  29. package/dist/lib/modules/coupon/validations/coupon.validation.js.map +1 -1
  30. package/dist/lib/modules/deal-setting/services/deal-setting.service.d.ts +1 -1
  31. package/dist/lib/modules/deal-setting/services/deal-setting.service.d.ts.map +1 -1
  32. package/dist/lib/modules/deal-setting/services/deal-setting.service.js +6 -5
  33. package/dist/lib/modules/deal-setting/services/deal-setting.service.js.map +1 -1
  34. package/dist/lib/modules/marketing/routers/marketing.router.d.ts +7 -0
  35. package/dist/lib/modules/marketing/routers/marketing.router.d.ts.map +1 -1
  36. package/dist/lib/modules/marketing/routers/marketing.router.js +5 -0
  37. package/dist/lib/modules/marketing/routers/marketing.router.js.map +1 -1
  38. package/dist/lib/modules/marketing/services/marketing.service.d.ts.map +1 -1
  39. package/dist/lib/modules/marketing/services/marketing.service.js +23 -4
  40. package/dist/lib/modules/marketing/services/marketing.service.js.map +1 -1
  41. package/dist/lib/modules/marketing/services/product-marketing.service.d.ts +1 -0
  42. package/dist/lib/modules/marketing/services/product-marketing.service.d.ts.map +1 -1
  43. package/dist/lib/modules/marketing/services/product-marketing.service.js +10 -4
  44. package/dist/lib/modules/marketing/services/product-marketing.service.js.map +1 -1
  45. package/dist/lib/modules/marketing/services/synchronize-product-marketing.service.d.ts +1 -0
  46. package/dist/lib/modules/marketing/services/synchronize-product-marketing.service.d.ts.map +1 -1
  47. package/dist/lib/modules/marketing/services/synchronize-product-marketing.service.js +41 -0
  48. package/dist/lib/modules/marketing/services/synchronize-product-marketing.service.js.map +1 -1
  49. package/dist/lib/modules/marketing/validations/buy1-get1-marketing.validation.d.ts +12 -12
  50. package/dist/lib/modules/marketing/validations/discount-marketing.validation.d.ts +12 -12
  51. package/dist/lib/modules/marketing/validations/marketing.validation.d.ts +7 -0
  52. package/dist/lib/modules/marketing/validations/marketing.validation.d.ts.map +1 -1
  53. package/dist/lib/modules/marketing/validations/marketing.validation.js +4 -1
  54. package/dist/lib/modules/marketing/validations/marketing.validation.js.map +1 -1
  55. package/dist/types/index.d.ts +10 -1
  56. package/dist/types/index.d.ts.map +1 -1
  57. package/dist/types/modules/coupon/routers/coupon.router.d.ts +3 -1
  58. package/dist/types/modules/coupon/routers/coupon.router.d.ts.map +1 -1
  59. package/dist/types/modules/coupon/services/coupon.service.d.ts +3 -1
  60. package/dist/types/modules/coupon/services/coupon.service.d.ts.map +1 -1
  61. package/dist/types/modules/coupon/services/helper.service.d.ts +3 -0
  62. package/dist/types/modules/coupon/services/helper.service.d.ts.map +1 -1
  63. package/dist/types/modules/coupon/services/patterns/repository/CouponRepository.d.ts.map +1 -1
  64. package/dist/types/modules/coupon/services/referral-code-coupon.service.d.ts +1 -1
  65. package/dist/types/modules/coupon/services/referral-code-coupon.service.d.ts.map +1 -1
  66. package/dist/types/modules/coupon/services/referral-reward-coupon.service.d.ts.map +1 -1
  67. package/dist/types/modules/coupon/validations/coupon.validation.d.ts +3 -0
  68. package/dist/types/modules/coupon/validations/coupon.validation.d.ts.map +1 -1
  69. package/dist/types/modules/deal-setting/services/deal-setting.service.d.ts +1 -1
  70. package/dist/types/modules/deal-setting/services/deal-setting.service.d.ts.map +1 -1
  71. package/dist/types/modules/marketing/routers/marketing.router.d.ts +7 -0
  72. package/dist/types/modules/marketing/routers/marketing.router.d.ts.map +1 -1
  73. package/dist/types/modules/marketing/services/marketing.service.d.ts.map +1 -1
  74. package/dist/types/modules/marketing/services/product-marketing.service.d.ts +1 -0
  75. package/dist/types/modules/marketing/services/product-marketing.service.d.ts.map +1 -1
  76. package/dist/types/modules/marketing/services/synchronize-product-marketing.service.d.ts +1 -0
  77. package/dist/types/modules/marketing/services/synchronize-product-marketing.service.d.ts.map +1 -1
  78. package/dist/types/modules/marketing/validations/buy1-get1-marketing.validation.d.ts +12 -12
  79. package/dist/types/modules/marketing/validations/discount-marketing.validation.d.ts +12 -12
  80. package/dist/types/modules/marketing/validations/marketing.validation.d.ts +7 -0
  81. package/dist/types/modules/marketing/validations/marketing.validation.d.ts.map +1 -1
  82. package/package.json +2 -2
@@ -67,6 +67,7 @@ let CouponService = class CouponService {
67
67
  referralRewardModel;
68
68
  punchHistoryService;
69
69
  _coreUserModel = null;
70
+ couponHelper;
70
71
  constructor() {
71
72
  this.model = models_1.CouponModel;
72
73
  this.baseCouponModel = models_2.BaseCouponModel;
@@ -75,6 +76,7 @@ let CouponService = class CouponService {
75
76
  this.shopModel = models_1.ShopModel;
76
77
  this.referralRewardModel = models_1.ReferralRewardCouponModel;
77
78
  this.punchHistoryService = services_1.punchMarketingHistoryService;
79
+ this.couponHelper = helper_service_1.couponHelperService;
78
80
  }
79
81
  get coreUserModel() {
80
82
  if (!this._coreUserModel) {
@@ -84,6 +86,11 @@ let CouponService = class CouponService {
84
86
  }
85
87
  async create(data) {
86
88
  let coupon;
89
+ if (data.couponType != enum_1.CouponType.REFERRAL_CODE &&
90
+ data?.duration &&
91
+ !this.couponHelper.isDurationValid((0, dayjs_1.dayjs)(data?.duration?.start), (0, dayjs_1.dayjs)(data?.duration?.end))) {
92
+ (0, error_common_1.conflictError)(`Start date/time cannot be in the past `);
93
+ }
87
94
  const checkCoupon = await this.model.findOne({
88
95
  code: data.code,
89
96
  deletedAt: null,
@@ -262,18 +269,18 @@ let CouponService = class CouponService {
262
269
  }
263
270
  async update(id, data) {
264
271
  let coupon;
265
- const [oldCoupon, oldOrders, checkCouponCode] = await Promise.all([
266
- this.model.findById(id),
267
- this.orderModel
268
- .find({
269
- 'finance.coupon.coupon': id,
270
- })
271
- .select(['user', 'finance']),
272
+ const [oldCoupon, checkCouponCode, usersWithOldCoupon] = await Promise.all([
273
+ this.baseCouponModel.findById(id),
272
274
  this.model.findOne({
273
275
  code: data.code,
274
276
  _id: { $ne: id },
275
277
  updatedVersion: { $exists: false },
276
278
  }),
279
+ this.userModel
280
+ .find({
281
+ coupons: new typegoose_1.mongoose.Types.ObjectId(id),
282
+ })
283
+ .select(['_id', 'coupons']),
277
284
  ]);
278
285
  if (!oldCoupon) {
279
286
  throw new server_1.TRPCError({
@@ -281,23 +288,35 @@ let CouponService = class CouponService {
281
288
  message: `Coupon not found`,
282
289
  });
283
290
  }
291
+ if (data.couponType != enum_1.CouponType.REFERRAL_CODE &&
292
+ oldCoupon?.duration &&
293
+ (0, dayjs_1.dayjs)(oldCoupon?.duration?.start) > (0, dayjs_1.dayjs)(data?.duration.start)) {
294
+ throw new server_1.TRPCError({
295
+ code: 'BAD_REQUEST',
296
+ message: `Don't allow updating coupon to have earlier start date/time than the original coupon`,
297
+ });
298
+ }
299
+ if (data.couponType != enum_1.CouponType.REFERRAL_CODE &&
300
+ data?.duration &&
301
+ (0, dayjs_1.dayjs)(data?.duration?.start) > (0, dayjs_1.dayjs)(data?.duration.end)) {
302
+ throw new server_1.TRPCError({
303
+ code: 'BAD_REQUEST',
304
+ message: `End date/time must be after start date/time`,
305
+ });
306
+ }
284
307
  if (checkCouponCode) {
285
308
  throw new server_1.TRPCError({
286
309
  code: 'CONFLICT',
287
310
  message: `Coupon code already exists`,
288
311
  });
289
312
  }
290
- const oldCouponUsers = oldOrders.map(order => order.user);
291
313
  switch (data.couponType) {
292
314
  case enum_1.CouponType.GLOBAL: {
293
315
  coupon = await _1.globalCouponService.create(data);
294
316
  if (coupon) {
295
317
  const globalCoupon = coupon;
296
318
  if (!globalCoupon.forNewUserOnly) {
297
- await this.exchangeCouponForMultipleUser({ _id: { $nin: oldCouponUsers } }, oldCoupon._id, coupon._id);
298
- }
299
- else {
300
- await this.removeCouponFromMultipleUser({ _id: { $nin: oldCouponUsers } }, oldCoupon._id);
319
+ await this.exchangeCouponForMultipleUser({ _id: { $in: usersWithOldCoupon?.map(u => u._id) } }, oldCoupon._id, coupon._id);
301
320
  }
302
321
  }
303
322
  break;
@@ -307,10 +326,7 @@ let CouponService = class CouponService {
307
326
  if (coupon) {
308
327
  const shopsCategoriesCoupon = coupon;
309
328
  if (!shopsCategoriesCoupon.forNewUserOnly) {
310
- await this.exchangeCouponForMultipleUser({ _id: { $nin: oldCouponUsers } }, oldCoupon._id, coupon._id);
311
- }
312
- else {
313
- await this.removeCouponFromMultipleUser({ _id: { $nin: oldCouponUsers } }, oldCoupon._id);
329
+ await this.exchangeCouponForMultipleUser({ _id: { $in: usersWithOldCoupon?.map(u => u._id) } }, oldCoupon._id, shopsCategoriesCoupon._id);
314
330
  }
315
331
  }
316
332
  break;
@@ -320,10 +336,7 @@ let CouponService = class CouponService {
320
336
  if (coupon) {
321
337
  const individualStoreCoupon = coupon;
322
338
  if (!individualStoreCoupon.forNewUserOnly) {
323
- await this.exchangeCouponForMultipleUser({ _id: { $nin: oldCouponUsers } }, oldCoupon._id, coupon._id);
324
- }
325
- else {
326
- await this.removeCouponFromMultipleUser({ _id: { $nin: oldCouponUsers } }, oldCoupon._id);
339
+ await this.exchangeCouponForMultipleUser({ _id: { $in: usersWithOldCoupon?.map(u => u._id) } }, oldCoupon._id, individualStoreCoupon._id);
327
340
  }
328
341
  }
329
342
  break;
@@ -332,15 +345,19 @@ let CouponService = class CouponService {
332
345
  coupon = await _1.individualUserCouponService.create(data);
333
346
  if (coupon) {
334
347
  const individualUserCoupon = coupon;
335
- await this.removeCouponFromMultipleUser({ _id: { $nin: oldCouponUsers } }, oldCoupon._id);
336
- if (!individualUserCoupon.forNewUserOnly) {
337
- await this.assignCouponToMultipleUser({ _id: { $in: individualUserCoupon.users } }, oldCoupon._id);
338
- }
348
+ await this.removeCouponFromMultipleUser({ _id: { $in: usersWithOldCoupon?.map(u => u._id) } }, oldCoupon._id);
349
+ await this.assignCouponToMultipleUser({ _id: { $in: individualUserCoupon.users } }, individualUserCoupon._id);
339
350
  }
340
351
  break;
341
352
  }
342
353
  case enum_1.CouponType.CUSTOM_COUPON: {
343
354
  coupon = await _1.customCouponService.create(data);
355
+ if (coupon) {
356
+ const customCoupon = coupon;
357
+ if (!customCoupon.forNewUserOnly) {
358
+ await this.exchangeCouponForMultipleUser({ _id: { $in: usersWithOldCoupon?.map(u => u._id) } }, oldCoupon._id, coupon._id);
359
+ }
360
+ }
344
361
  break;
345
362
  }
346
363
  default: {
@@ -358,7 +375,7 @@ let CouponService = class CouponService {
358
375
  }
359
376
  const previousVersions = oldCoupon?.previousVersions || [];
360
377
  previousVersions.push(oldCoupon._id);
361
- const updatedCoupon = await this.model.findByIdAndUpdate(coupon._id, {
378
+ const updatedCoupon = await this.baseCouponModel.findByIdAndUpdate(coupon._id, {
362
379
  $set: {
363
380
  previousVersions,
364
381
  },
@@ -372,9 +389,10 @@ let CouponService = class CouponService {
372
389
  message: `Could not set previous versions of coupon`,
373
390
  });
374
391
  }
375
- const updatedOldCoupon = await this.model.findByIdAndUpdate(oldCoupon._id, {
392
+ const updatedOldCoupon = await this.baseCouponModel.findByIdAndUpdate(oldCoupon._id, {
376
393
  $set: {
377
394
  updatedVersion: coupon._id,
395
+ 'duration.end': coupon.duration.end,
378
396
  },
379
397
  }, {
380
398
  new: true,
@@ -395,10 +413,20 @@ let CouponService = class CouponService {
395
413
  message: 'Coupon not found',
396
414
  });
397
415
  }
416
+ const previousVersions = coupon.previousVersions;
417
+ if (previousVersions && previousVersions.length > 0) {
418
+ await this.baseCouponModel.updateMany({ _id: { $in: previousVersions } }, {
419
+ $set: { status },
420
+ });
421
+ }
398
422
  return coupon;
399
423
  }
400
424
  async deleteById(data) {
401
425
  const { _id, softDelete } = data;
426
+ const coupon = await this.model.findById(_id);
427
+ if (!coupon) {
428
+ (0, error_common_1.notFoundError)('Coupon not found');
429
+ }
402
430
  const result = await this.model.deleteRecord({ _id, deletedAt: null }, softDelete);
403
431
  if (!result) {
404
432
  throw new server_1.TRPCError({
@@ -407,6 +435,10 @@ let CouponService = class CouponService {
407
435
  });
408
436
  }
409
437
  this.removeCouponFromMultipleUser({}, _id);
438
+ const previousVersions = coupon.previousVersions;
439
+ if (previousVersions && previousVersions.length > 0) {
440
+ await this.model.deleteRecord({ _id: { $in: previousVersions }, deletedAt: null }, softDelete);
441
+ }
410
442
  return 'Record deleted successfully';
411
443
  }
412
444
  async getUserCoupons(user, shop, page = 0, size = 0) {
@@ -420,7 +452,7 @@ let CouponService = class CouponService {
420
452
  if (shop && user) {
421
453
  const punch = await this.punchHistoryService.getPunchCoupon(user, shop);
422
454
  if (punch) {
423
- coupons.available.unshift(punch);
455
+ coupons.available.push(punch);
424
456
  }
425
457
  }
426
458
  return couponRepository.addLabelsToAllCoupons(coupons);
@@ -429,19 +461,30 @@ let CouponService = class CouponService {
429
461
  if (data.coupon === 'punch') {
430
462
  return await services_1.punchMarketingHistoryService.getPunchDiscount(data);
431
463
  }
432
- const [user, coupon] = await Promise.all([
433
- this.userModel.findById(data.user),
434
- this.model.findOne({ code: data.coupon, updatedVersion: { $exists: false } }),
435
- ]);
464
+ const user = await this.userModel.findById(data.user);
436
465
  if (!user)
437
466
  (0, error_common_1.notFoundError)('User not found');
438
- if (!coupon)
439
- (0, error_common_1.notFoundError)('Coupon not found');
467
+ let coupon = await this.model.findOne({
468
+ code: data.coupon,
469
+ _id: { $in: user.coupons ?? [] },
470
+ status: { $in: [enum_1.Status.ACTIVE, null] },
471
+ });
472
+ if (!coupon) {
473
+ coupon = await this.model.findOne({
474
+ code: data.coupon,
475
+ status: { $in: [enum_1.Status.ACTIVE, null] },
476
+ couponType: { $in: [enum_1.CouponType.REFERRAL_CODE, enum_1.CouponType.CUSTOM_COUPON] },
477
+ updatedVersion: { $exists: false },
478
+ });
479
+ if (!coupon) {
480
+ (0, error_common_1.notFoundError)('Coupon not found');
481
+ }
482
+ }
440
483
  if (coupon.couponType == enum_1.CouponType.REFERRAL_CODE) {
441
- return await _1.referralCodeCouponService.validateCoupon(data);
484
+ return await _1.referralCodeCouponService.validateCoupon(data, coupon);
442
485
  }
443
486
  const baseCoupon = coupon;
444
- const { isValid, invalidMessage } = await this.validateBaseCoupon(baseCoupon, user._id, data.amountBeforeCoupon);
487
+ const { isValid, invalidMessage } = await this.validateBaseCoupon(baseCoupon, user._id, data.amountBeforeCoupon, Boolean(data.scheduledAt) ? (0, dayjs_1.dayjs)(data.scheduledAt) : undefined);
445
488
  if (!isValid) {
446
489
  return {
447
490
  isValid,
@@ -471,15 +514,16 @@ let CouponService = class CouponService {
471
514
  }
472
515
  return false;
473
516
  }
474
- async validateBaseCoupon(coupon, user, orderAmount) {
517
+ async validateBaseCoupon(coupon, user, orderAmount, scheduledAt = undefined) {
475
518
  const invalidConditions = [
476
519
  this.isCouponExpired(coupon),
477
- coupon.duration.start > new Date(),
520
+ coupon.duration.start > (0, dayjs_1.dayjs)().toDate(),
478
521
  coupon.isMinOrderValueEnabled && coupon.minOrderValue && orderAmount < coupon.minOrderValue,
479
- coupon.forNewUserOnly && !(await helper_service_1.couponHelperService.isNewUser(user)),
522
+ coupon.forNewUserOnly && !(await this.verifyNewUserConditions(coupon, user)),
480
523
  coupon.isOrderLimitPerUserEnabled &&
481
524
  coupon.orderLimitPerUser &&
482
525
  (await this.getCouponOrdersForUser(user, coupon.code)) >= coupon.orderLimitPerUser,
526
+ scheduledAt && Boolean(coupon.duration.end) && (0, dayjs_1.dayjs)(coupon.duration.end).isBefore(scheduledAt),
483
527
  ];
484
528
  const invalidMessages = [
485
529
  'This coupon is expired',
@@ -487,11 +531,25 @@ let CouponService = class CouponService {
487
531
  'The minimum order amount for this coupon is not met',
488
532
  'This coupon is for new users only',
489
533
  'You have reached the order limit for this coupon',
534
+ 'This coupon is not valid for this scheduled orders',
490
535
  ];
491
536
  const isValid = invalidConditions.every(value => Boolean(value) == false);
492
537
  const invalidMessage = invalidMessages.filter((_, index) => invalidConditions[index])?.[0];
493
538
  return { isValid, invalidMessage };
494
539
  }
540
+ async verifyNewUserConditions(coupon, user) {
541
+ const forNewUserOnly = coupon.forNewUserOnly;
542
+ const isOrderLimitPerUserEnabled = coupon.isOrderLimitPerUserEnabled;
543
+ const orderLimitPerUser = coupon.orderLimitPerUser;
544
+ if (forNewUserOnly) {
545
+ if (isOrderLimitPerUserEnabled && orderLimitPerUser) {
546
+ const orderCount = await helper_service_1.couponHelperService.getSameDeviceOrders(user);
547
+ return orderLimitPerUser > orderCount;
548
+ }
549
+ return await helper_service_1.couponHelperService.isNewUser(user);
550
+ }
551
+ return true;
552
+ }
495
553
  async getCouponOrdersForUser(user, couponCode) {
496
554
  const orders = (await this.orderModel
497
555
  .find({
@@ -503,11 +561,9 @@ let CouponService = class CouponService {
503
561
  const count = orders.filter(order => order.cart.couponCode == couponCode).length;
504
562
  return count;
505
563
  }
506
- async handleCouponExpiry(couponCode) {
507
- const coupon = await this.model.findOne({ code: couponCode, updatedVersion: { $exists: false } });
508
- if (!coupon ||
509
- coupon.couponType == enum_1.CouponType.REFERRAL_CODE ||
510
- coupon.couponType == enum_1.CouponType.REFERRAL_REWARD) {
564
+ async handleCouponExpiry(couponId) {
565
+ const coupon = await this.model.findById(couponId);
566
+ if (!coupon || coupon.couponType == enum_1.CouponType.REFERRAL_CODE) {
511
567
  return;
512
568
  }
513
569
  const typedCoupon = coupon;
@@ -542,7 +598,7 @@ let CouponService = class CouponService {
542
598
  ];
543
599
  const result = await this.orderModel.aggregate(pipeline);
544
600
  const orderCount = result[0]?.orderCount ?? 0;
545
- if (orderCount > typedCoupon.totalOrderLimit) {
601
+ if (orderCount >= typedCoupon.totalOrderLimit) {
546
602
  expirationReason = enum_1.CouponExpirationReason.TOTAL_ORDER_LIMIT;
547
603
  }
548
604
  }
@@ -562,7 +618,7 @@ let CouponService = class CouponService {
562
618
  });
563
619
  }
564
620
  async findCouponByCode(code) {
565
- const coupon = await this.model.findOne({ code: code });
621
+ const coupon = await this.model.findOne({ code: code, updatedVersion: { $exists: false } });
566
622
  if (!coupon) {
567
623
  throw new server_1.TRPCError({
568
624
  code: 'NOT_FOUND',
@@ -601,14 +657,14 @@ let CouponService = class CouponService {
601
657
  totalCouponDiscount: {
602
658
  $sum: {
603
659
  $toDouble: {
604
- $ifNull: ['$finance.pricing.couponDiscount', 0],
660
+ $ifNull: ['$adjustedFinance.pricing.couponDiscount', 0],
605
661
  },
606
662
  },
607
663
  },
608
664
  totalSecondaryCouponDiscount: {
609
665
  $sum: {
610
666
  $toDouble: {
611
- $ifNull: ['$finance.pricing.secondaryCouponDiscount', 0],
667
+ $ifNull: ['$adjustedFinance.pricing.secondaryCouponDiscount', 0],
612
668
  },
613
669
  },
614
670
  },
@@ -680,6 +736,11 @@ let CouponService = class CouponService {
680
736
  if (coupon.couponType == enum_1.CouponType.REFERRAL_CODE && !isNewUser) {
681
737
  this.throwBadRequest('This coupon is valid for new users only');
682
738
  }
739
+ if (coupon.couponType == enum_1.CouponType.REFERRAL_CODE) {
740
+ if (coupon.referralUser.toString() == user) {
741
+ this.throwBadRequest('You cannot add your own referral code');
742
+ }
743
+ }
683
744
  const typedCoupon = coupon;
684
745
  if (this.isCouponExpired(typedCoupon)) {
685
746
  this.throwBadRequest('This coupon has expired and cannot be added');
@@ -687,7 +748,7 @@ let CouponService = class CouponService {
687
748
  if (typedCoupon.forNewUserOnly && !isNewUser) {
688
749
  this.throwBadRequest('This coupon is valid for new users only');
689
750
  }
690
- const alreadyApplied = await this.hasUserAlreadyAppliedCoupon(user, typedCoupon._id);
751
+ const alreadyApplied = await this.hasUserAlreadyAppliedCoupon(user, typedCoupon);
691
752
  if (alreadyApplied) {
692
753
  this.throwBadRequest('Coupon already applied to user');
693
754
  }
@@ -699,18 +760,13 @@ let CouponService = class CouponService {
699
760
  await this.userModel.findByIdAndUpdate(user, { $push: { coupons: typedCoupon._id } }, { new: true, runValidators: true });
700
761
  return coupon;
701
762
  }
702
- async hasUserAlreadyAppliedCoupon(userId, couponId) {
703
- const user = await this.userModel.findById(userId).select('coupons');
704
- if (!user) {
705
- throw new server_1.TRPCError({
706
- code: 'NOT_FOUND',
707
- message: 'User not found',
708
- });
709
- }
710
- return (user.coupons?.some((c) => {
711
- const id = (c?._id ?? c)?.toString();
712
- return id === couponId.toString();
713
- }) ?? false);
763
+ async hasUserAlreadyAppliedCoupon(userId, coupon) {
764
+ const couponIds = [coupon._id, ...(coupon.previousVersions ?? []).map(v => v._id)];
765
+ const user = await this.userModel.exists({
766
+ _id: userId,
767
+ coupons: { $in: couponIds },
768
+ });
769
+ return !!user;
714
770
  }
715
771
  async exchangeCouponForMultipleUser(query, oldCoupon, newCoupon) {
716
772
  await this.removeCouponFromMultipleUser(query, oldCoupon);
@@ -738,6 +794,7 @@ let CouponService = class CouponService {
738
794
  code: 1,
739
795
  status: 1,
740
796
  createdAt: 1,
797
+ couponType: 1,
741
798
  };
742
799
  let isExpiredField = null;
743
800
  if (query.status) {
@@ -779,7 +836,15 @@ let CouponService = class CouponService {
779
836
  isExpired: {
780
837
  $cond: {
781
838
  if: {
782
- $or: [{ $lt: ['$duration.end', new Date()] }, { $ifNull: ['$expirationReason', false] }],
839
+ $or: [
840
+ {
841
+ $and: [
842
+ { $ifNull: ['$duration.end', false] },
843
+ { $lt: ['$duration.end', (0, dayjs_1.dayjs)().toDate()] },
844
+ ],
845
+ },
846
+ { $ifNull: ['$expirationReason', false] },
847
+ ],
783
848
  },
784
849
  then: true,
785
850
  else: false,
@@ -830,17 +895,22 @@ let CouponService = class CouponService {
830
895
  }
831
896
  }
832
897
  async addExistingCouponsToNewUser(userId) {
833
- const coupons = await this.baseCouponModel.find({
898
+ const isNewUser = await helper_service_1.couponHelperService.isNewUser(userId);
899
+ const query = {
834
900
  couponType: { $in: [enum_1.CouponType.GLOBAL, enum_1.CouponType.INDIVIDUAL_STORE, enum_1.CouponType.SHOPS_CATEGORIES] },
835
901
  deletedAt: null,
836
902
  expirationReason: null,
837
903
  $or: [
838
- { 'duration.end': { $gt: new Date() } },
904
+ { 'duration.end': { $gt: (0, dayjs_1.dayjs)().toDate() } },
839
905
  { 'duration.end': { $exists: false } },
840
906
  { 'duration.end': null },
841
907
  ],
842
908
  updatedVersion: { $exists: false },
843
- });
909
+ };
910
+ if (!isNewUser) {
911
+ query.forNewUserOnly = { $ne: true };
912
+ }
913
+ const coupons = await this.baseCouponModel.find(query);
844
914
  const couponIds = coupons.map(coupon => coupon._id);
845
915
  await this.userModel.findByIdAndUpdate(userId, {
846
916
  $addToSet: {