@lyxa.ai/marketing 1.0.37 → 1.0.40

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 (59) hide show
  1. package/dist/lib/index.d.ts +87 -7
  2. package/dist/lib/index.d.ts.map +1 -1
  3. package/dist/lib/modules/coupon/services/coupon.service.d.ts +3 -0
  4. package/dist/lib/modules/coupon/services/coupon.service.d.ts.map +1 -1
  5. package/dist/lib/modules/coupon/services/coupon.service.js +122 -5
  6. package/dist/lib/modules/coupon/services/coupon.service.js.map +1 -1
  7. package/dist/lib/modules/coupon/services/patterns/repository/CouponRepository.d.ts.map +1 -1
  8. package/dist/lib/modules/coupon/services/patterns/repository/CouponRepository.js +7 -0
  9. package/dist/lib/modules/coupon/services/patterns/repository/CouponRepository.js.map +1 -1
  10. package/dist/lib/modules/coupon/validations/coupon.validation.d.ts.map +1 -1
  11. package/dist/lib/modules/coupon/validations/coupon.validation.js +5 -14
  12. package/dist/lib/modules/coupon/validations/coupon.validation.js.map +1 -1
  13. package/dist/lib/modules/marketing/patterns/repository/MarketingMetricsRepository.d.ts +39 -0
  14. package/dist/lib/modules/marketing/patterns/repository/MarketingMetricsRepository.d.ts.map +1 -0
  15. package/dist/lib/modules/marketing/patterns/repository/MarketingMetricsRepository.js +539 -0
  16. package/dist/lib/modules/marketing/patterns/repository/MarketingMetricsRepository.js.map +1 -0
  17. package/dist/lib/modules/marketing/routers/marketing.router.d.ts +87 -7
  18. package/dist/lib/modules/marketing/routers/marketing.router.d.ts.map +1 -1
  19. package/dist/lib/modules/marketing/routers/marketing.router.js +27 -8
  20. package/dist/lib/modules/marketing/routers/marketing.router.js.map +1 -1
  21. package/dist/lib/modules/marketing/services/marketing.service.d.ts +4 -8
  22. package/dist/lib/modules/marketing/services/marketing.service.d.ts.map +1 -1
  23. package/dist/lib/modules/marketing/services/marketing.service.js +65 -355
  24. package/dist/lib/modules/marketing/services/marketing.service.js.map +1 -1
  25. package/dist/lib/modules/marketing/services/product-marketing.service.d.ts +1 -0
  26. package/dist/lib/modules/marketing/services/product-marketing.service.d.ts.map +1 -1
  27. package/dist/lib/modules/marketing/services/product-marketing.service.js +4 -0
  28. package/dist/lib/modules/marketing/services/product-marketing.service.js.map +1 -1
  29. package/dist/lib/modules/marketing/validations/marketing.validation.d.ts +106 -1
  30. package/dist/lib/modules/marketing/validations/marketing.validation.d.ts.map +1 -1
  31. package/dist/lib/modules/marketing/validations/marketing.validation.js +31 -1
  32. package/dist/lib/modules/marketing/validations/marketing.validation.js.map +1 -1
  33. package/dist/lib/modules/punch-marketing-history/services/punch-marketing-history.service.d.ts.map +1 -1
  34. package/dist/lib/modules/punch-marketing-history/services/punch-marketing-history.service.js +19 -1
  35. package/dist/lib/modules/punch-marketing-history/services/punch-marketing-history.service.js.map +1 -1
  36. package/dist/lib/utility/utils.d.ts +3 -0
  37. package/dist/lib/utility/utils.d.ts.map +1 -0
  38. package/dist/lib/utility/utils.js +31 -0
  39. package/dist/lib/utility/utils.js.map +1 -0
  40. package/dist/types/index.d.ts +87 -7
  41. package/dist/types/index.d.ts.map +1 -1
  42. package/dist/types/modules/coupon/services/coupon.service.d.ts +3 -0
  43. package/dist/types/modules/coupon/services/coupon.service.d.ts.map +1 -1
  44. package/dist/types/modules/coupon/services/patterns/repository/CouponRepository.d.ts.map +1 -1
  45. package/dist/types/modules/coupon/validations/coupon.validation.d.ts.map +1 -1
  46. package/dist/types/modules/marketing/patterns/repository/MarketingMetricsRepository.d.ts +39 -0
  47. package/dist/types/modules/marketing/patterns/repository/MarketingMetricsRepository.d.ts.map +1 -0
  48. package/dist/types/modules/marketing/routers/marketing.router.d.ts +87 -7
  49. package/dist/types/modules/marketing/routers/marketing.router.d.ts.map +1 -1
  50. package/dist/types/modules/marketing/services/marketing.service.d.ts +4 -8
  51. package/dist/types/modules/marketing/services/marketing.service.d.ts.map +1 -1
  52. package/dist/types/modules/marketing/services/product-marketing.service.d.ts +1 -0
  53. package/dist/types/modules/marketing/services/product-marketing.service.d.ts.map +1 -1
  54. package/dist/types/modules/marketing/validations/marketing.validation.d.ts +106 -1
  55. package/dist/types/modules/marketing/validations/marketing.validation.d.ts.map +1 -1
  56. package/dist/types/modules/punch-marketing-history/services/punch-marketing-history.service.d.ts.map +1 -1
  57. package/dist/types/utility/utils.d.ts +15 -0
  58. package/dist/types/utility/utils.d.ts.map +1 -0
  59. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"coupon.service.js","sourceRoot":"/","sources":["modules/coupon/services/coupon.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAA4C;AAC5C,yCAAyC;AACzC,oDAA4F;AAC5F,sEAmBmD;AAenD,wEAIiD;AAEjD,wBAOW;AACX,4DAO2C;AAC3C,sEAAwF;AACxF,wEAGmD;AACnD,wCAA6C;AAE7C,6EAA0E;AAC1E,4EAMmD;AACnD,uFAAiF;AACjF,qDAA4E;AAC5E,8DAAkE;AAG3D,IAAM,aAAa,GAAnB,MAAM,aAAa;IACjB,KAAK,CAA8C;IACnD,eAAe,CAAuD;IACtE,SAAS,CAA2C;IACpD,UAAU,CAA2D;IACrE,SAAS,CAA2C;IACpD,mBAAmB,CAA2E;IAC9F,mBAAmB,CAA+B;IAClD,cAAc,GAA+C,IAAI,CAAC;IAClE,YAAY,CAAsB;IAE1C;QACC,IAAI,CAAC,KAAK,GAAG,oBAA0D,CAAC;QACxE,IAAI,CAAC,eAAe,GAAG,wBAAuE,CAAC;QAC/F,IAAI,CAAC,SAAS,GAAG,kBAAqD,CAAC;QACvE,IAAI,CAAC,UAAU,GAAG,0BAA6E,CAAC;QAChG,IAAI,CAAC,SAAS,GAAG,kBAAqD,CAAC;QACvE,IAAI,CAAC,mBAAmB,GAAG,kCACW,CAAC;QACvC,IAAI,CAAC,mBAAmB,GAAG,uCAA4B,CAAC;QACxD,IAAI,CAAC,YAAY,GAAG,oCAAmB,CAAC;IACzC,C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C,OAAO,CAAC,CAAC;QAGrD,MAAM,mBAAmB,GAAG,MAAM,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAChE,IAAI,CAAC,mBAAmB,EAAE,CAAC;YAC1B,IAAA,4BAAa,EAAC,iCAAiC,CAAC,CAAC;QAClD,CAAC;QAGD,IACC,mBAAmB,CAAC,0BAA0B;YAC9C,WAAW,GAAG,CAAC,mBAAmB,CAAC,iBAAiB,IAAI,CAAC,CAAC,EACzD,CAAC;YACF,OAAO,gBAAgB,CAAC,kBAAkB,CAAC,CAAC,mBAAmB,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAC5E,CAAC;QAED,IAAA,4BAAa,EAAC,8BAA8B,CAAC,CAAC;QAE9C,OAAO,EAAE,CAAC;IACX,CAAC;IAEM,KAAK,CAAC,wBAAwB,CAAC,MAA+B,EAAE,IAAS;QAC/E,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,SAAS,CAC5C,EAAE,GAAG,EAAE,MAAM,EAAE,EACf;YACC,IAAI,EAAE;gBACL,qBAAqB,EAAE,IAAI,CAAC,qBAAqB;aACjD;SACD,CACD,CAAC;QAEF,OAAO,MAAM,CAAC,aAAa,CAAC;IAC7B,CAAC;CACD,CAAA;AAvuCY,sCAAa;wBAAb,aAAa;IADzB,IAAA,gBAAO,GAAE;;GACG,aAAa,CAuuCzB;AAEY,QAAA,aAAa,GAAG,gBAAS,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC","sourcesContent":["import Container, { Service } from 'typedi';\nimport { TRPCError } from '@trpc/server';\nimport { DocumentType, mongoose, queryMethod, ReturnModelType } from '@typegoose/typegoose';\nimport {\n\tCart,\n\tCouponModel,\n\tCustomCoupon,\n\tgetCoreUserModel,\n\tGlobalCoupon,\n\tIndividualStoreCoupon,\n\tIndividualUserCoupon,\n\tCoupon as Model,\n\tReferralRewardCoupon,\n\tReferralRewardCouponModel,\n\tRegularOrder,\n\tRegularOrderModel,\n\tShopModel,\n\tShop,\n\tShopsCategoriesCoupon,\n\tUser,\n\tUserModel,\n\tReferralCodeCoupon,\n} from '@lyxa.ai/core/dist/libraries/mongo/models';\nimport {\n\tAllCouponsValidationDTO,\n\tCouponValidationOutputDTO,\n\tValidateCouponDTO,\n\tAllCouponsDTO,\n\tCheckExistingNewUserCouponOutputDTO,\n} from '@modules/coupon/validations';\nimport { SoftDeleteModel } from '@lyxa.ai/core/dist/libraries/mongo/plugins/soft-delete-plugin';\nimport {\n\tFilterDTO,\n\tPaginatedResponse,\n\tDeleteDTO,\n\tShareableLinkDTO,\n} from '@lyxa.ai/core/dist/utilities/validation';\nimport {\n\tcreateRawDocumentPaginatorObject,\n\tpaginateAggregation,\n\tPaginatorOptions,\n} from '@lyxa.ai/core/dist/utilities/pagination';\nimport { ModelType } from '@typegoose/typegoose/lib/types';\nimport {\n\tcustomCouponService,\n\tglobalCouponService,\n\tindividualStoreCouponService,\n\tindividualUserCouponService,\n\treferralCodeCouponService,\n\treferralRewardCouponService,\n} from '.';\nimport {\n\tCouponExpirationReason,\n\tCouponType,\n\tItemType,\n\tOrderType,\n\tRegularOrderStatus,\n\tStatus,\n} from '@lyxa.ai/core/dist/utilities/enum';\nimport { BaseCoupon, BaseCouponModel } from '@lyxa.ai/core/dist/libraries/mongo/models';\nimport {\n\tPunchMarketingHistoryService,\n\tpunchMarketingHistoryService,\n} from '@modules/punch-marketing-history/services';\nimport { getLibraries } from '@lyxa.ai/core';\nimport { NotificationMicroserviceRouter } from '@lyxa.ai/notification';\nimport { CouponRepository } from './patterns/repository/CouponRepository';\nimport {\n\tbadRequestError,\n\tconflictError,\n\tinternalServerError,\n\tnotFoundError,\n\tnotImplementedError,\n} from '@lyxa.ai/core/dist/utilities/error-common';\nimport { shopsCategoriesCouponService } from './shops-categories-coupon.service';\nimport { CouponHelperService, couponHelperService } from './helper.service';\nimport { Dayjs, dayjs } from '@lyxa.ai/core/dist/utilities/dayjs';\n\n@Service()\nexport class CouponService {\n\tprivate model: typeof CouponModel & SoftDeleteModel<Model>;\n\tprivate baseCouponModel: typeof BaseCouponModel & SoftDeleteModel<BaseCoupon>;\n\tprivate userModel: typeof UserModel & SoftDeleteModel<User>;\n\tprivate orderModel: typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\n\tprivate shopModel: typeof ShopModel & SoftDeleteModel<Shop>;\n\tprivate referralRewardModel: typeof ReferralRewardCouponModel & SoftDeleteModel<ReferralRewardCoupon>;\n\tprivate punchHistoryService: PunchMarketingHistoryService;\n\tprivate _coreUserModel: ReturnType<typeof getCoreUserModel> | null = null;\n\tprivate couponHelper: CouponHelperService;\n\n\tconstructor() {\n\t\tthis.model = CouponModel as typeof CouponModel & SoftDeleteModel<Model>;\n\t\tthis.baseCouponModel = BaseCouponModel as typeof BaseCouponModel & SoftDeleteModel<BaseCoupon>;\n\t\tthis.userModel = UserModel as typeof UserModel & SoftDeleteModel<User>;\n\t\tthis.orderModel = RegularOrderModel as typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\n\t\tthis.shopModel = ShopModel as typeof ShopModel & SoftDeleteModel<Shop>;\n\t\tthis.referralRewardModel = ReferralRewardCouponModel as typeof ReferralRewardCouponModel &\n\t\t\tSoftDeleteModel<ReferralRewardCoupon>;\n\t\tthis.punchHistoryService = punchMarketingHistoryService;\n\t\tthis.couponHelper = couponHelperService;\n\t}\n\n\tprivate get coreUserModel() {\n\t\tif (!this._coreUserModel) {\n\t\t\tthis._coreUserModel = getCoreUserModel();\n\t\t}\n\t\treturn this._coreUserModel;\n\t}\n\n\t/**\n\t * Create a new record\n\t * @param data Data for the new record\n\t */\n\tpublic async create(data: AllCouponsValidationDTO): Promise<DocumentType<Model>> {\n\t\tlet coupon: DocumentType<Model>;\n\n\t\tif (\n\t\t\tdata.couponType != CouponType.REFERRAL_CODE &&\n\t\t\tdata?.duration &&\n\t\t\t!this.couponHelper.isDurationValid(dayjs(data?.duration?.start), dayjs(data?.duration?.end))\n\t\t) {\n\t\t\tconflictError(`Start date/time cannot be in the past `);\n\t\t}\n\n\t\tconst checkCoupon = await this.model.findOne({\n\t\t\tcode: data.code,\n\t\t\tdeletedAt: null,\n\t\t});\n\n\t\tif (checkCoupon) conflictError('Coupon code already exists');\n\n\t\tswitch (data.couponType) {\n\t\t\tcase CouponType.GLOBAL: {\n\t\t\t\tcoupon = await globalCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst globalCoupon = coupon as DocumentType<GlobalCoupon>;\n\t\t\t\t\tif (!globalCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.assignCouponToMultipleUser({}, coupon._id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.assignCouponToNewUsers(coupon._id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CouponType.REFERRAL_CODE: {\n\t\t\t\tcoupon = await referralCodeCouponService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CouponType.REFERRAL_REWARD: {\n\t\t\t\tcoupon = await referralRewardCouponService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CouponType.SHOPS_CATEGORIES: {\n\t\t\t\tcoupon = await shopsCategoriesCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst shopsCategoriesCoupon = coupon as DocumentType<ShopsCategoriesCoupon>;\n\t\t\t\t\tif (!shopsCategoriesCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.assignCouponToMultipleUser({}, coupon._id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.assignCouponToNewUsers(coupon._id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CouponType.INDIVIDUAL_STORE: {\n\t\t\t\tcoupon = await individualStoreCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst individualStoreCoupon = coupon as DocumentType<IndividualStoreCoupon>;\n\t\t\t\t\tif (!individualStoreCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.assignCouponToMultipleUser({}, coupon._id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.assignCouponToNewUsers(coupon._id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CouponType.INDIVIDUAL_USER: {\n\t\t\t\tcoupon = await individualUserCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst individualUserCoupon = coupon as DocumentType<IndividualUserCoupon>;\n\t\t\t\t\tconst users = individualUserCoupon.users;\n\t\t\t\t\tawait this.assignCouponToMultipleUser({ _id: { $in: users } }, coupon._id);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CouponType.CUSTOM_COUPON: {\n\t\t\t\tcoupon = await customCouponService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tbadRequestError('Coupon type is not valid');\n\t\t\t}\n\t\t}\n\n\t\tif (!coupon) internalServerError('Could not create coupon');\n\n\t\t// Send Notification\n\t\tconst dispatcher = getLibraries().getMicroServiceDispatcher();\n\t\tconst notificationRouter =\n\t\t\tawait dispatcher.getMicroService<NotificationMicroserviceRouter>('notification');\n\n\t\tawait notificationRouter.notificationRouter.sendPushNotificationForCoupon.mutate(coupon._id);\n\n\t\treturn coupon;\n\t}\n\n\t/**\n\t * Get record by ID\n\t * @param id ID of the record\n\t */\n\tpublic async findById(id: string | mongoose.Types.ObjectId): Promise<DocumentType<Model>> {\n\t\tconst result = await this.model\n\t\t\t.findOne({\n\t\t\t\t_id: id,\n\t\t\t\tdeletedAt: null,\n\t\t\t})\n\t\t\t.populate([\n\t\t\t\t{\n\t\t\t\t\tpath: 'previousVersions',\n\t\t\t\t},\n\t\t\t]);\n\t\tif (!result) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'NOT_FOUND',\n\t\t\t\tmessage: 'Record not found',\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get records\n\t * @param query Query to find records\n\t */\n\tpublic async find(data?: Partial<FilterDTO>): Promise<PaginatedResponse<DocumentType<ModelType<Model>>>> {\n\t\ttry {\n\t\t\tconst populate = [\n\t\t\t\t...data?.populate,\n\t\t\t\t{\n\t\t\t\t\tpath: 'users',\n\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: 'coreUser',\n\t\t\t\t\t\t\tmodel: this.coreUserModel,\n\t\t\t\t\t\t\tselect: 'name profilePhoto -_id',\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tselect: 'coreUser phoneNumber',\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tpath: 'influencer',\n\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: 'coreUser',\n\t\t\t\t\t\t\tmodel: this.coreUserModel,\n\t\t\t\t\t\t\tselect: 'name profilePhoto -_id',\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tselect: 'coreUser phoneNumber',\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tpath: 'referralUser',\n\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: 'coreUser',\n\t\t\t\t\t\t\tmodel: this.coreUserModel,\n\t\t\t\t\t\t\tselect: 'name profilePhoto -_id',\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tselect: 'coreUser phoneNumber',\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tpath: 'user',\n\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: 'coreUser',\n\t\t\t\t\t\t\tmodel: this.coreUserModel,\n\t\t\t\t\t\t\tselect: 'name profilePhoto -_id',\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tselect: 'coreUser phoneNumber',\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tpath: 'referralCodeUsedBy',\n\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: 'coreUser',\n\t\t\t\t\t\t\tmodel: this.coreUserModel,\n\t\t\t\t\t\t\tselect: 'name profilePhoto -_id',\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tselect: 'coreUser phoneNumber',\n\t\t\t\t},\n\t\t\t];\n\n\t\t\tconst paginate = createRawDocumentPaginatorObject(this.model as ReturnModelType<typeof this.model>);\n\t\t\tconst options: PaginatorOptions<typeof Model> = {\n\t\t\t\tpage: data?.page,\n\t\t\t\tsize: data?.size,\n\t\t\t\tsort: data?.sort,\n\t\t\t\tquery: { ...data?.query, updatedVersion: { $exists: false } },\n\t\t\t\tselect: data?.select,\n\t\t\t\tpopulate: populate,\n\t\t\t};\n\t\t\tconst paginatedResult = await paginate(options);\n\t\t\treturn paginatedResult;\n\t\t} catch (err) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: `err: ${err}`,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Update record\n\t * @param id ID of the old coupon\n\t * @param data Data of the updated coupon\n\t */\n\tpublic async update(id: string, data: AllCouponsValidationDTO): Promise<DocumentType<Model>> {\n\t\tlet coupon: DocumentType<BaseCoupon> | null;\n\n\t\tconst [oldCoupon, checkCouponCode, usersWithOldCoupon] = await Promise.all([\n\t\t\tthis.baseCouponModel.findById(id),\n\t\t\tthis.model.findOne({\n\t\t\t\tcode: data.code,\n\t\t\t\t_id: { $ne: id },\n\t\t\t\tupdatedVersion: { $exists: false },\n\t\t\t}),\n\t\t\tthis.userModel\n\t\t\t\t.find({\n\t\t\t\t\tcoupons: new mongoose.Types.ObjectId(id),\n\t\t\t\t})\n\t\t\t\t.select(['_id', 'coupons']),\n\t\t]);\n\n\t\tif (!oldCoupon) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'NOT_FOUND',\n\t\t\t\tmessage: `Coupon not found`,\n\t\t\t});\n\t\t}\n\n\t\tif (\n\t\t\tdata.couponType != CouponType.REFERRAL_CODE &&\n\t\t\toldCoupon?.duration &&\n\t\t\tdayjs(oldCoupon?.duration?.start) > dayjs(data?.duration.start)\n\t\t) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\tmessage: `Don't allow updating coupon to have earlier start date/time than the original coupon`,\n\t\t\t});\n\t\t}\n\n\t\tif (\n\t\t\tdata.couponType != CouponType.REFERRAL_CODE &&\n\t\t\tdata?.duration &&\n\t\t\tdayjs(data?.duration?.start) > dayjs(data?.duration.end)\n\t\t) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\tmessage: `End date/time must be after start date/time`,\n\t\t\t});\n\t\t}\n\n\t\tif (checkCouponCode) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'CONFLICT',\n\t\t\t\tmessage: `Coupon code already exists`,\n\t\t\t});\n\t\t}\n\n\t\tswitch (data.couponType) {\n\t\t\tcase CouponType.GLOBAL: {\n\t\t\t\tcoupon = await globalCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst globalCoupon = coupon as DocumentType<GlobalCoupon>;\n\t\t\t\t\tif (!globalCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.exchangeCouponForMultipleUser(\n\t\t\t\t\t\t\t{ _id: { $in: usersWithOldCoupon?.map(u => u._id) } },\n\t\t\t\t\t\t\toldCoupon._id,\n\t\t\t\t\t\t\tcoupon._id\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CouponType.SHOPS_CATEGORIES: {\n\t\t\t\tcoupon = await shopsCategoriesCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst shopsCategoriesCoupon = coupon as DocumentType<ShopsCategoriesCoupon>;\n\t\t\t\t\tif (!shopsCategoriesCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.exchangeCouponForMultipleUser(\n\t\t\t\t\t\t\t{ _id: { $in: usersWithOldCoupon?.map(u => u._id) } },\n\t\t\t\t\t\t\toldCoupon._id,\n\t\t\t\t\t\t\tshopsCategoriesCoupon._id\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CouponType.INDIVIDUAL_STORE: {\n\t\t\t\tcoupon = await individualStoreCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst individualStoreCoupon = coupon as DocumentType<IndividualStoreCoupon>;\n\t\t\t\t\tif (!individualStoreCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.exchangeCouponForMultipleUser(\n\t\t\t\t\t\t\t{ _id: { $in: usersWithOldCoupon?.map(u => u._id) } },\n\t\t\t\t\t\t\toldCoupon._id,\n\t\t\t\t\t\t\tindividualStoreCoupon._id\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CouponType.INDIVIDUAL_USER: {\n\t\t\t\tcoupon = await individualUserCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst individualUserCoupon = coupon as DocumentType<IndividualUserCoupon>;\n\t\t\t\t\tawait this.removeCouponFromMultipleUser(\n\t\t\t\t\t\t{ _id: { $in: usersWithOldCoupon?.map(u => u._id) } },\n\t\t\t\t\t\toldCoupon._id\n\t\t\t\t\t);\n\t\t\t\t\tawait this.assignCouponToMultipleUser(\n\t\t\t\t\t\t{ _id: { $in: individualUserCoupon.users } },\n\t\t\t\t\t\tindividualUserCoupon._id\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CouponType.CUSTOM_COUPON: {\n\t\t\t\tcoupon = await customCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst customCoupon = coupon as DocumentType<CustomCoupon>;\n\t\t\t\t\tif (!customCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.exchangeCouponForMultipleUser(\n\t\t\t\t\t\t\t{ _id: { $in: usersWithOldCoupon?.map(u => u._id) } },\n\t\t\t\t\t\t\toldCoupon._id,\n\t\t\t\t\t\t\tcoupon._id\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\t\tmessage: `Invalid coupon type`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (!coupon) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\tmessage: `Could create updated coupon`,\n\t\t\t});\n\t\t}\n\n\t\t// add previous version to new coupon\n\t\tconst previousVersions = oldCoupon?.previousVersions || [];\n\t\tpreviousVersions.push(oldCoupon._id);\n\n\t\tconst updatedCoupon = await this.baseCouponModel.findByIdAndUpdate(\n\t\t\tcoupon._id,\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tpreviousVersions,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\n\t\tif (!updatedCoupon) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: `Could not set previous versions of coupon`,\n\t\t\t});\n\t\t}\n\t\t// update old coupon\n\t\tconst updatedOldCoupon = await this.baseCouponModel.findByIdAndUpdate(\n\t\t\toldCoupon._id,\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tupdatedVersion: coupon._id,\n\t\t\t\t\t'duration.end': coupon.duration.end,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\n\t\treturn updatedCoupon;\n\t}\n\n\tpublic async updateStatus(id: string, status: Status): Promise<DocumentType<Model>> {\n\t\tconst coupon = await this.baseCouponModel.findByIdAndUpdate(\n\t\t\tid,\n\t\t\t{\n\t\t\t\t$set: { status },\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\n\t\tif (!coupon) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'NOT_FOUND',\n\t\t\t\tmessage: 'Coupon not found',\n\t\t\t});\n\t\t}\n\n\t\t// also update the status of previous versions of the coupon\n\t\tconst previousVersions = coupon.previousVersions;\n\t\tif (previousVersions && previousVersions.length > 0) {\n\t\t\tawait this.baseCouponModel.updateMany(\n\t\t\t\t{ _id: { $in: previousVersions } },\n\t\t\t\t{\n\t\t\t\t\t$set: { status },\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\n\t\treturn coupon;\n\t}\n\n\t/**\n\t * Delete record\n\t * @param data Data for delete\n\t */\n\tpublic async deleteById(data: DeleteDTO): Promise<string> {\n\t\tconst { _id, softDelete } = data;\n\n\t\tconst coupon = await this.model.findById(_id);\n\n\t\tif (!coupon) {\n\t\t\tnotFoundError('Coupon not found');\n\t\t}\n\n\t\tconst result = await this.model.deleteRecord({ _id, deletedAt: null }, softDelete);\n\t\tif (!result) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'NOT_FOUND',\n\t\t\t\tmessage: 'Record not found',\n\t\t\t});\n\t\t}\n\n\t\t// remove coupons from users' coupon lists\n\t\tthis.removeCouponFromMultipleUser({}, _id);\n\n\t\t// also delete previous versions of the coupon\n\t\tconst previousVersions = coupon.previousVersions;\n\t\tif (previousVersions && previousVersions.length > 0) {\n\t\t\tawait this.model.deleteRecord({ _id: { $in: previousVersions }, deletedAt: null }, softDelete);\n\t\t}\n\n\t\treturn 'Record deleted successfully';\n\t}\n\n\t/**\n\t * Get User Coupons\n\t * @param data User and pagination data\n\t */\n\tpublic async getUserCoupons(\n\t\tuser: mongoose.Types.ObjectId | undefined,\n\t\tshop: mongoose.Types.ObjectId | undefined,\n\t\tpage: number = 0,\n\t\tsize: number = 0\n\t): Promise<{\n\t\tavailable: Array<DocumentType<Model>>;\n\t\tused: Array<DocumentType<Model>>;\n\t\texpired: Array<DocumentType<Model>>;\n\t}> {\n\t\tconst couponRepository = new CouponRepository();\n\t\tlet itemType: ItemType | undefined = undefined;\n\t\tif (shop) {\n\t\t\tconst shopDocument = await this.shopModel.findOne({ _id: shop }).select('itemType');\n\t\t\titemType = shopDocument?.itemType;\n\t\t}\n\t\tconst coupons = await couponRepository.getUserCoupons(user, shop, itemType);\n\n\t\tif (shop && user) {\n\t\t\tconst punch = await this.punchHistoryService.getPunchCoupon(user, shop);\n\t\t\tif (punch) {\n\t\t\t\tcoupons.available.push(punch);\n\t\t\t}\n\t\t}\n\n\t\treturn couponRepository.addLabelsToAllCoupons(coupons);\n\t}\n\n\tpublic async validateCoupon(data: ValidateCouponDTO): Promise<CouponValidationOutputDTO> {\n\t\tif (data.coupon === 'punch') {\n\t\t\treturn await punchMarketingHistoryService.getPunchDiscount(data);\n\t\t}\n\n\t\tconst user = await this.userModel.findById(data.user);\n\t\tif (!user) notFoundError('User not found');\n\n\t\tlet coupon = await this.model.findOne({\n\t\t\tcode: data.coupon,\n\t\t\t_id: { $in: user.coupons ?? [] },\n\t\t\tstatus: { $in: [Status.ACTIVE, null] },\n\t\t});\n\n\t\tif (!coupon) {\n\t\t\tcoupon = await this.model.findOne({\n\t\t\t\tcode: data.coupon,\n\t\t\t\tstatus: { $in: [Status.ACTIVE, null] },\n\t\t\t\tcouponType: { $in: [CouponType.REFERRAL_CODE, CouponType.CUSTOM_COUPON] },\n\t\t\t\tupdatedVersion: { $exists: false },\n\t\t\t});\n\n\t\t\tif (!coupon) {\n\t\t\t\tnotFoundError('Coupon not found');\n\t\t\t}\n\t\t}\n\n\t\tif (coupon.couponType == CouponType.REFERRAL_CODE) {\n\t\t\treturn await referralCodeCouponService.validateCoupon(data, coupon as DocumentType<ReferralCodeCoupon>);\n\t\t}\n\n\t\tconst baseCoupon = coupon as DocumentType<BaseCoupon>;\n\n\t\tconst { isValid, invalidMessage } = await this.validateBaseCoupon(\n\t\t\tbaseCoupon,\n\t\t\tuser._id,\n\t\t\tdata.amountBeforeCoupon,\n\t\t\tBoolean(data.scheduledAt) ? dayjs(data.scheduledAt) : undefined\n\t\t);\n\n\t\tif (!isValid) {\n\t\t\treturn {\n\t\t\t\tisValid,\n\t\t\t\tmessage: invalidMessage,\n\t\t\t};\n\t\t}\n\n\t\tswitch (coupon.couponType) {\n\t\t\tcase CouponType.REFERRAL_REWARD:\n\t\t\t\treturn await referralRewardCouponService.validateCoupon(\n\t\t\t\t\tdata,\n\t\t\t\t\tcoupon as DocumentType<ReferralRewardCoupon>\n\t\t\t\t);\n\t\t\tcase CouponType.GLOBAL:\n\t\t\t\treturn await globalCouponService.validateCoupon(data, coupon as DocumentType<GlobalCoupon>);\n\t\t\tcase CouponType.SHOPS_CATEGORIES:\n\t\t\t\treturn await shopsCategoriesCouponService.validateCoupon(\n\t\t\t\t\tdata,\n\t\t\t\t\tcoupon as DocumentType<ShopsCategoriesCoupon>\n\t\t\t\t);\n\t\t\tcase CouponType.INDIVIDUAL_STORE:\n\t\t\t\treturn await individualStoreCouponService.validateCoupon(\n\t\t\t\t\tdata,\n\t\t\t\t\tcoupon as DocumentType<IndividualStoreCoupon>\n\t\t\t\t);\n\t\t\tcase CouponType.INDIVIDUAL_USER:\n\t\t\t\treturn await individualUserCouponService.validateCoupon(\n\t\t\t\t\tdata,\n\t\t\t\t\tcoupon as DocumentType<IndividualUserCoupon>\n\t\t\t\t);\n\t\t\tcase CouponType.CUSTOM_COUPON:\n\t\t\t\treturn await customCouponService.validateCoupon(data, coupon as DocumentType<CustomCoupon>);\n\t\t\tdefault:\n\t\t\t\tnotImplementedError(`Validation not implemented for ${coupon.couponType} coupons`);\n\t\t}\n\t}\n\n\tprivate isCouponExpired(coupon: DocumentType<BaseCoupon>): Boolean {\n\t\tif (coupon.expirationReason || (coupon?.duration?.end && new Date(coupon?.duration?.end) < new Date())) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t *\n\t * @param coupon Base coupon document\n\t * @param user ID of the user trying to user the coupon\n\t * @param orderAmount Order subtotal\n\t * @returns True if coupon is valid\n\t */\n\tprivate async validateBaseCoupon(\n\t\tcoupon: DocumentType<BaseCoupon>,\n\t\tuser: mongoose.Types.ObjectId,\n\t\torderAmount: number,\n\t\tscheduledAt: Dayjs | undefined = undefined\n\t): Promise<{ isValid: boolean; invalidMessage?: string }> {\n\t\tconst invalidConditions = [\n\t\t\tthis.isCouponExpired(coupon), // check coupon expired\n\t\t\tcoupon.duration.start > dayjs().toDate(), // check coupon start\n\t\t\tcoupon.isMinOrderValueEnabled && coupon.minOrderValue && orderAmount < coupon.minOrderValue, // check minimum order value\n\t\t\tcoupon.forNewUserOnly && !(await this.verifyNewUserConditions(coupon, user)), // check if new user\n\t\t\tcoupon.isOrderLimitPerUserEnabled &&\n\t\t\t\tcoupon.orderLimitPerUser &&\n\t\t\t\t(await this.getCouponOrdersForUser(user, coupon.code)) >= coupon.orderLimitPerUser, // check order limit for user\n\t\t\tscheduledAt && Boolean(coupon.duration.end) && dayjs(coupon.duration.end).isBefore(scheduledAt), // check scheduledAt is before coupon end date\n\t\t];\n\n\t\tconst invalidMessages = [\n\t\t\t'This coupon is expired',\n\t\t\t'This coupon is not available yet',\n\t\t\t'The minimum order amount for this coupon is not met',\n\t\t\t'This coupon is for new users only',\n\t\t\t'You have reached the order limit for this coupon',\n\t\t\t'This coupon is not valid for this scheduled orders',\n\t\t];\n\n\t\tconst isValid = invalidConditions.every(value => Boolean(value) == false);\n\t\tconst invalidMessage = invalidMessages.filter((_, index) => invalidConditions[index])?.[0];\n\n\t\treturn { isValid, invalidMessage };\n\t}\n\n\t// Returns true if new user conditions are met. False otherwise\n\tprivate async verifyNewUserConditions(\n\t\tcoupon: DocumentType<BaseCoupon>,\n\t\tuser: mongoose.Types.ObjectId\n\t): Promise<boolean> {\n\t\tconst forNewUserOnly = coupon.forNewUserOnly;\n\t\tconst isOrderLimitPerUserEnabled = coupon.isOrderLimitPerUserEnabled;\n\t\tconst orderLimitPerUser = coupon.orderLimitPerUser;\n\n\t\tif (forNewUserOnly) {\n\t\t\tif (isOrderLimitPerUserEnabled && orderLimitPerUser) {\n\t\t\t\tconst orderCount = await couponHelperService.getSameDeviceOrders(user);\n\t\t\t\treturn orderLimitPerUser > orderCount;\n\t\t\t}\n\t\t\treturn await couponHelperService.isNewUser(user);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tprivate async getCouponOrdersForUser(user: mongoose.Types.ObjectId, couponCode: string): Promise<number> {\n\t\tconst orders = (await this.orderModel\n\t\t\t.find({\n\t\t\t\tuser: user,\n\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\torderType: OrderType.REGULAR,\n\t\t\t})\n\t\t\t.populate([{ path: 'cart' }])) as Array<DocumentType<RegularOrder> & { cart: DocumentType<Cart> }>;\n\n\t\tconst count = orders.filter(order => order.cart.couponCode == couponCode).length;\n\n\t\treturn count;\n\t}\n\n\tpublic async handleCouponExpiry(couponId: mongoose.Types.ObjectId) {\n\t\tconst coupon = await this.model.findById(couponId);\n\t\tif (!coupon || coupon.couponType == CouponType.REFERRAL_CODE) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst typedCoupon = coupon as DocumentType<BaseCoupon>;\n\t\tawait this.processCouponForExpiry(typedCoupon);\n\t}\n\n\tprivate async processCouponForExpiry(coupon: DocumentType<BaseCoupon>) {\n\t\tlet expirationReason: string | null = null;\n\n\t\tif (coupon.isTotalOrderLimitEnabled && coupon.totalOrderLimit) {\n\t\t\t// find the order count by aggregating the order collection,\n\t\t\t// checking orders that have adjustedFinance.pricing.couponDiscount > 0,\n\t\t\t// populating cart collection to match coupon code\n\n\t\t\tconst pipeline = [\n\t\t\t\t{\n\t\t\t\t\t$match: {\n\t\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\t\t'adjustedFinance.pricing.couponDiscount': { $gt: 0 },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$lookup: {\n\t\t\t\t\t\tfrom: 'carts',\n\t\t\t\t\t\tlocalField: 'cart',\n\t\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\t\tas: 'cart',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$unwind: '$cart',\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$match: {\n\t\t\t\t\t\t'cart.couponCode': coupon.code,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$count: 'orderCount',\n\t\t\t\t},\n\t\t\t];\n\t\t\tconst result = await this.orderModel.aggregate(pipeline);\n\t\t\tconst orderCount = result[0]?.orderCount ?? 0;\n\n\t\t\tif (orderCount >= coupon.totalOrderLimit) {\n\t\t\t\texpirationReason = CouponExpirationReason.TOTAL_ORDER_LIMIT;\n\t\t\t}\n\t\t}\n\t\tif (coupon.isSpendLimitEnabled && coupon.spendLimit) {\n\t\t\t// spend limit\n\n\t\t\tconst { totalCouponDiscount, totalSecondaryCouponDiscount } = await this.getCouponDiscountTotals(\n\t\t\t\tcoupon.code\n\t\t\t);\n\n\t\t\tif (totalCouponDiscount >= coupon.spendLimit) {\n\t\t\t\texpirationReason = CouponExpirationReason.SPEND_LIMIT;\n\t\t\t}\n\t\t}\n\n\t\tawait this.baseCouponModel.findByIdAndUpdate(\n\t\t\tcoupon._id,\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\texpirationReason,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async syncCouponExpiry() {\n\t\tconst coupons = await this.baseCouponModel.find({\n\t\t\tcouponType: { $ne: CouponType.REFERRAL_CODE },\n\t\t\texpirationReason: null,\n\t\t});\n\n\t\tconsole.log(`Syncing expiry for ${coupons.length} coupons`);\n\n\t\tconsole.time('syncCouponExpiry');\n\t\tfor (const coupon of coupons) {\n\t\t\tconsole.time(`Processing coupon ${coupon.code}`);\n\t\t\tawait this.processCouponForExpiry(coupon);\n\t\t\tconsole.timeEnd(`Processing coupon ${coupon.code}`);\n\t\t}\n\t\tconsole.timeEnd('syncCouponExpiry');\n\t}\n\n\tprivate async findCouponByCode(code: string): Promise<DocumentType<Model> | null> {\n\t\tconst coupon = await this.model.findOne({ code: code, updatedVersion: { $exists: false } });\n\t\tif (!coupon) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'NOT_FOUND',\n\t\t\t\tmessage: 'Coupon not found',\n\t\t\t});\n\t\t}\n\t\treturn coupon;\n\t}\n\n\tprivate async getCouponDiscountTotals(couponCode: string) {\n\t\tconst pipeline = [\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\t'adjustedFinance.pricing.couponDiscount': { $gt: 0 },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'carts',\n\t\t\t\t\tlocalField: 'cart',\n\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\tas: 'cart',\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t$unwind: '$cart',\n\t\t\t},\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t'cart.couponCode': couponCode,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: null,\n\t\t\t\t\ttotalCouponDiscount: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$toDouble: {\n\t\t\t\t\t\t\t\t$ifNull: ['$adjustedFinance.pricing.couponDiscount', 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\ttotalSecondaryCouponDiscount: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$toDouble: {\n\t\t\t\t\t\t\t\t$ifNull: ['$adjustedFinance.pricing.secondaryCouponDiscount', 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\tconst result = await this.orderModel.aggregate(pipeline);\n\n\t\treturn {\n\t\t\ttotalCouponDiscount: result[0]?.totalCouponDiscount ?? 0,\n\t\t\ttotalSecondaryCouponDiscount: result[0]?.totalSecondaryCouponDiscount ?? 0,\n\t\t};\n\t}\n\n\tprivate async assignCouponToUser(user: mongoose.Types.ObjectId, coupon: mongoose.Types.ObjectId) {\n\t\tconst updatedUser = await this.userModel.findByIdAndUpdate(\n\t\t\tuser,\n\t\t\t{\n\t\t\t\t$push: {\n\t\t\t\t\tcoupons: coupon,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\t}\n\n\tprivate async assignCouponToMultipleUser(\n\t\tquery: mongoose.FilterQuery<User>,\n\t\tcoupon: mongoose.Types.ObjectId\n\t) {\n\t\tconsole.log('Assigning coupon to multiple users with coupon:', coupon);\n\t\tconst updatedUsers = await this.userModel.updateMany(query, {\n\t\t\t$push: {\n\t\t\t\tcoupons: coupon,\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate async assignCouponToNewUsers(coupon: mongoose.Types.ObjectId) {\n\t\tconsole.log('Assigning coupon to new users', coupon);\n\n\t\tconst newUsers = await couponHelperService.getNewUsers();\n\t\tconst updatedUsers = await this.userModel.updateMany(\n\t\t\t{ _id: { $in: newUsers.map(user => user._id) } },\n\t\t\t{\n\t\t\t\t$push: {\n\t\t\t\t\tcoupons: coupon,\n\t\t\t\t},\n\t\t\t}\n\t\t);\n\t}\n\n\tprivate async removeCouponFromUser(user: mongoose.Types.ObjectId, coupon: mongoose.Types.ObjectId) {\n\t\tconst updatedUser = await this.userModel.findByIdAndUpdate(\n\t\t\tuser,\n\t\t\t{\n\t\t\t\t$pull: {\n\t\t\t\t\tcoupons: coupon,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\t}\n\n\tprivate async removeCouponFromMultipleUser(\n\t\tquery: mongoose.FilterQuery<User>,\n\t\tcoupon: mongoose.Types.ObjectId\n\t) {\n\t\tconst updatedUsers = await this.userModel.updateMany(query, {\n\t\t\t$pull: {\n\t\t\t\tcoupons: coupon,\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate throwBadRequest(message: string): never {\n\t\tthrow new TRPCError({\n\t\t\tcode: 'BAD_REQUEST',\n\t\t\tmessage,\n\t\t});\n\t}\n\n\tpublic async addCouponToUser(user: any, couponCode: string): Promise<DocumentType<Model>> {\n\t\tconst coupon = await this.findCouponByCode(couponCode);\n\t\tif (!coupon) {\n\t\t\tthis.throwBadRequest('Coupon not found');\n\t\t}\n\t\tconst isNewUser = await couponHelperService.isNewUser(new mongoose.Types.ObjectId(user));\n\n\t\tif (coupon.couponType == CouponType.REFERRAL_CODE && !isNewUser) {\n\t\t\tthis.throwBadRequest('This coupon is valid for new users only');\n\t\t}\n\n\t\tif (coupon.couponType == CouponType.REFERRAL_CODE) {\n\t\t\tif ((coupon as DocumentType<ReferralCodeCoupon>).referralUser.toString() == user) {\n\t\t\t\tthis.throwBadRequest('You cannot add your own referral code');\n\t\t\t}\n\t\t}\n\n\t\tconst typedCoupon = coupon as DocumentType<BaseCoupon>;\n\n\t\tif (this.isCouponExpired(typedCoupon)) {\n\t\t\tthis.throwBadRequest('This coupon has expired and cannot be added');\n\t\t}\n\n\t\tif (typedCoupon.forNewUserOnly && !isNewUser) {\n\t\t\tthis.throwBadRequest('This coupon is valid for new users only');\n\t\t}\n\n\t\tconst alreadyApplied = await this.hasUserAlreadyAppliedCoupon(user, typedCoupon);\n\t\tif (alreadyApplied) {\n\t\t\tthis.throwBadRequest('Coupon already applied to user');\n\t\t}\n\n\t\tif (typedCoupon.couponType == CouponType.INDIVIDUAL_USER) {\n\t\t\tif (!(typedCoupon as DocumentType<IndividualUserCoupon>).users?.includes(user)) {\n\t\t\t\tthis.throwBadRequest('This coupon is not assigned to this user');\n\t\t\t}\n\t\t}\n\n\t\tawait this.userModel.findByIdAndUpdate(\n\t\t\tuser,\n\t\t\t{ $push: { coupons: typedCoupon._id } },\n\t\t\t{ new: true, runValidators: true }\n\t\t);\n\n\t\treturn coupon;\n\t}\n\n\tprivate async hasUserAlreadyAppliedCoupon(\n\t\tuserId: mongoose.Types.ObjectId,\n\t\tcoupon: DocumentType<BaseCoupon>\n\t): Promise<boolean> {\n\t\tconst couponIds = [coupon._id, ...(coupon.previousVersions ?? []).map(v => v._id)];\n\n\t\tconst user = await this.userModel.exists({\n\t\t\t_id: userId,\n\t\t\tcoupons: { $in: couponIds },\n\t\t});\n\n\t\treturn !!user;\n\t}\n\n\tprivate async exchangeCouponForMultipleUser(\n\t\tquery: mongoose.FilterQuery<User>,\n\t\toldCoupon: mongoose.Types.ObjectId,\n\t\tnewCoupon: mongoose.Types.ObjectId\n\t) {\n\t\tawait this.removeCouponFromMultipleUser(query, oldCoupon);\n\t\tawait this.assignCouponToMultipleUser(query, newCoupon);\n\t}\n\n\tpublic getShareableLink = async (code: string): Promise<ShareableLinkDTO> => {\n\t\tconst secretsService = getLibraries().getSecretsService();\n\t\tconst deepLinkUrl = (await secretsService.getKey('DEEP_LINK_URL')) ?? 'https://link.lyxa.ai';\n\n\t\tconst link = `${deepLinkUrl}/invite/${code}`;\n\n\t\tconst message = `Download Lyxa and explore the wide variety of offerings and benefits! Use my code at checkout to claim a special coupon : ${code}.\n\t\t${link}`;\n\n\t\treturn { link, message };\n\t};\n\n\tpublic async getUserCouponList(data?: Partial<FilterDTO>): Promise<PaginatedResponse<AllCouponsDTO>> {\n\t\ttry {\n\t\t\tlet query = data?.query || {};\n\n\t\t\tif (!query.user) {\n\t\t\t\tbadRequestError('User ID is required in query');\n\t\t\t}\n\n\t\t\tconst select = data?.select || {\n\t\t\t\t_id: 1,\n\t\t\t\t'createdBy.name': 1,\n\t\t\t\t'duration.start': 1,\n\t\t\t\t'duration.end': 1,\n\t\t\t\tcode: 1,\n\t\t\t\tstatus: 1,\n\t\t\t\tcreatedAt: 1,\n\t\t\t\tcouponType: 1,\n\t\t\t};\n\n\t\t\tlet isExpiredField = null;\n\n\t\t\tif (query.status) {\n\t\t\t\tif (query.status === 'expired') {\n\t\t\t\t\tisExpiredField = true;\n\t\t\t\t\tdelete query.status;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (query.createdAt) {\n\t\t\t\t// convert to date range\n\t\t\t\tif ('$gte' in query.createdAt) {\n\t\t\t\t\tquery.createdAt.$gte = new Date(query.createdAt.$gte);\n\t\t\t\t}\n\t\t\t\tif ('$lte' in query.createdAt) {\n\t\t\t\t\tquery.createdAt.$lte = new Date(query.createdAt.$lte);\n\t\t\t\t}\n\t\t\t\tif ('$gt' in query.createdAt) {\n\t\t\t\t\tquery.createdAt.$gt = new Date(query.createdAt.$gt);\n\t\t\t\t}\n\t\t\t\tif ('$lt' in query.createdAt) {\n\t\t\t\t\tquery.createdAt.$lt = new Date(query.createdAt.$lt);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst user = await this.userModel.findById(query.user).select('coupons');\n\t\t\tquery._id = { $in: user?.coupons ?? [] };\n\t\t\tdelete query.user; // remove user from query to avoid issues in aggregation match stage\n\n\t\t\tconst pipeline: any[] = [\n\t\t\t\t{ $match: { ...query, deletedAt: null } }, // Filter by search query\n\t\t\t\t{\n\t\t\t\t\t$lookup: {\n\t\t\t\t\t\t// INNER JOIN on categories\n\t\t\t\t\t\tfrom: 'admins', // Mongoose auto-pluralizes collection names\n\t\t\t\t\t\tlocalField: 'createdBy',\n\t\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\t\tas: 'createdBy',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ $unwind: { path: '$createdBy', preserveNullAndEmptyArrays: true } }, // Flatten the array\n\t\t\t\t{\n\t\t\t\t\t$addFields: {\n\t\t\t\t\t\tisExpired: {\n\t\t\t\t\t\t\t$cond: {\n\t\t\t\t\t\t\t\tif: {\n\t\t\t\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t\t\t\t{ $ifNull: ['$duration.end', false] },\n\t\t\t\t\t\t\t\t\t\t\t\t{ $lt: ['$duration.end', dayjs().toDate()] },\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t{ $ifNull: ['$expirationReason', false] },\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\tthen: true,\n\t\t\t\t\t\t\t\telse: false,\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$match: isExpiredField\n\t\t\t\t\t\t? { isExpired: true }\n\t\t\t\t\t\t: query.status === 'active'\n\t\t\t\t\t\t\t? { isExpired: false }\n\t\t\t\t\t\t\t: {},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$addFields: {\n\t\t\t\t\t\tstatus: {\n\t\t\t\t\t\t\t$cond: {\n\t\t\t\t\t\t\t\tif: { $eq: ['$isExpired', true] },\n\t\t\t\t\t\t\t\tthen: 'expired',\n\t\t\t\t\t\t\t\telse: '$status',\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$project: select,\n\t\t\t\t},\n\t\t\t];\n\n\t\t\tif (data?.search?.searchKey) {\n\t\t\t\tconst searchKey = data.search.searchKey;\n\t\t\t\tconst regex = new RegExp(searchKey, 'i'); // case-insensitive search\n\t\t\t\tconst fields = data.search.searchFields?.length ? data.search.searchFields : ['code']; // default field(s) to search in\n\n\t\t\t\tpipeline.push({\n\t\t\t\t\t$match: {\n\t\t\t\t\t\t$or: fields.map(field => ({ [field]: { $regex: regex } })),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Execute the aggregation with pagination and sorting\n\t\t\tconst results = await paginateAggregation(this.model, pipeline, data?.page, data?.size, data?.sort);\n\n\t\t\treturn results as unknown as PaginatedResponse<AllCouponsDTO>;\n\t\t} catch (err) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: `err: ${err}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic async addExistingCouponsToNewUser(userId: mongoose.Types.ObjectId) {\n\t\tconst isNewUser = await couponHelperService.isNewUser(userId);\n\n\t\tconst query: any = {\n\t\t\tcouponType: { $in: [CouponType.GLOBAL, CouponType.INDIVIDUAL_STORE, CouponType.SHOPS_CATEGORIES] },\n\t\t\tdeletedAt: null,\n\t\t\texpirationReason: null,\n\t\t\t$or: [\n\t\t\t\t{ 'duration.end': { $gt: dayjs().toDate() } },\n\t\t\t\t{ 'duration.end': { $exists: false } },\n\t\t\t\t{ 'duration.end': null },\n\t\t\t],\n\t\t\tupdatedVersion: { $exists: false },\n\t\t};\n\n\t\tif (!isNewUser) {\n\t\t\tquery.forNewUserOnly = { $ne: true };\n\t\t}\n\n\t\t// assign all coupons that are not expired\n\t\tconst coupons = await this.baseCouponModel.find(query);\n\n\t\tconst couponIds = coupons.map(coupon => coupon._id);\n\n\t\tawait this.userModel.findByIdAndUpdate(\n\t\t\tuserId,\n\t\t\t{\n\t\t\t\t$addToSet: {\n\t\t\t\t\tcoupons: { $each: couponIds },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getActiveNewUserCoupon(): Promise<DocumentType<BaseCoupon> | null> {\n\t\tconst currentDate = dayjs().toDate();\n\t\tconst activeForNewUserCoupon = await this.baseCouponModel.findOne({\n\t\t\tcouponType: CouponType.GLOBAL,\n\t\t\tforNewUserOnly: true,\n\t\t\tdeletedAt: null,\n\t\t\t$or: [\n\t\t\t\t{\n\t\t\t\t\texpirationReason: { $exists: false },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\texpirationReason: null,\n\t\t\t\t},\n\t\t\t],\n\t\t\t'duration.end': { $gte: currentDate },\n\t\t\tupdatedVersion: { $exists: false },\n\t\t});\n\n\t\treturn activeForNewUserCoupon;\n\t}\n\n\tpublic async checkExistingNewUserCoupon(): Promise<CheckExistingNewUserCouponOutputDTO> {\n\t\tconst alreadyActiveForNewUserCoupon = await this.getActiveNewUserCoupon();\n\n\t\tif (alreadyActiveForNewUserCoupon) {\n\t\t\treturn { exists: true };\n\t\t}\n\n\t\treturn { exists: false };\n\t}\n\n\tprivate async getAllOrders(userIds: mongoose.Types.ObjectId[]): Promise<number> {\n\t\treturn await this.orderModel.countDocuments({\n\t\t\tuser: { $in: userIds },\n\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\torderType: OrderType.REGULAR,\n\t\t});\n\t}\n\n\tpublic async handleCouponGiftBox(\n\t\tdeviceId: string,\n\t\tuserId: mongoose.Types.ObjectId | null\n\t): Promise<DocumentType<GlobalCoupon>[]> {\n\t\tconst couponRepository = new CouponRepository();\n\n\t\t// 1. Get all the user id using device id\n\t\tconst allUsers = await this.userModel.find({ deviceId }).select('_id');\n\n\t\t// 2. Make an array using all the user ids\n\t\tconst userIds = allUsers.map(user => user._id);\n\n\t\t// 3. Append the current user id to the array\n\t\tif (userId) {\n\t\t\tuserIds.push(new mongoose.Types.ObjectId(userId));\n\t\t}\n\n\t\t// 4. Find how many orders placed by these user ids\n\t\tconst totalOrders = await this.getAllOrders(userIds);\n\n\t\t// 5. Get coupon details\n\t\tconst activeNewUserCoupon = await this.getActiveNewUserCoupon();\n\t\tif (!activeNewUserCoupon) {\n\t\t\tnotFoundError('No active new user coupon found');\n\t\t}\n\n\t\t// 6. Check the total order quantity less than to order limit per user\n\t\tif (\n\t\t\tactiveNewUserCoupon.isOrderLimitPerUserEnabled &&\n\t\t\ttotalOrders < (activeNewUserCoupon.orderLimitPerUser || 0)\n\t\t) {\n\t\t\treturn couponRepository.addLabelsToCoupons([activeNewUserCoupon.toJSON()]);\n\t\t}\n\n\t\tnotFoundError('No gift box coupon available');\n\n\t\treturn [];\n\t}\n\n\tpublic async updateCouponGiftBoxShown(userId: mongoose.Types.ObjectId, data: any): Promise<number> {\n\t\tconst result = await this.userModel.updateOne(\n\t\t\t{ _id: userId },\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tisNewUserCouponShowed: data.isNewUserGiftBoxShown,\n\t\t\t\t},\n\t\t\t}\n\t\t);\n\n\t\treturn result.modifiedCount;\n\t}\n}\n\nexport const couponService = Container.get(CouponService);\n"]}
1
+ {"version":3,"file":"coupon.service.js","sourceRoot":"/","sources":["modules/coupon/services/coupon.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAA4C;AAC5C,yCAAyC;AACzC,oDAA4F;AAC5F,sEAqBmD;AAenD,wEAIiD;AAEjD,wBAOW;AACX,4DAQ2C;AAC3C,sEAAwF;AACxF,wEAGmD;AACnD,wCAA6C;AAE7C,6EAA0E;AAC1E,4EAMmD;AACnD,uFAAiF;AACjF,qDAA4E;AAC5E,8DAAkE;AAClE,oEAAwE;AACxE,gEAA6E;AAC7E,gHAAkH;AAG3G,IAAM,aAAa,GAAnB,MAAM,aAAa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AC;QAEF,OAAO,MAAM,CAAC,aAAa,CAAC;IAC7B,CAAC;IAEM,KAAK,CAAC,wBAAwB,CAAC,MAA+B,EAAE,IAAS;QAE/E,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QAGnD,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS;aAChC,IAAI,CAAC,EAAC,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAC,CAAC;aAChC,MAAM,CAAC,KAAK,CAAC;aACb,IAAI,EAAE,CAAA;QAGR,MAAM,OAAO,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAGtC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,UAAU,CAC7C,EAAE,GAAG,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,EACzB;YACC,IAAI,EAAE;gBACL,qBAAqB,EAAE,IAAI,CAAC,qBAAqB;aACjD;SACD,CACD,CAAC;QAEF,OAAO,MAAM,CAAC,aAAa,CAAC;IAC7B,CAAC;CACD,CAAA;AA/3CY,sCAAa;wBAAb,aAAa;IADzB,IAAA,gBAAO,GAAE;;GACG,aAAa,CA+3CzB;AAEY,QAAA,aAAa,GAAG,gBAAS,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC","sourcesContent":["import Container, { Service } from 'typedi';\nimport { TRPCError } from '@trpc/server';\nimport { DocumentType, mongoose, queryMethod, ReturnModelType } from '@typegoose/typegoose';\nimport {\n\tCart,\n\tCouponModel,\n\tCustomCoupon,\n\tgetCoreUserModel,\n\tGlobalCoupon,\n\tIndividualStoreCoupon,\n\tIndividualUserCoupon,\n\tCoupon as Model,\n\tReferralRewardCoupon,\n\tReferralRewardCouponModel,\n\tRegularOrder,\n\tRegularOrderModel,\n\tShopModel,\n\tShop,\n\tShopsCategoriesCoupon,\n\tUser,\n\tUserModel,\n\tReferralCodeCoupon,\n\tReferralSetting,\n\tReferralSettingModel,\n} from '@lyxa.ai/core/dist/libraries/mongo/models';\nimport {\n\tAllCouponsValidationDTO,\n\tCouponValidationOutputDTO,\n\tValidateCouponDTO,\n\tAllCouponsDTO,\n\tCheckExistingNewUserCouponOutputDTO,\n} from '@modules/coupon/validations';\nimport { SoftDeleteModel } from '@lyxa.ai/core/dist/libraries/mongo/plugins/soft-delete-plugin';\nimport {\n\tFilterDTO,\n\tPaginatedResponse,\n\tDeleteDTO,\n\tShareableLinkDTO,\n} from '@lyxa.ai/core/dist/utilities/validation';\nimport {\n\tcreateRawDocumentPaginatorObject,\n\tpaginateAggregation,\n\tPaginatorOptions,\n} from '@lyxa.ai/core/dist/utilities/pagination';\nimport { ModelType } from '@typegoose/typegoose/lib/types';\nimport {\n\tcustomCouponService,\n\tglobalCouponService,\n\tindividualStoreCouponService,\n\tindividualUserCouponService,\n\treferralCodeCouponService,\n\treferralRewardCouponService,\n} from '.';\nimport {\n\tCouponExpirationReason,\n\tCouponType,\n\tItemType,\n\tOrderType,\n\tRegularOrderStatus,\n\tStatus,\n\tValueType,\n} from '@lyxa.ai/core/dist/utilities/enum';\nimport { BaseCoupon, BaseCouponModel } from '@lyxa.ai/core/dist/libraries/mongo/models';\nimport {\n\tPunchMarketingHistoryService,\n\tpunchMarketingHistoryService,\n} from '@modules/punch-marketing-history/services';\nimport { getLibraries } from '@lyxa.ai/core';\nimport { NotificationMicroserviceRouter } from '@lyxa.ai/notification';\nimport { CouponRepository } from './patterns/repository/CouponRepository';\nimport {\n\tbadRequestError,\n\tconflictError,\n\tinternalServerError,\n\tnotFoundError,\n\tnotImplementedError,\n} from '@lyxa.ai/core/dist/utilities/error-common';\nimport { shopsCategoriesCouponService } from './shops-categories-coupon.service';\nimport { CouponHelperService, couponHelperService } from './helper.service';\nimport { Dayjs, dayjs } from '@lyxa.ai/core/dist/utilities/dayjs';\nimport { getExchangeRate } from '@lyxa.ai/core/dist/utilities/currency';\nimport { roundSecondaryCurrency } from '@lyxa.ai/core/dist/utilities/shared';\nimport { getRoundSecondaryCurrencyStage } from '@lyxa.ai/core/dist/utilities/pipelines/common-pipeline-functions';\n\n@Service()\nexport class CouponService {\n\tprivate model: typeof CouponModel & SoftDeleteModel<Model>;\n\tprivate baseCouponModel: typeof BaseCouponModel & SoftDeleteModel<BaseCoupon>;\n\tprivate userModel: typeof UserModel & SoftDeleteModel<User>;\n\tprivate orderModel: typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\n\tprivate shopModel: typeof ShopModel & SoftDeleteModel<Shop>;\n\tprivate referralRewardModel: typeof ReferralRewardCouponModel & SoftDeleteModel<ReferralRewardCoupon>;\n\tprivate punchHistoryService: PunchMarketingHistoryService;\n\tprivate _coreUserModel: ReturnType<typeof getCoreUserModel> | null = null;\n\tprivate couponHelper: CouponHelperService;\n\tprivate readonly referralSettingsModel: typeof ReferralSettingModel & SoftDeleteModel<ReferralSetting>;\n\n\tconstructor() {\n\t\tthis.model = CouponModel as typeof CouponModel & SoftDeleteModel<Model>;\n\t\tthis.baseCouponModel = BaseCouponModel as typeof BaseCouponModel & SoftDeleteModel<BaseCoupon>;\n\t\tthis.userModel = UserModel as typeof UserModel & SoftDeleteModel<User>;\n\t\tthis.orderModel = RegularOrderModel as typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\n\t\tthis.shopModel = ShopModel as typeof ShopModel & SoftDeleteModel<Shop>;\n\t\tthis.referralRewardModel = ReferralRewardCouponModel as typeof ReferralRewardCouponModel &\n\t\t\tSoftDeleteModel<ReferralRewardCoupon>;\n\t\tthis.punchHistoryService = punchMarketingHistoryService;\n\t\tthis.couponHelper = couponHelperService;\n\t\tthis.referralSettingsModel = ReferralSettingModel as typeof ReferralSettingModel &\n\t\t\t\t\tSoftDeleteModel<ReferralSetting>;\n\t}\n\n\tprivate get coreUserModel() {\n\t\tif (!this._coreUserModel) {\n\t\t\tthis._coreUserModel = getCoreUserModel();\n\t\t}\n\t\treturn this._coreUserModel;\n\t}\n\n\t/**\n\t * Create a new record\n\t * @param data Data for the new record\n\t */\n\tpublic async create(data: AllCouponsValidationDTO): Promise<DocumentType<Model>> {\n\t\tlet coupon: DocumentType<Model>;\n\n\t\tif (\n\t\t\tdata.couponType != CouponType.REFERRAL_CODE &&\n\t\t\tdata?.duration &&\n\t\t\t!this.couponHelper.isDurationValid(dayjs(data?.duration?.start), dayjs(data?.duration?.end))\n\t\t) {\n\t\t\tconflictError(`Start date/time cannot be in the past `);\n\t\t}\n\n\t\tconst checkCoupon = await this.model.findOne({\n\t\t\tcode: data.code,\n\t\t\tdeletedAt: null,\n\t\t});\n\n\t\tif (checkCoupon) conflictError('Coupon code already exists');\n\n\t\tswitch (data.couponType) {\n\t\t\tcase CouponType.GLOBAL: {\n\t\t\t\tcoupon = await globalCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst globalCoupon = coupon as DocumentType<GlobalCoupon>;\n\t\t\t\t\tif (!globalCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.assignCouponToMultipleUser({}, coupon._id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.assignCouponToNewUsers(coupon._id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CouponType.REFERRAL_CODE: {\n\t\t\t\tcoupon = await referralCodeCouponService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CouponType.REFERRAL_REWARD: {\n\t\t\t\tcoupon = await referralRewardCouponService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CouponType.SHOPS_CATEGORIES: {\n\t\t\t\tcoupon = await shopsCategoriesCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst shopsCategoriesCoupon = coupon as DocumentType<ShopsCategoriesCoupon>;\n\t\t\t\t\tif (!shopsCategoriesCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.assignCouponToMultipleUser({}, coupon._id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.assignCouponToNewUsers(coupon._id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CouponType.INDIVIDUAL_STORE: {\n\t\t\t\tcoupon = await individualStoreCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst individualStoreCoupon = coupon as DocumentType<IndividualStoreCoupon>;\n\t\t\t\t\tif (!individualStoreCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.assignCouponToMultipleUser({}, coupon._id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.assignCouponToNewUsers(coupon._id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CouponType.INDIVIDUAL_USER: {\n\t\t\t\tcoupon = await individualUserCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst individualUserCoupon = coupon as DocumentType<IndividualUserCoupon>;\n\t\t\t\t\tconst users = individualUserCoupon.users;\n\t\t\t\t\tawait this.assignCouponToMultipleUser({ _id: { $in: users } }, coupon._id);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase CouponType.CUSTOM_COUPON: {\n\t\t\t\tcoupon = await customCouponService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tbadRequestError('Coupon type is not valid');\n\t\t\t}\n\t\t}\n\n\t\tif (!coupon) internalServerError('Could not create coupon');\n\n\t\t// Send Notification\n\t\tconst dispatcher = getLibraries().getMicroServiceDispatcher();\n\t\tconst notificationRouter =\n\t\t\tawait dispatcher.getMicroService<NotificationMicroserviceRouter>('notification');\n\n\t\tawait notificationRouter.notificationRouter.sendPushNotificationForCoupon.mutate(coupon._id);\n\n\t\treturn coupon;\n\t}\n\n\t/**\n\t * Get record by ID\n\t * @param id ID of the record\n\t */\n\tpublic async findById(id: string | mongoose.Types.ObjectId): Promise<DocumentType<Model>> {\n\t\tconst result = await this.model\n\t\t\t.findOne({\n\t\t\t\t_id: id,\n\t\t\t\tdeletedAt: null,\n\t\t\t})\n\t\t\t.populate([\n\t\t\t\t{\n\t\t\t\t\tpath: 'previousVersions',\n\t\t\t\t},\n\t\t\t]);\n\t\tif (!result) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'NOT_FOUND',\n\t\t\t\tmessage: 'Record not found',\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get records\n\t * @param query Query to find records\n\t */\n\tpublic async find(data?: Partial<FilterDTO>): Promise<PaginatedResponse<DocumentType<ModelType<Model>>>> {\n\t\ttry {\n\t\t\tconst populate = [\n\t\t\t\t...data?.populate,\n\t\t\t\t{\n\t\t\t\t\tpath: 'users',\n\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: 'coreUser',\n\t\t\t\t\t\t\tmodel: this.coreUserModel,\n\t\t\t\t\t\t\tselect: 'name profilePhoto -_id',\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tselect: 'coreUser phoneNumber',\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tpath: 'influencer',\n\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: 'coreUser',\n\t\t\t\t\t\t\tmodel: this.coreUserModel,\n\t\t\t\t\t\t\tselect: 'name profilePhoto -_id',\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tselect: 'coreUser phoneNumber',\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tpath: 'referralUser',\n\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: 'coreUser',\n\t\t\t\t\t\t\tmodel: this.coreUserModel,\n\t\t\t\t\t\t\tselect: 'name profilePhoto -_id',\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tselect: 'coreUser phoneNumber',\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tpath: 'user',\n\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: 'coreUser',\n\t\t\t\t\t\t\tmodel: this.coreUserModel,\n\t\t\t\t\t\t\tselect: 'name profilePhoto -_id',\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tselect: 'coreUser phoneNumber',\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tpath: 'referralCodeUsedBy',\n\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: 'coreUser',\n\t\t\t\t\t\t\tmodel: this.coreUserModel,\n\t\t\t\t\t\t\tselect: 'name profilePhoto -_id',\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tselect: 'coreUser phoneNumber',\n\t\t\t\t},\n\t\t\t];\n\n\t\t\tconst paginate = createRawDocumentPaginatorObject(this.model as ReturnModelType<typeof this.model>);\n\t\t\tconst options: PaginatorOptions<typeof Model> = {\n\t\t\t\tpage: data?.page,\n\t\t\t\tsize: data?.size,\n\t\t\t\tsort: data?.sort,\n\t\t\t\tquery: { ...data?.query, updatedVersion: { $exists: false } },\n\t\t\t\tselect: data?.select,\n\t\t\t\tpopulate: populate,\n\t\t\t};\n\t\t\tconst paginatedResult = await paginate(options);\n\t\t\treturn paginatedResult;\n\t\t} catch (err) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: `err: ${err}`,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Update record\n\t * @param id ID of the old coupon\n\t * @param data Data of the updated coupon\n\t */\n\tpublic async update(id: string, data: AllCouponsValidationDTO): Promise<DocumentType<Model>> {\n\t\tlet coupon: DocumentType<BaseCoupon> | null;\n\n\t\tconst [oldCoupon, checkCouponCode, usersWithOldCoupon] = await Promise.all([\n\t\t\tthis.baseCouponModel.findById(id),\n\t\t\tthis.model.findOne({\n\t\t\t\tcode: data.code,\n\t\t\t\t_id: { $ne: id },\n\t\t\t\tupdatedVersion: { $exists: false },\n\t\t\t}),\n\t\t\tthis.userModel\n\t\t\t\t.find({\n\t\t\t\t\tcoupons: new mongoose.Types.ObjectId(id),\n\t\t\t\t})\n\t\t\t\t.select(['_id', 'coupons']),\n\t\t]);\n\n\t\tif (!oldCoupon) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'NOT_FOUND',\n\t\t\t\tmessage: `Coupon not found`,\n\t\t\t});\n\t\t}\n\n\t\tif (\n\t\t\tdata.couponType != CouponType.REFERRAL_CODE &&\n\t\t\toldCoupon?.duration &&\n\t\t\tdayjs(oldCoupon?.duration?.start) > dayjs(data?.duration.start)\n\t\t) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\tmessage: `Don't allow updating coupon to have earlier start date/time than the original coupon`,\n\t\t\t});\n\t\t}\n\n\t\tif (\n\t\t\tdata.couponType != CouponType.REFERRAL_CODE &&\n\t\t\tdata?.duration &&\n\t\t\tdayjs(data?.duration?.start) > dayjs(data?.duration.end)\n\t\t) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\tmessage: `End date/time must be after start date/time`,\n\t\t\t});\n\t\t}\n\n\t\tif (checkCouponCode) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'CONFLICT',\n\t\t\t\tmessage: `Coupon code already exists`,\n\t\t\t});\n\t\t}\n\n\t\tswitch (data.couponType) {\n\t\t\tcase CouponType.GLOBAL: {\n\t\t\t\tcoupon = await globalCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst globalCoupon = coupon as DocumentType<GlobalCoupon>;\n\t\t\t\t\tif (!globalCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.exchangeCouponForMultipleUser(\n\t\t\t\t\t\t\t{ _id: { $in: usersWithOldCoupon?.map(u => u._id) } },\n\t\t\t\t\t\t\toldCoupon._id,\n\t\t\t\t\t\t\tcoupon._id\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CouponType.SHOPS_CATEGORIES: {\n\t\t\t\tcoupon = await shopsCategoriesCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst shopsCategoriesCoupon = coupon as DocumentType<ShopsCategoriesCoupon>;\n\t\t\t\t\tif (!shopsCategoriesCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.exchangeCouponForMultipleUser(\n\t\t\t\t\t\t\t{ _id: { $in: usersWithOldCoupon?.map(u => u._id) } },\n\t\t\t\t\t\t\toldCoupon._id,\n\t\t\t\t\t\t\tshopsCategoriesCoupon._id\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CouponType.INDIVIDUAL_STORE: {\n\t\t\t\tcoupon = await individualStoreCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst individualStoreCoupon = coupon as DocumentType<IndividualStoreCoupon>;\n\t\t\t\t\tif (!individualStoreCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.exchangeCouponForMultipleUser(\n\t\t\t\t\t\t\t{ _id: { $in: usersWithOldCoupon?.map(u => u._id) } },\n\t\t\t\t\t\t\toldCoupon._id,\n\t\t\t\t\t\t\tindividualStoreCoupon._id\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CouponType.INDIVIDUAL_USER: {\n\t\t\t\tcoupon = await individualUserCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst individualUserCoupon = coupon as DocumentType<IndividualUserCoupon>;\n\t\t\t\t\tawait this.removeCouponFromMultipleUser(\n\t\t\t\t\t\t{ _id: { $in: usersWithOldCoupon?.map(u => u._id) } },\n\t\t\t\t\t\toldCoupon._id\n\t\t\t\t\t);\n\t\t\t\t\tawait this.assignCouponToMultipleUser(\n\t\t\t\t\t\t{ _id: { $in: individualUserCoupon.users } },\n\t\t\t\t\t\tindividualUserCoupon._id\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CouponType.CUSTOM_COUPON: {\n\t\t\t\tcoupon = await customCouponService.create(data);\n\t\t\t\tif (coupon) {\n\t\t\t\t\tconst customCoupon = coupon as DocumentType<CustomCoupon>;\n\t\t\t\t\tif (!customCoupon.forNewUserOnly) {\n\t\t\t\t\t\tawait this.exchangeCouponForMultipleUser(\n\t\t\t\t\t\t\t{ _id: { $in: usersWithOldCoupon?.map(u => u._id) } },\n\t\t\t\t\t\t\toldCoupon._id,\n\t\t\t\t\t\t\tcoupon._id\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\t\tmessage: `Invalid coupon type`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (!coupon) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\tmessage: `Could create updated coupon`,\n\t\t\t});\n\t\t}\n\n\t\t// add previous version to new coupon\n\t\tconst previousVersions = oldCoupon?.previousVersions || [];\n\t\tpreviousVersions.push(oldCoupon._id);\n\n\t\tconst updatedCoupon = await this.baseCouponModel.findByIdAndUpdate(\n\t\t\tcoupon._id,\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tpreviousVersions,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\n\t\tif (!updatedCoupon) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: `Could not set previous versions of coupon`,\n\t\t\t});\n\t\t}\n\t\t// update old coupon\n\t\tconst updatedOldCoupon = await this.baseCouponModel.findByIdAndUpdate(\n\t\t\toldCoupon._id,\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tupdatedVersion: coupon._id,\n\t\t\t\t\t'duration.end': coupon.duration.end,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\n\t\treturn updatedCoupon;\n\t}\n\n\tpublic async updateStatus(id: string, status: Status): Promise<DocumentType<Model>> {\n\t\tconst coupon = await this.baseCouponModel.findByIdAndUpdate(\n\t\t\tid,\n\t\t\t{\n\t\t\t\t$set: { status },\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\n\t\tif (!coupon) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'NOT_FOUND',\n\t\t\t\tmessage: 'Coupon not found',\n\t\t\t});\n\t\t}\n\n\t\t// also update the status of previous versions of the coupon\n\t\tconst previousVersions = coupon.previousVersions;\n\t\tif (previousVersions && previousVersions.length > 0) {\n\t\t\tawait this.baseCouponModel.updateMany(\n\t\t\t\t{ _id: { $in: previousVersions } },\n\t\t\t\t{\n\t\t\t\t\t$set: { status },\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\n\t\treturn coupon;\n\t}\n\n\t/**\n\t * Delete record\n\t * @param data Data for delete\n\t */\n\tpublic async deleteById(data: DeleteDTO): Promise<string> {\n\t\tconst { _id, softDelete } = data;\n\n\t\tconst coupon = await this.model.findById(_id);\n\n\t\tif (!coupon) {\n\t\t\tnotFoundError('Coupon not found');\n\t\t}\n\n\t\tconst result = await this.model.deleteRecord({ _id, deletedAt: null }, softDelete);\n\t\tif (!result) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'NOT_FOUND',\n\t\t\t\tmessage: 'Record not found',\n\t\t\t});\n\t\t}\n\n\t\t// remove coupons from users' coupon lists\n\t\tthis.removeCouponFromMultipleUser({}, _id);\n\n\t\t// also delete previous versions of the coupon\n\t\tconst previousVersions = coupon.previousVersions;\n\t\tif (previousVersions && previousVersions.length > 0) {\n\t\t\tawait this.model.deleteRecord({ _id: { $in: previousVersions }, deletedAt: null }, softDelete);\n\t\t}\n\n\t\treturn 'Record deleted successfully';\n\t}\n\n\t/**\n\t * Get User Coupons\n\t * @param data User and pagination data\n\t */\n\tpublic async getUserCoupons(\n\t\tuser: mongoose.Types.ObjectId | undefined,\n\t\tshop: mongoose.Types.ObjectId | undefined,\n\t\tpage: number = 0,\n\t\tsize: number = 0\n\t): Promise<{\n\t\tavailable: Array<DocumentType<Model>>;\n\t\tused: Array<DocumentType<Model>>;\n\t\texpired: Array<DocumentType<Model>>;\n\t}> {\n\t\tconst couponRepository = new CouponRepository();\n\t\tlet itemType: ItemType | undefined = undefined;\n\t\tif (shop) {\n\t\t\tconst shopDocument = await this.shopModel.findOne({ _id: shop }).select('itemType');\n\t\t\titemType = shopDocument?.itemType;\n\t\t}\n\t\tconst coupons = await couponRepository.getUserCoupons(user, shop, itemType);\n\n\t\tif (shop && user) {\n\t\t\tconst punch = await this.punchHistoryService.getPunchCoupon(user, shop);\n\t\t\tif (punch) {\n\t\t\t\tcoupons.available.push(punch);\n\t\t\t}\n\t\t}\n\n\t\treturn couponRepository.addLabelsToAllCoupons(coupons);\n\t}\n\n\tpublic async validateCoupon(data: ValidateCouponDTO): Promise<CouponValidationOutputDTO> {\n\t\tif (data.coupon === 'punch') {\n\t\t\treturn await punchMarketingHistoryService.getPunchDiscount(data);\n\t\t}\n\n\t\tconst user = await this.userModel.findById(data.user);\n\t\tif (!user) notFoundError('User not found');\n\n\t\tlet coupon = await this.model.findOne({\n\t\t\tcode: data.coupon,\n\t\t\t_id: { $in: user.coupons ?? [] },\n\t\t\tstatus: { $in: [Status.ACTIVE, null] },\n\t\t});\n\n\t\tif (!coupon) {\n\t\t\tcoupon = await this.model.findOne({\n\t\t\t\tcode: data.coupon,\n\t\t\t\tstatus: { $in: [Status.ACTIVE, null] },\n\t\t\t\tcouponType: { $in: [CouponType.REFERRAL_CODE, CouponType.CUSTOM_COUPON] },\n\t\t\t\tupdatedVersion: { $exists: false },\n\t\t\t});\n\n\t\t\tif (!coupon) {\n\t\t\t\tnotFoundError('Coupon not found');\n\t\t\t}\n\t\t}\n\n\t\tif (coupon.couponType == CouponType.REFERRAL_CODE) {\n\t\t\treturn await referralCodeCouponService.validateCoupon(data, coupon as DocumentType<ReferralCodeCoupon>);\n\t\t}\n\n\t\tconst baseCoupon = coupon as DocumentType<BaseCoupon>;\n\n\t\tconst { isValid, invalidMessage } = await this.validateBaseCoupon(\n\t\t\tbaseCoupon,\n\t\t\tuser._id,\n\t\t\tdata.amountBeforeCoupon,\n\t\t\tBoolean(data.scheduledAt) ? dayjs(data.scheduledAt) : undefined\n\t\t);\n\n\t\tif (!isValid) {\n\t\t\treturn {\n\t\t\t\tisValid,\n\t\t\t\tmessage: invalidMessage,\n\t\t\t};\n\t\t}\n\n\t\tswitch (coupon.couponType) {\n\t\t\tcase CouponType.REFERRAL_REWARD:\n\t\t\t\treturn await referralRewardCouponService.validateCoupon(\n\t\t\t\t\tdata,\n\t\t\t\t\tcoupon as DocumentType<ReferralRewardCoupon>\n\t\t\t\t);\n\t\t\tcase CouponType.GLOBAL:\n\t\t\t\treturn await globalCouponService.validateCoupon(data, coupon as DocumentType<GlobalCoupon>);\n\t\t\tcase CouponType.SHOPS_CATEGORIES:\n\t\t\t\treturn await shopsCategoriesCouponService.validateCoupon(\n\t\t\t\t\tdata,\n\t\t\t\t\tcoupon as DocumentType<ShopsCategoriesCoupon>\n\t\t\t\t);\n\t\t\tcase CouponType.INDIVIDUAL_STORE:\n\t\t\t\treturn await individualStoreCouponService.validateCoupon(\n\t\t\t\t\tdata,\n\t\t\t\t\tcoupon as DocumentType<IndividualStoreCoupon>\n\t\t\t\t);\n\t\t\tcase CouponType.INDIVIDUAL_USER:\n\t\t\t\treturn await individualUserCouponService.validateCoupon(\n\t\t\t\t\tdata,\n\t\t\t\t\tcoupon as DocumentType<IndividualUserCoupon>\n\t\t\t\t);\n\t\t\tcase CouponType.CUSTOM_COUPON:\n\t\t\t\treturn await customCouponService.validateCoupon(data, coupon as DocumentType<CustomCoupon>);\n\t\t\tdefault:\n\t\t\t\tnotImplementedError(`Validation not implemented for ${coupon.couponType} coupons`);\n\t\t}\n\t}\n\n\tprivate isCouponExpired(coupon: DocumentType<BaseCoupon>): Boolean {\n\t\tif (coupon.expirationReason || (coupon?.duration?.end && new Date(coupon?.duration?.end) < new Date())) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t *\n\t * @param coupon Base coupon document\n\t * @param user ID of the user trying to user the coupon\n\t * @param orderAmount Order subtotal\n\t * @returns True if coupon is valid\n\t */\n\tprivate async validateBaseCoupon(\n\t\tcoupon: DocumentType<BaseCoupon>,\n\t\tuser: mongoose.Types.ObjectId,\n\t\torderAmount: number,\n\t\tscheduledAt: Dayjs | undefined = undefined\n\t): Promise<{ isValid: boolean; invalidMessage?: string }> {\n\t\tconst invalidConditions = [\n\t\t\tthis.isCouponExpired(coupon), // check coupon expired\n\t\t\tcoupon.duration.start > dayjs().toDate(), // check coupon start\n\t\t\tcoupon.isMinOrderValueEnabled && coupon.minOrderValue && orderAmount < coupon.minOrderValue, // check minimum order value\n\t\t\tcoupon.forNewUserOnly && !(await this.verifyNewUserConditions(coupon, user)), // check if new user\n\t\t\tcoupon.isOrderLimitPerUserEnabled &&\n\t\t\t\tcoupon.orderLimitPerUser &&\n\t\t\t\t(await this.getCouponOrdersForUser(user, coupon.code)) >= coupon.orderLimitPerUser, // check order limit for user\n\t\t\tscheduledAt && Boolean(coupon.duration.end) && dayjs(coupon.duration.end).isBefore(scheduledAt), // check scheduledAt is before coupon end date\n\t\t];\n\n\t\tconst invalidMessages = [\n\t\t\t'This coupon is expired',\n\t\t\t'This coupon is not available yet',\n\t\t\t'The minimum order amount for this coupon is not met',\n\t\t\t'This coupon is for new users only',\n\t\t\t'You have reached the order limit for this coupon',\n\t\t\t'This coupon is not valid for this scheduled orders',\n\t\t];\n\n\t\tconst isValid = invalidConditions.every(value => Boolean(value) == false);\n\t\tconst invalidMessage = invalidMessages.filter((_, index) => invalidConditions[index])?.[0];\n\n\t\treturn { isValid, invalidMessage };\n\t}\n\n\t// Returns true if new user conditions are met. False otherwise\n\tprivate async verifyNewUserConditions(\n\t\tcoupon: DocumentType<BaseCoupon>,\n\t\tuser: mongoose.Types.ObjectId\n\t): Promise<boolean> {\n\t\tconst forNewUserOnly = coupon.forNewUserOnly;\n\t\tconst isOrderLimitPerUserEnabled = coupon.isOrderLimitPerUserEnabled;\n\t\tconst orderLimitPerUser = coupon.orderLimitPerUser;\n\n\t\tif (forNewUserOnly) {\n\t\t\tif (isOrderLimitPerUserEnabled && orderLimitPerUser) {\n\t\t\t\tconst orderCount = await couponHelperService.getSameDeviceOrders(user);\n\t\t\t\treturn orderLimitPerUser > orderCount;\n\t\t\t}\n\t\t\treturn await couponHelperService.isNewUser(user);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tprivate async getCouponOrdersForUser(user: mongoose.Types.ObjectId, couponCode: string): Promise<number> {\n\t\tconst orders = (await this.orderModel\n\t\t\t.find({\n\t\t\t\tuser: user,\n\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\torderType: OrderType.REGULAR,\n\t\t\t})\n\t\t\t.populate([{ path: 'cart' }])) as Array<DocumentType<RegularOrder> & { cart: DocumentType<Cart> }>;\n\n\t\tconst count = orders.filter(order => order.cart.couponCode == couponCode).length;\n\n\t\treturn count;\n\t}\n\n\tpublic async handleCouponExpiry(couponId: mongoose.Types.ObjectId) {\n\t\tconst coupon = await this.model.findById(couponId);\n\t\tif (!coupon || coupon.couponType == CouponType.REFERRAL_CODE) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst typedCoupon = coupon as DocumentType<BaseCoupon>;\n\t\tawait this.processCouponForExpiry(typedCoupon);\n\t}\n\n\tprivate async processCouponForExpiry(coupon: DocumentType<BaseCoupon>) {\n\t\tlet expirationReason: string | null = null;\n\n\t\tif (coupon.isTotalOrderLimitEnabled && coupon.totalOrderLimit) {\n\t\t\t// find the order count by aggregating the order collection,\n\t\t\t// checking orders that have adjustedFinance.pricing.couponDiscount > 0,\n\t\t\t// populating cart collection to match coupon code\n\n\t\t\tconst pipeline = [\n\t\t\t\t{\n\t\t\t\t\t$match: {\n\t\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\t\t'adjustedFinance.pricing.couponDiscount': { $gt: 0 },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$lookup: {\n\t\t\t\t\t\tfrom: 'carts',\n\t\t\t\t\t\tlocalField: 'cart',\n\t\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\t\tas: 'cart',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$unwind: '$cart',\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$match: {\n\t\t\t\t\t\t'cart.couponCode': coupon.code,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$count: 'orderCount',\n\t\t\t\t},\n\t\t\t];\n\t\t\tconst result = await this.orderModel.aggregate(pipeline);\n\t\t\tconst orderCount = result[0]?.orderCount ?? 0;\n\n\t\t\tif (orderCount >= coupon.totalOrderLimit) {\n\t\t\t\texpirationReason = CouponExpirationReason.TOTAL_ORDER_LIMIT;\n\t\t\t}\n\t\t}\n\t\tif (coupon.isSpendLimitEnabled && coupon.spendLimit) {\n\t\t\t// spend limit\n\n\t\t\tconst { totalCouponDiscount, totalSecondaryCouponDiscount } = await this.getCouponDiscountTotals(\n\t\t\t\tcoupon.code\n\t\t\t);\n\n\t\t\tif (totalCouponDiscount >= coupon.spendLimit) {\n\t\t\t\texpirationReason = CouponExpirationReason.SPEND_LIMIT;\n\t\t\t}\n\t\t}\n\n\t\tawait this.baseCouponModel.findByIdAndUpdate(\n\t\t\tcoupon._id,\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\texpirationReason,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async syncCouponExpiry() {\n\t\tconst coupons = await this.baseCouponModel.find({\n\t\t\tcouponType: { $ne: CouponType.REFERRAL_CODE },\n\t\t\texpirationReason: null,\n\t\t});\n\n\t\tconsole.log(`Syncing expiry for ${coupons.length} coupons`);\n\n\t\tconsole.time('syncCouponExpiry');\n\t\tfor (const coupon of coupons) {\n\t\t\tconsole.time(`Processing coupon ${coupon.code}`);\n\t\t\tawait this.processCouponForExpiry(coupon);\n\t\t\tconsole.timeEnd(`Processing coupon ${coupon.code}`);\n\t\t}\n\t\tconsole.timeEnd('syncCouponExpiry');\n\t}\n\n\tprivate async findCouponByCode(code: string): Promise<DocumentType<Model> | null> {\n\t\tconst coupon = await this.model.findOne({ code: code, updatedVersion: { $exists: false } });\n\t\tif (!coupon) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'NOT_FOUND',\n\t\t\t\tmessage: 'Coupon not found',\n\t\t\t});\n\t\t}\n\t\treturn coupon;\n\t}\n\n\tprivate async getCouponDiscountTotals(couponCode: string) {\n\t\tconst pipeline = [\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\t'adjustedFinance.pricing.couponDiscount': { $gt: 0 },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'carts',\n\t\t\t\t\tlocalField: 'cart',\n\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\tas: 'cart',\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t$unwind: '$cart',\n\t\t\t},\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t'cart.couponCode': couponCode,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: null,\n\t\t\t\t\ttotalCouponDiscount: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$toDouble: {\n\t\t\t\t\t\t\t\t$ifNull: ['$adjustedFinance.pricing.couponDiscount', 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\ttotalSecondaryCouponDiscount: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$toDouble: {\n\t\t\t\t\t\t\t\t$ifNull: ['$adjustedFinance.pricing.secondaryCouponDiscount', 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\tconst result = await this.orderModel.aggregate(pipeline);\n\n\t\treturn {\n\t\t\ttotalCouponDiscount: result[0]?.totalCouponDiscount ?? 0,\n\t\t\ttotalSecondaryCouponDiscount: result[0]?.totalSecondaryCouponDiscount ?? 0,\n\t\t};\n\t}\n\n\tprivate async assignCouponToUser(user: mongoose.Types.ObjectId, coupon: mongoose.Types.ObjectId) {\n\t\tconst updatedUser = await this.userModel.findByIdAndUpdate(\n\t\t\tuser,\n\t\t\t{\n\t\t\t\t$push: {\n\t\t\t\t\tcoupons: coupon,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\t}\n\n\tprivate async assignCouponToMultipleUser(\n\t\tquery: mongoose.FilterQuery<User>,\n\t\tcoupon: mongoose.Types.ObjectId\n\t) {\n\t\tconsole.log('Assigning coupon to multiple users with coupon:', coupon);\n\t\tconst updatedUsers = await this.userModel.updateMany(query, {\n\t\t\t$push: {\n\t\t\t\tcoupons: coupon,\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate async assignCouponToNewUsers(coupon: mongoose.Types.ObjectId) {\n\t\tconsole.log('Assigning coupon to new users', coupon);\n\n\t\tconst newUsers = await couponHelperService.getNewUsers();\n\t\tconst updatedUsers = await this.userModel.updateMany(\n\t\t\t{ _id: { $in: newUsers.map(user => user._id) } },\n\t\t\t{\n\t\t\t\t$push: {\n\t\t\t\t\tcoupons: coupon,\n\t\t\t\t},\n\t\t\t}\n\t\t);\n\t}\n\n\tprivate async removeCouponFromUser(user: mongoose.Types.ObjectId, coupon: mongoose.Types.ObjectId) {\n\t\tconst updatedUser = await this.userModel.findByIdAndUpdate(\n\t\t\tuser,\n\t\t\t{\n\t\t\t\t$pull: {\n\t\t\t\t\tcoupons: coupon,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\t}\n\n\tprivate async removeCouponFromMultipleUser(\n\t\tquery: mongoose.FilterQuery<User>,\n\t\tcoupon: mongoose.Types.ObjectId\n\t) {\n\t\tconst updatedUsers = await this.userModel.updateMany(query, {\n\t\t\t$pull: {\n\t\t\t\tcoupons: coupon,\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate throwBadRequest(message: string): never {\n\t\tthrow new TRPCError({\n\t\t\tcode: 'BAD_REQUEST',\n\t\t\tmessage,\n\t\t});\n\t}\n\n\tpublic async addCouponToUser(user: any, couponCode: string): Promise<DocumentType<Model>> {\n\t\tconst coupon = await this.findCouponByCode(couponCode);\n\t\tif (!coupon) {\n\t\t\tthis.throwBadRequest('Coupon not found');\n\t\t}\n\t\tconst isNewUser = await couponHelperService.isNewUser(new mongoose.Types.ObjectId(user));\n\n\t\tif (coupon.couponType == CouponType.REFERRAL_CODE && !isNewUser) {\n\t\t\tthis.throwBadRequest('This coupon is valid for new users only');\n\t\t}\n\n\t\tif (coupon.couponType == CouponType.REFERRAL_CODE) {\n\t\t\tif ((coupon as DocumentType<ReferralCodeCoupon>).referralUser.toString() == user) {\n\t\t\t\tthis.throwBadRequest('You cannot add your own referral code');\n\t\t\t}\n\t\t}\n\n\t\tconst typedCoupon = coupon as DocumentType<BaseCoupon>;\n\n\t\tif (this.isCouponExpired(typedCoupon)) {\n\t\t\tthis.throwBadRequest('This coupon has expired and cannot be added');\n\t\t}\n\n\t\tif (typedCoupon.forNewUserOnly && !isNewUser) {\n\t\t\tthis.throwBadRequest('This coupon is valid for new users only');\n\t\t}\n\n\t\tconst alreadyApplied = await this.hasUserAlreadyAppliedCoupon(user, typedCoupon);\n\t\tif (alreadyApplied) {\n\t\t\tthis.throwBadRequest('Coupon already applied to user');\n\t\t}\n\n\t\tif (typedCoupon.couponType == CouponType.INDIVIDUAL_USER) {\n\t\t\tif (!(typedCoupon as DocumentType<IndividualUserCoupon>).users?.includes(user)) {\n\t\t\t\tthis.throwBadRequest('This coupon is not assigned to this user');\n\t\t\t}\n\t\t}\n\n\t\tawait this.userModel.findByIdAndUpdate(\n\t\t\tuser,\n\t\t\t{ $push: { coupons: typedCoupon._id } },\n\t\t\t{ new: true, runValidators: true }\n\t\t);\n\n\t\treturn coupon;\n\t}\n\n\tprivate async hasUserAlreadyAppliedCoupon(\n\t\tuserId: mongoose.Types.ObjectId,\n\t\tcoupon: DocumentType<BaseCoupon>\n\t): Promise<boolean> {\n\t\tconst couponIds = [coupon._id, ...(coupon.previousVersions ?? []).map(v => v._id)];\n\n\t\tconst user = await this.userModel.exists({\n\t\t\t_id: userId,\n\t\t\tcoupons: { $in: couponIds },\n\t\t});\n\n\t\treturn !!user;\n\t}\n\n\tprivate async exchangeCouponForMultipleUser(\n\t\tquery: mongoose.FilterQuery<User>,\n\t\toldCoupon: mongoose.Types.ObjectId,\n\t\tnewCoupon: mongoose.Types.ObjectId\n\t) {\n\t\tawait this.removeCouponFromMultipleUser(query, oldCoupon);\n\t\tawait this.assignCouponToMultipleUser(query, newCoupon);\n\t}\n\n\tpublic getShareableLink = async (code: string): Promise<ShareableLinkDTO> => {\n\t\tconst secretsService = getLibraries().getSecretsService();\n\t\tconst deepLinkUrl = (await secretsService.getKey('DEEP_LINK_URL')) ?? 'https://link.lyxa.ai';\n\n\t\tconst link = `${deepLinkUrl}/invite/${code}`;\n\n\t\tconst message = `Download Lyxa and explore the wide variety of offerings and benefits! Use my code at checkout to claim a special coupon : ${code}.\n\t\t${link}`;\n\n\t\treturn { link, message };\n\t};\n\n\tpublic async getUserCouponList(data?: Partial<FilterDTO>): Promise<PaginatedResponse<AllCouponsDTO>> {\n\t\ttry {\n\t\t\tlet query = data?.query || {};\n\n\t\t\tif (!query.user) {\n\t\t\t\tbadRequestError('User ID is required in query');\n\t\t\t}\n\n\t\t\tconst select = data?.select || {\n\t\t\t\t_id: 1,\n\t\t\t\t'createdBy.name': 1,\n\t\t\t\t'duration.start': 1,\n\t\t\t\t'duration.end': 1,\n\t\t\t\tcode: 1,\n\t\t\t\tstatus: 1,\n\t\t\t\tcreatedAt: 1,\n\t\t\t\tcouponType: 1,\n\t\t\t};\n\n\t\t\tlet isExpiredField = null;\n\n\t\t\tif (query.status) {\n\t\t\t\tif (query.status === 'expired') {\n\t\t\t\t\tisExpiredField = true;\n\t\t\t\t\tdelete query.status;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (query.createdAt) {\n\t\t\t\t// convert to date range\n\t\t\t\tif ('$gte' in query.createdAt) {\n\t\t\t\t\tquery.createdAt.$gte = new Date(query.createdAt.$gte);\n\t\t\t\t}\n\t\t\t\tif ('$lte' in query.createdAt) {\n\t\t\t\t\tquery.createdAt.$lte = new Date(query.createdAt.$lte);\n\t\t\t\t}\n\t\t\t\tif ('$gt' in query.createdAt) {\n\t\t\t\t\tquery.createdAt.$gt = new Date(query.createdAt.$gt);\n\t\t\t\t}\n\t\t\t\tif ('$lt' in query.createdAt) {\n\t\t\t\t\tquery.createdAt.$lt = new Date(query.createdAt.$lt);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst user = await this.userModel.findById(query.user).select('coupons');\n\t\t\tquery._id = { $in: user?.coupons ?? [] };\n\t\t\tdelete query.user; // remove user from query to avoid issues in aggregation match stage\n\n\t\t\tconst pipeline: any[] = [\n\t\t\t\t{ $match: { ...query, deletedAt: null } }, // Filter by search query\n\t\t\t\t{\n\t\t\t\t\t$lookup: {\n\t\t\t\t\t\t// INNER JOIN on categories\n\t\t\t\t\t\tfrom: 'admins', // Mongoose auto-pluralizes collection names\n\t\t\t\t\t\tlocalField: 'createdBy',\n\t\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\t\tas: 'createdBy',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ $unwind: { path: '$createdBy', preserveNullAndEmptyArrays: true } }, // Flatten the array\n\t\t\t\t{\n\t\t\t\t\t$addFields: {\n\t\t\t\t\t\tisExpired: {\n\t\t\t\t\t\t\t$cond: {\n\t\t\t\t\t\t\t\tif: {\n\t\t\t\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t\t\t\t{ $ifNull: ['$duration.end', false] },\n\t\t\t\t\t\t\t\t\t\t\t\t{ $lt: ['$duration.end', dayjs().toDate()] },\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t{ $ifNull: ['$expirationReason', false] },\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\tthen: true,\n\t\t\t\t\t\t\t\telse: false,\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$match: isExpiredField\n\t\t\t\t\t\t? { isExpired: true }\n\t\t\t\t\t\t: query.status === 'active'\n\t\t\t\t\t\t\t? { isExpired: false }\n\t\t\t\t\t\t\t: {},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$addFields: {\n\t\t\t\t\t\tstatus: {\n\t\t\t\t\t\t\t$cond: {\n\t\t\t\t\t\t\t\tif: { $eq: ['$isExpired', true] },\n\t\t\t\t\t\t\t\tthen: 'expired',\n\t\t\t\t\t\t\t\telse: '$status',\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$project: select,\n\t\t\t\t},\n\t\t\t];\n\n\t\t\tif (data?.search?.searchKey) {\n\t\t\t\tconst searchKey = data.search.searchKey;\n\t\t\t\tconst regex = new RegExp(searchKey, 'i'); // case-insensitive search\n\t\t\t\tconst fields = data.search.searchFields?.length ? data.search.searchFields : ['code']; // default field(s) to search in\n\n\t\t\t\tpipeline.push({\n\t\t\t\t\t$match: {\n\t\t\t\t\t\t$or: fields.map(field => ({ [field]: { $regex: regex } })),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Execute the aggregation with pagination and sorting\n\t\t\tconst results = await paginateAggregation(this.model, pipeline, data?.page, data?.size, data?.sort);\n\n\t\t\treturn results as unknown as PaginatedResponse<AllCouponsDTO>;\n\t\t} catch (err) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: `err: ${err}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic async addExistingCouponsToNewUser(userId: mongoose.Types.ObjectId) {\n\t\tconst isNewUser = await couponHelperService.isNewUser(userId);\n\n\t\tconst query: any = {\n\t\t\tcouponType: { $in: [CouponType.GLOBAL, CouponType.INDIVIDUAL_STORE, CouponType.SHOPS_CATEGORIES] },\n\t\t\tdeletedAt: null,\n\t\t\texpirationReason: null,\n\t\t\t$or: [\n\t\t\t\t{ 'duration.end': { $gt: dayjs().toDate() } },\n\t\t\t\t{ 'duration.end': { $exists: false } },\n\t\t\t\t{ 'duration.end': null },\n\t\t\t],\n\t\t\tupdatedVersion: { $exists: false },\n\t\t};\n\n\t\tif (!isNewUser) {\n\t\t\tquery.forNewUserOnly = { $ne: true };\n\t\t}\n\n\t\t// assign all coupons that are not expired\n\t\tconst coupons = await this.baseCouponModel.find(query);\n\n\t\tconst couponIds = coupons.map(coupon => coupon._id);\n\n\t\tawait this.userModel.findByIdAndUpdate(\n\t\t\tuserId,\n\t\t\t{\n\t\t\t\t$addToSet: {\n\t\t\t\t\tcoupons: { $each: couponIds },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tnew: true,\n\t\t\t\trunValidators: true,\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getActiveNewUserCoupon(): Promise<DocumentType<BaseCoupon> | null> {\n\t\tconst currentDate = dayjs().toDate();\n\t\tconst activeForNewUserCoupon = await this.baseCouponModel.findOne({\n\t\t\tcouponType: CouponType.GLOBAL,\n\t\t\tforNewUserOnly: true,\n\t\t\tdeletedAt: null,\n\t\t\t$or: [\n\t\t\t\t{\n\t\t\t\t\texpirationReason: { $exists: false },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\texpirationReason: null,\n\t\t\t\t},\n\t\t\t],\n\t\t\t'duration.end': { $gte: currentDate },\n\t\t\tupdatedVersion: { $exists: false },\n\t\t});\n\n\t\treturn activeForNewUserCoupon;\n\t}\n\n\tpublic async getActiveNewUserCouponWithSecondaryCurrency(): Promise<DocumentType<BaseCoupon> | null> {\n\t\tconst exchangeRate = await getExchangeRate();\n\t\tconst currentDate = dayjs().toDate();\n\n\t\tconst referralSettings = await this.referralSettingsModel.findOne();\n\n\t\tconst secondaryReferralReceiverValue =\n\t\t\treferralSettings?.receiver?.valueType == ValueType.PERCENTAGE\n\t\t\t\t? null\n\t\t\t\t: roundSecondaryCurrency((referralSettings?.receiver?.value ?? 0) * exchangeRate);\n\n\t\tconst secondaryReferralReceiverMinOrderAmount = roundSecondaryCurrency(\n\t\t\t(referralSettings?.receiver?.minimumOrderValue ?? 0) * exchangeRate\n\t\t);\n\n\t\tconst activeForNewUserCoupon = await this.baseCouponModel.aggregate([\n\t\t\t// Match (same as findOne filter)\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\tcouponType: CouponType.GLOBAL,\n\t\t\t\t\tforNewUserOnly: true,\n\t\t\t\t\tdeletedAt: null,\n\t\t\t\t\t$or: [\n\t\t\t\t\t\t{ expirationReason: { $exists: false } },\n\t\t\t\t\t\t{ expirationReason: null },\n\t\t\t\t\t],\n\t\t\t\t\t'duration.end': { $gte: currentDate },\n\t\t\t\t\tupdatedVersion: { $exists: false },\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Add computed fields\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\t'secondaryCurrencyValue': {\n\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$eq: ['$valueType', ValueType.PERCENTAGE],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tcase: {\n\t\t\t\t\t\t\t\t\t\t\t\t$eq: [\n\t\t\t\t\t\t\t\t\t\t\t\t\t'$couponType',\n\t\t\t\t\t\t\t\t\t\t\t\t\tCouponType.REFERRAL_CODE,\n\t\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\tthen: secondaryReferralReceiverValue,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tdefault: getRoundSecondaryCurrencyStage({\n\t\t\t\t\t\t\t\t\t\t$multiply: ['$value', exchangeRate],\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\n\t\t\t\t\t'secondaryCurrencyMaxDiscountLimit': {\n\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcase: {\n\t\t\t\t\t\t\t\t\t\t$eq: [\n\t\t\t\t\t\t\t\t\t\t\t'$couponType',\n\t\t\t\t\t\t\t\t\t\t\tCouponType.REFERRAL_CODE,\n\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tthen: null,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdefault: getRoundSecondaryCurrencyStage({\n\t\t\t\t\t\t\t\t$multiply: ['$maxDiscountLimit', exchangeRate],\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\t'secondaryCurrencyMinOrderValue': {\n\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcase: {\n\t\t\t\t\t\t\t\t\t\t$eq: [\n\t\t\t\t\t\t\t\t\t\t\t'$couponType',\n\t\t\t\t\t\t\t\t\t\t\tCouponType.REFERRAL_CODE,\n\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tthen: secondaryReferralReceiverMinOrderAmount,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdefault: getRoundSecondaryCurrencyStage({\n\t\t\t\t\t\t\t\t$multiply: ['$minOrderValue', exchangeRate],\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\n\t\t\t// Limit to 1 document (like findOne)\n\t\t\t{$limit: 1},\n\t\t]);\n\n\t\treturn activeForNewUserCoupon[0] || null;\n\t}\n\n\tpublic async checkExistingNewUserCoupon(): Promise<CheckExistingNewUserCouponOutputDTO> {\n\t\tconst alreadyActiveForNewUserCoupon = await this.getActiveNewUserCoupon();\n\n\t\tif (alreadyActiveForNewUserCoupon) {\n\t\t\treturn { exists: true };\n\t\t}\n\n\t\treturn { exists: false };\n\t}\n\n\tprivate async getAllOrders(userIds: mongoose.Types.ObjectId[]): Promise<number> {\n\t\treturn await this.orderModel.countDocuments({\n\t\t\tuser: { $in: userIds },\n\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\torderType: OrderType.REGULAR,\n\t\t});\n\t}\n\n\tpublic async handleCouponGiftBox(\n\t\tdeviceId: string,\n\t\tuserId: mongoose.Types.ObjectId | null\n\t): Promise<DocumentType<GlobalCoupon>[]> {\n\t\tconst couponRepository = new CouponRepository();\n\n\t\t// 1. Get all the user id using device id\n\t\tconst allUsers = await this.userModel.find({ deviceId }).select('_id');\n\n\t\t// 2. Make an array using all the user ids\n\t\tconst userIds = allUsers.map(user => user._id);\n\n\t\t// 3. Append the current user id to the array\n\t\tif (userId) {\n\t\t\tuserIds.push(new mongoose.Types.ObjectId(userId));\n\t\t}\n\n\t\t// 4. Check if any user has isNewUserCouponShowed = true\n\t\tconst hasShownCoupon = await this.userModel.exists({\n\t\t\t_id: { $in: userIds },\n\t\t\tisNewUserCouponShowed: true,\n\t\t});\n\n\t\tif (hasShownCoupon) {\n\t\t\t// console.log('At least one user already saw the coupon');\n\t\t\treturn [];\n\t\t}\n\n\t\t// 5. Find how many orders placed by these user ids\n\t\tconst totalOrders = await this.getAllOrders(userIds);\n\n\t\t// 6. Get coupon details\n\t\tconst activeNewUserCoupon = await this.getActiveNewUserCouponWithSecondaryCurrency();\n\t\tif (!activeNewUserCoupon) {\n\t\t\t// notFoundError('No active new user coupon found');\n\t\t\treturn [];\n\t\t}\n\n\t\t// 7. Check the total order quantity less than to order limit per user\n\t\tif (\n\t\t\tactiveNewUserCoupon.isOrderLimitPerUserEnabled &&\n\t\t\ttotalOrders < (activeNewUserCoupon.orderLimitPerUser || 0)\n\t\t) {\n\t\t\t// Update the user document for the new user coupon\n\t\t\t// this.updateNewUserCouponField(userIds);\n\t\t\t\n\t\t\t// Return the coupon details to show in the gift box\n\t\t\treturn couponRepository.addLabelsToCoupons([activeNewUserCoupon]);\n\t\t}\n\n\t\treturn [];\n\t}\n\n\tprivate async updateNewUserCouponField(userIds: mongoose.Types.ObjectId[]): Promise<number> {\n\t\t// Update all the users coupon-shown field\n\t\tconst result = await this.userModel.updateMany(\n\t\t\t{ _id: { $in: userIds } },\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tisNewUserCouponShowed: false,\n\t\t\t\t},\n\t\t\t}\n\t\t);\n\n\t\treturn result.modifiedCount;\n\t}\n\n\tpublic async updateCouponGiftBoxShown(userId: mongoose.Types.ObjectId, data: any): Promise<number> {\n\t\t// Get device-id using user-id\n\t\tconst user = await this.userModel.findById(userId);\n\t\t\n\t\t// Get all users using device-id\n\t\tconst users = await this.userModel\n\t\t\t.find({deviceId: user?.deviceId})\n\t\t\t.select('_id')\n\t\t\t.lean()\n\n\t\t// Set array of ids\n\t\tconst userIds = users.map(u => u._id);\n\n\t\t// Update all the users coupon-shown field\n\t\tconst result = await this.userModel.updateMany(\n\t\t\t{ _id: { $in: userIds } },\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tisNewUserCouponShowed: data.isNewUserGiftBoxShown,\n\t\t\t\t},\n\t\t\t}\n\t\t);\n\n\t\treturn result.modifiedCount;\n\t}\n}\n\nexport const couponService = Container.get(CouponService);\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"CouponRepository.d.ts","sourceRoot":"/","sources":["modules/coupon/services/patterns/repository/CouponRepository.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAEhD,OAAO,EAEN,QAAQ,EAIR,MAAM,m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AAE,QAAQ,GAAG,SAAS,GAC5B,OAAO,CAAC,GAAG,CAAC;IAoVR,qBAAqB,CAAC,OAAO,EAAE,GAAG,GAAG,GAAG;IAQxC,kBAAkB,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,GAAG,EAAE;IA6ChD,OAAO,CAAC,cAAc;IAOtB,OAAO,CAAC,iBAAiB;IA0DzB,OAAO,CAAC,2BAA2B;CAyGnC"}
@@ -307,6 +307,13 @@ class CouponRepository {
307
307
  },
308
308
  ];
309
309
  const [results] = await this.userModel.aggregate(pipeline);
310
+ if (!results) {
311
+ return {
312
+ available: [],
313
+ used: [],
314
+ expired: [],
315
+ };
316
+ }
310
317
  const populatedResults = await this.userModel.populate(results, {
311
318
  path: 'available.referringUser',
312
319
  model: this.coreUserModel,
@@ -1 +1 @@
1
- {"version":3,"file":"CouponRepository.js","sourceRoot":"/","sources":["modules/coupon/services/patterns/repository/CouponRepository.ts"],"names":[],"mappings":";;;AAAA,sEAQmD;AAGnD,gHAAkH;AAClH,4DAM2C;AAC3C,oEAAwE;AACxE,gEAA6E;AAC7E,8DAA2D;AAE3D,MAAa,gBAAgB;IACX,KAAK,CAA+C;IACpD,SAAS,CAA2C;IACpD,qBAAqB,CAAiE;IAC/F,cAAc,GAA+C,IAAI,CAAC;IAE1E;QACC,IAAI,CAAC,KAAK,GAAG,oBAA2D,CAAC;QACzE,IAAI,CAAC,SAAS,GAAG,kBAAqD,CAAC;QACvE,IAAI,CAAC,qBAAqB,GAAG,6BACI,CAAC;IACnC,CAAC;IAED,IAAY,aAAa;QACxB,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;YAC1B,IAAI,CAAC,cAAc,GAAG,IAAA,yBAAgB,GAAE,CAAC;QAC1C,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC;IAC5B,CAAC;IAEM,KAAK,CAAC,cAAc,CAC1B,IAAyC,EACzC,IAAyC,EACzC,QAA8B;QAE9B,MAAM,YAAY,GAAG,MAAM,IA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etCoreUserModel,\n\tReferralSetting,\n\tReferralSettingModel,\n\tUser,\n\tUserModel,\n} from '@lyxa.ai/core/dist/libraries/mongo/models';\nimport { SoftDeleteModel } from '@lyxa.ai/core/dist/libraries/mongo/plugins/soft-delete-plugin';\nimport { mongoose } from '@typegoose/typegoose';\nimport { getRoundSecondaryCurrencyStage } from '@lyxa.ai/core/dist/utilities/pipelines/common-pipeline-functions';\nimport {\n\tCouponType,\n\tItemType,\n\tRegularOrderStatus,\n\tStatus,\n\tValueType,\n} from '@lyxa.ai/core/dist/utilities/enum';\nimport { getExchangeRate } from '@lyxa.ai/core/dist/utilities/currency';\nimport { roundSecondaryCurrency } from '@lyxa.ai/core/dist/utilities/shared';\nimport { dayjs } from '@lyxa.ai/core/dist/utilities/dayjs';\n\nexport class CouponRepository {\n\tprivate readonly model: typeof CouponModel & SoftDeleteModel<Coupon>;\n\tprivate readonly userModel: typeof UserModel & SoftDeleteModel<User>;\n\tprivate readonly referralSettingsModel: typeof ReferralSettingModel & SoftDeleteModel<ReferralSetting>;\n\tprivate _coreUserModel: ReturnType<typeof getCoreUserModel> | null = null;\n\n\tconstructor() {\n\t\tthis.model = CouponModel as typeof CouponModel & SoftDeleteModel<Coupon>;\n\t\tthis.userModel = UserModel as typeof UserModel & SoftDeleteModel<User>;\n\t\tthis.referralSettingsModel = ReferralSettingModel as typeof ReferralSettingModel &\n\t\t\tSoftDeleteModel<ReferralSetting>;\n\t}\n\n\tprivate get coreUserModel() {\n\t\tif (!this._coreUserModel) {\n\t\t\tthis._coreUserModel = getCoreUserModel();\n\t\t}\n\t\treturn this._coreUserModel;\n\t}\n\n\tpublic async getUserCoupons(\n\t\tuser: mongoose.Types.ObjectId | undefined,\n\t\tshop: mongoose.Types.ObjectId | undefined,\n\t\titemType: ItemType | undefined\n\t): Promise<any> {\n\t\tconst exchangeRate = await getExchangeRate();\n\n\t\tconst referralSettings = await this.referralSettingsModel.findOne();\n\n\t\tconst secondaryReferralReceiverValue =\n\t\t\treferralSettings?.receiver?.valueType == ValueType.PERCENTAGE\n\t\t\t\t? null\n\t\t\t\t: roundSecondaryCurrency((referralSettings?.receiver?.value ?? 0) * exchangeRate);\n\n\t\tconst secondaryReferralReceiverMinOrderAmount = roundSecondaryCurrency(\n\t\t\t(referralSettings?.receiver?.minimumOrderValue ?? 0) * exchangeRate\n\t\t);\n\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\t// Match the user\n\t\t\t{\n\t\t\t\t$match: { _id: user },\n\t\t\t},\n\n\t\t\t// Lookup coupon documents\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'coupons',\n\t\t\t\t\tlocalField: 'coupons',\n\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\tas: 'couponDocs',\n\t\t\t\t\tpipeline: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$expr: {\n\t\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$eq: [{ $ifNull: ['$status', Status.ACTIVE] }, Status.ACTIVE],\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$lte: [{ $ifNull: ['$duration.start', dayjs().toDate()] }, dayjs().toDate()],\n\t\t\t\t\t\t\t\t\t\t},\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\t{\n\t\t\t\t\t\t\t$lookup: {\n\t\t\t\t\t\t\t\tfrom: 'users',\n\t\t\t\t\t\t\t\tlocalField: 'referralUser',\n\t\t\t\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\t\t\t\tas: 'referralUser',\n\t\t\t\t\t\t\t\tpipeline: [{ $project: { coreUser: 1 } }],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$lookup: {\n\t\t\t\t\t\t\t\tfrom: 'users',\n\t\t\t\t\t\t\t\tlocalField: 'influencer',\n\t\t\t\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\t\t\t\tas: 'influencer',\n\t\t\t\t\t\t\t\tpipeline: [{ $project: { coreUser: 1 } }],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$lookup: {\n\t\t\t\t\t\t\t\tfrom: 'shops',\n\t\t\t\t\t\t\t\tlocalField: 'shop',\n\t\t\t\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\t\t\t\tas: 'shop',\n\t\t\t\t\t\t\t\tpipeline: [{ $project: { name: 1 } }],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$unwind: { path: '$shop', preserveNullAndEmptyArrays: true },\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$unwind: { path: '$referralUser', preserveNullAndEmptyArrays: true },\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$unwind: { path: '$influencer', preserveNullAndEmptyArrays: true },\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$addFields: {\n\t\t\t\t\t\t\t\treferringUser: {\n\t\t\t\t\t\t\t\t\t$ifNull: ['$referralUser.coreUser', '$influencer.coreUser'],\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\t{\n\t\t\t\t\t\t\t$project: { referralUser: 0, influencer: 0 },\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// Lookup orders containing coupons for this user\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'orders',\n\t\t\t\t\tlet: { userId: '$_id' },\n\t\t\t\t\tpipeline: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$expr: { $eq: ['$user', '$$userId'] },\n\t\t\t\t\t\t\t\t'adjustedFinance.coupon': { $exists: true },\n\t\t\t\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$lookup: {\n\t\t\t\t\t\t\t\tfrom: 'coupons',\n\t\t\t\t\t\t\t\tlocalField: 'adjustedFinance.coupon.coupon',\n\t\t\t\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\t\t\t\tas: 'couponInfo',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$unwind: '$couponInfo',\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t\t_id: '$adjustedFinance.coupon.coupon',\n\t\t\t\t\t\t\t\tsnap: { $first: '$couponInfo' },\n\t\t\t\t\t\t\t\tcount: { $sum: 1 },\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\tas: 'couponUsage',\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Unwind coupons to classify individually\n\t\t\t{\n\t\t\t\t$unwind: '$couponDocs',\n\t\t\t},\n\n\t\t\t// Filter individual shop and shops categories coupons\n\t\t\tthis.filterShopCoupons(shop, itemType),\n\n\t\t\t// Filter first order only coupons\n\t\t\t...this.filterFirstOrderOnlyCoupons(shop),\n\n\t\t\t// Join usage count for this coupon\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\tusageData: {\n\t\t\t\t\t\t$arrayElemAt: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$filter: {\n\t\t\t\t\t\t\t\t\tinput: '$couponUsage',\n\t\t\t\t\t\t\t\t\tas: 'cu',\n\t\t\t\t\t\t\t\t\tcond: { $eq: ['$$cu._id', '$couponDocs._id'] },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t0,\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// Classify expiration exactly like isCouponExpired()\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\tisExpired: {\n\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t// true only if expirationReason is a non-empty string\n\t\t\t\t\t\t\t{ $gt: [{ $strLenCP: { $ifNull: ['$couponDocs.expirationReason', ''] } }, 0] },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t{ $ifNull: ['$couponDocs.duration.end', false] },\n\t\t\t\t\t\t\t\t\t{ $lt: ['$couponDocs.duration.end', '$$NOW'] }, // consistent “now”\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\tusedCount: { $ifNull: ['$usageData.count', 0] },\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Add exchange rate and secondary currency rounding factor\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\texchangeRate: exchangeRate,\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Compute and add secondary currency values to coupon documents\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\t// base value\n\t\t\t\t\t'couponDocs.value': {\n\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcase: { $eq: ['$couponDocs.couponType', CouponType.REFERRAL_CODE] },\n\t\t\t\t\t\t\t\t\tthen: referralSettings?.receiver?.value ?? 0,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdefault: '$couponDocs.value',\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\t// value type\n\t\t\t\t\t'couponDocs.valueType': {\n\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcase: { $eq: ['$couponDocs.couponType', CouponType.REFERRAL_CODE] },\n\t\t\t\t\t\t\t\t\tthen: referralSettings?.receiver?.valueType ?? 0,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdefault: '$couponDocs.valueType',\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\t'couponDocs.secondaryCurrencyValue': {\n\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t// If valueType is percentage => null always\n\t\t\t\t\t\t\t{ $eq: ['$couponDocs.valueType', ValueType.PERCENTAGE] },\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tcase: { $eq: ['$couponDocs.couponType', CouponType.REFERRAL_CODE] },\n\t\t\t\t\t\t\t\t\t\t\tthen: secondaryReferralReceiverValue,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tdefault: getRoundSecondaryCurrencyStage({\n\t\t\t\t\t\t\t\t\t\t$multiply: ['$couponDocs.value', exchangeRate],\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\n\t\t\t\t\t'couponDocs.secondaryCurrencyMaxDiscountLimit': {\n\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcase: { $eq: ['$couponDocs.couponType', CouponType.REFERRAL_CODE] },\n\t\t\t\t\t\t\t\t\tthen: null,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdefault: getRoundSecondaryCurrencyStage({\n\t\t\t\t\t\t\t\t$multiply: ['$couponDocs.maxDiscountLimit', exchangeRate],\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\t'couponDocs.secondaryCurrencyMinOrderValue': {\n\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcase: { $eq: ['$couponDocs.couponType', CouponType.REFERRAL_CODE] },\n\t\t\t\t\t\t\t\t\tthen: secondaryReferralReceiverMinOrderAmount,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdefault: getRoundSecondaryCurrencyStage({\n\t\t\t\t\t\t\t\t$multiply: ['$couponDocs.minOrderValue', exchangeRate],\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\n\t\t\t// Category logic\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\tcategory: {\n\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t'$isExpired',\n\t\t\t\t\t\t\t'expired',\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t\t\t{ $gt: ['$usedCount', 0] },\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t\t\t\t\t\t\t{ $not: ['$couponDocs.orderLimitPerUser'] },\n\t\t\t\t\t\t\t\t\t\t\t\t\t{ $lt: ['$usedCount', '$couponDocs.orderLimitPerUser'] },\n\t\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t'available',\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$cond: [{ $gt: ['$usedCount', 0] }, 'used', 'available'],\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},\n\n\t\t\t// Group into arrays\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: '$_id',\n\t\t\t\t\tavailable: {\n\t\t\t\t\t\t$push: {\n\t\t\t\t\t\t\t$cond: [{ $eq: ['$category', 'available'] }, '$couponDocs', '$$REMOVE'],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tused: {\n\t\t\t\t\t\t$push: {\n\t\t\t\t\t\t\t$cond: [{ $eq: ['$category', 'used'] }, '$usageData.snap', '$$REMOVE'],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\texpired: {\n\t\t\t\t\t\t$push: {\n\t\t\t\t\t\t\t$cond: [{ $eq: ['$category', 'expired'] }, '$couponDocs', '$$REMOVE'],\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\t{\n\t\t\t\t$project: {\n\t\t\t\t\t_id: 0,\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\n\t\tconst [results] = await this.userModel.aggregate(pipeline);\n\n\t\tconst populatedResults = await this.userModel.populate(results, {\n\t\t\tpath: 'available.referringUser',\n\t\t\tmodel: this.coreUserModel,\n\t\t\tselect: { _id: 0, name: 1 },\n\t\t});\n\n\t\treturn populatedResults;\n\t}\n\n\tpublic addLabelsToAllCoupons(coupons: any): any {\n\t\treturn {\n\t\t\tavailable: this.addLabelsToCoupons(coupons.available).reverse(), // Just to make newly added coupon at the top\n\t\t\tused: this.addLabelsToCoupons(coupons.used).reverse(), // Just to make newly added coupon at the top\n\t\t\texpired: this.addLabelsToCoupons(coupons.expired).reverse(), // Just to make newly added coupon at the top\n\t\t};\n\t}\n\n\tpublic addLabelsToCoupons(coupons: any[]): any[] {\n\t\tconst resultsWithLabels = coupons.map(coupon => {\n\t\t\t// couponOfferLabel\n\t\t\tconst valuePart =\n\t\t\t\tcoupon.valueType === 'fixed'\n\t\t\t\t\t? this.formatCurrency(coupon.value, coupon.secondaryCurrencyValue)\n\t\t\t\t\t: `${coupon.value}%`;\n\n\t\t\tconst maxDiscountPart =\n\t\t\t\tcoupon.isMaxDiscountLimitEnabled && coupon.maxDiscountLimit > 0\n\t\t\t\t\t? ` up to ${this.formatCurrency(coupon.maxDiscountLimit, coupon.secondaryCurrencyMaxDiscountLimit)}`\n\t\t\t\t\t: '';\n\n\t\t\tconst influencerPart = coupon.referringUser ? ` (Referred by ${coupon.referringUser.name})` : '';\n\n\t\t\tcoupon.couponOfferLabel = `Save ${valuePart}${maxDiscountPart}${influencerPart}`;\n\n\t\t\t// couponValidityLabel\n\t\t\tlet validityParts: string[] = [];\n\n\t\t\t// 1. Minimum Order\n\t\t\tif (coupon.isMinOrderValueEnabled && coupon.minOrderValue > 0) {\n\t\t\t\tvalidityParts.push(\n\t\t\t\t\t`Minimum order ${this.formatCurrency(coupon.minOrderValue, coupon.secondaryCurrencyMinOrderValue)}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// 2. Order Limit\n\t\t\tif (coupon.isOrderLimitPerUserEnabled && coupon.orderLimitPerUser > 0) {\n\t\t\t\tvalidityParts.push(`applied on ${coupon.orderLimitPerUser} order`);\n\t\t\t}\n\n\t\t\tif(coupon.couponType === CouponType.REFERRAL_CODE || coupon.couponType === CouponType.REFERRAL_REWARD){\n\t\t\t\tvalidityParts = [];\n\t\t\t\tvalidityParts.push(`Applied on 1 Order`);\n\t\t\t}\n\n\t\t\tcoupon.couponValidityLabel = validityParts.join('. ');\n\n\t\t\treturn coupon;\n\t\t});\n\n\t\treturn resultsWithLabels;\n\t}\n\n\tprivate formatCurrency(value: any, secondaryCurrencyValue: any) {\n\t\tif (secondaryCurrencyValue !== null && secondaryCurrencyValue !== undefined) {\n\t\t\treturn 'LBP ' + String(secondaryCurrencyValue);\n\t\t}\n\t\treturn '$' + String(value ?? 0);\n\t}\n\n\tprivate filterShopCoupons(\n\t\tshop: mongoose.Types.ObjectId | undefined,\n\t\titemType: ItemType | undefined\n\t): mongoose.PipelineStage {\n\t\treturn {\n\t\t\t$match: {\n\t\t\t\t$expr: {\n\t\t\t\t\t// If shopId is undefined → skip filtering (always true)\n\t\t\t\t\t$cond: [\n\t\t\t\t\t\t{ $not: [shop] }, // means shopId is null/undefined\n\t\t\t\t\t\ttrue, // skip filtering\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t\t// Case 1: INDIVIDUAL_STORE → shop must match\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t\t{ $eq: ['$couponDocs.couponType', CouponType.INDIVIDUAL_STORE] },\n\t\t\t\t\t\t\t\t\t\t{ $eq: ['$couponDocs.shop._id', shop] },\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t// Case 2: SHOP_CATEGORY\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t\t{ $eq: ['$couponDocs.couponType', CouponType.SHOPS_CATEGORIES] },\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t\t\t\t\t\t// itemType matches\n\t\t\t\t\t\t\t\t\t\t\t\t{ $eq: ['$couponDocs.itemType', itemType] },\n\n\t\t\t\t\t\t\t\t\t\t\t\t// or shopId is inside couponDocs.shops[]\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t$in: [shop, { $ifNull: ['$couponDocs.shops', []] }],\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t// Case 3: All other coupon types → keep\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$not: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$in: [\n\t\t\t\t\t\t\t\t\t\t\t\t'$couponDocs.couponType',\n\t\t\t\t\t\t\t\t\t\t\t\t[CouponType.INDIVIDUAL_STORE, CouponType.SHOPS_CATEGORIES],\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t},\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},\n\t\t};\n\t}\n\n\tprivate filterFirstOrderOnlyCoupons(shop?: mongoose.Types.ObjectId): mongoose.PipelineStage[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'orders',\n\t\t\t\t\tlet: {\n\t\t\t\t\t\tuserId: '$_id',\n\t\t\t\t\t\tshopId: shop ?? '$couponDocs.shop._id',\n\t\t\t\t\t\tcouponShops: { $ifNull: ['$couponDocs.shops', []] },\n\t\t\t\t\t},\n\t\t\t\t\tpipeline: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$expr: {\n\t\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t\t{ $eq: ['$user', '$$userId'] },\n\n\t\t\t\t\t\t\t\t\t\t{ $ne: ['$status', RegularOrderStatus.CANCELLED] },\n\n\t\t\t\t\t\t\t\t\t\t// If shop is provided → only that shop\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t\t\t\t\t{ $ne: ['$$shopId', null] },\n\t\t\t\t\t\t\t\t\t\t\t\t{ $eq: ['$shop', '$$shopId'] },\n\n\t\t\t\t\t\t\t\t\t\t\t\t// Else → any shop in coupon.shops\n\t\t\t\t\t\t\t\t\t\t\t\t{ $in: ['$shop', '$$couponShops'] },\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t},\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\t{\n\t\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t\t_id: null,\n\t\t\t\t\t\t\t\torderedShops: { $addToSet: '$shop' },\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\tas: 'orderStats',\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\torderedShops: {\n\t\t\t\t\t\t$ifNull: [{ $arrayElemAt: ['$orderStats.orderedShops', 0] }, []],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\t// Individual store logic\n\t\t\t\t\thasOrderedFromStore: {\n\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t{ $eq: ['$couponDocs.couponType', CouponType.INDIVIDUAL_STORE] },\n\t\t\t\t\t\t\t{ $in: [shop ?? '$couponDocs.shop._id', '$orderedShops'] },\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\n\t\t\t\t\t// Multiple store logic\n\t\t\t\t\thasUnusedShopInCategory: {\n\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t{ $eq: ['$couponDocs.couponType', CouponType.SHOPS_CATEGORIES] },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t\t{ $ifNull: [shop, false] },\n\t\t\t\t\t\t\t\t\t// shop provided → hide if user has ordered from this shop\n\t\t\t\t\t\t\t\t\t{ $in: [shop, '$orderedShops'] },\n\t\t\t\t\t\t\t\t\t// no shop provided → hide if no unused shops\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$eq: [\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t$size: { $setDifference: [{ $ifNull: ['$couponDocs.shops', []] }, '$orderedShops'] },\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\t\t],\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\tfalse,\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\t{\n\t\t\t\t$match: {\n\t\t\t\t\t$expr: {\n\t\t\t\t\t\t$not: {\n\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$in: ['$couponDocs.couponType', [CouponType.INDIVIDUAL_STORE, CouponType.SHOPS_CATEGORIES]],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{ $eq: ['$couponDocs.firstOrderOnly', true] },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$or: ['$hasOrderedFromStore', '$hasUnusedShopInCategory'],\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},\n\t\t];\n\t}\n}\n"]}
1
+ {"version":3,"file":"CouponRepository.js","sourceRoot":"/","sources":["modules/coupon/services/patterns/repository/CouponRepository.ts"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EAAE,OAAO,EAAE,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;oCAE1B,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,eAAe,CAAC,EAAE;oCAEhC;wCACC,GAAG,EAAE;4CACJ;gDACC,KAAK,EAAE,EAAE,cAAc,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,mBAAmB,EAAE,EAAE,CAAC,EAAE,EAAE,eAAe,CAAC,EAAE;6CACpF;4CACD,CAAC;yCACD;qCACD;iCACD;6BACD;4BACD,KAAK;yBACL;qBACD;iBACD;aACD;YACD;gBACC,MAAM,EAAE;oBACP,KAAK,EAAE;wBACN,IAAI,EAAE;4BACL,IAAI,EAAE;gCACL;oCACC,GAAG,EAAE,CAAC,wBAAwB,EAAE,CAAC,iBAAU,CAAC,gBAAgB,EAAE,iBAAU,CAAC,gBAAgB,CAAC,CAAC;iCAC3F;gCACD,EAAE,GAAG,EAAE,CAAC,4BAA4B,EAAE,IAAI,CAAC,EAAE;gCAC7C;oCACC,GAAG,EAAE,CAAC,sBAAsB,EAAE,0BAA0B,CAAC;iCACzD;6BACD;yBACD;qBACD;iBACD;aACD;SACD,CAAC;IACH,CAAC;CACD;AA3kBD,4CA2kBC","sourcesContent":["import {\n\tCoupon,\n\tCouponModel,\n\tgetCoreUserModel,\n\tReferralSetting,\n\tReferralSettingModel,\n\tUser,\n\tUserModel,\n} from '@lyxa.ai/core/dist/libraries/mongo/models';\nimport { SoftDeleteModel } from '@lyxa.ai/core/dist/libraries/mongo/plugins/soft-delete-plugin';\nimport { mongoose } from '@typegoose/typegoose';\nimport { getRoundSecondaryCurrencyStage } from '@lyxa.ai/core/dist/utilities/pipelines/common-pipeline-functions';\nimport {\n\tCouponType,\n\tItemType,\n\tRegularOrderStatus,\n\tStatus,\n\tValueType,\n} from '@lyxa.ai/core/dist/utilities/enum';\nimport { getExchangeRate } from '@lyxa.ai/core/dist/utilities/currency';\nimport { roundSecondaryCurrency } from '@lyxa.ai/core/dist/utilities/shared';\nimport { dayjs } from '@lyxa.ai/core/dist/utilities/dayjs';\n\nexport class CouponRepository {\n\tprivate readonly model: typeof CouponModel & SoftDeleteModel<Coupon>;\n\tprivate readonly userModel: typeof UserModel & SoftDeleteModel<User>;\n\tprivate readonly referralSettingsModel: typeof ReferralSettingModel & SoftDeleteModel<ReferralSetting>;\n\tprivate _coreUserModel: ReturnType<typeof getCoreUserModel> | null = null;\n\n\tconstructor() {\n\t\tthis.model = CouponModel as typeof CouponModel & SoftDeleteModel<Coupon>;\n\t\tthis.userModel = UserModel as typeof UserModel & SoftDeleteModel<User>;\n\t\tthis.referralSettingsModel = ReferralSettingModel as typeof ReferralSettingModel &\n\t\t\tSoftDeleteModel<ReferralSetting>;\n\t}\n\n\tprivate get coreUserModel() {\n\t\tif (!this._coreUserModel) {\n\t\t\tthis._coreUserModel = getCoreUserModel();\n\t\t}\n\t\treturn this._coreUserModel;\n\t}\n\n\tpublic async getUserCoupons(\n\t\tuser: mongoose.Types.ObjectId | undefined,\n\t\tshop: mongoose.Types.ObjectId | undefined,\n\t\titemType: ItemType | undefined\n\t): Promise<any> {\n\t\tconst exchangeRate = await getExchangeRate();\n\n\t\tconst referralSettings = await this.referralSettingsModel.findOne();\n\n\t\tconst secondaryReferralReceiverValue =\n\t\t\treferralSettings?.receiver?.valueType == ValueType.PERCENTAGE\n\t\t\t\t? null\n\t\t\t\t: roundSecondaryCurrency((referralSettings?.receiver?.value ?? 0) * exchangeRate);\n\n\t\tconst secondaryReferralReceiverMinOrderAmount = roundSecondaryCurrency(\n\t\t\t(referralSettings?.receiver?.minimumOrderValue ?? 0) * exchangeRate\n\t\t);\n\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\t// Match the user\n\t\t\t{\n\t\t\t\t$match: { _id: user },\n\t\t\t},\n\n\t\t\t// Lookup coupon documents\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'coupons',\n\t\t\t\t\tlocalField: 'coupons',\n\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\tas: 'couponDocs',\n\t\t\t\t\tpipeline: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$expr: {\n\t\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$eq: [{ $ifNull: ['$status', Status.ACTIVE] }, Status.ACTIVE],\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$lte: [{ $ifNull: ['$duration.start', dayjs().toDate()] }, dayjs().toDate()],\n\t\t\t\t\t\t\t\t\t\t},\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\t{\n\t\t\t\t\t\t\t$lookup: {\n\t\t\t\t\t\t\t\tfrom: 'users',\n\t\t\t\t\t\t\t\tlocalField: 'referralUser',\n\t\t\t\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\t\t\t\tas: 'referralUser',\n\t\t\t\t\t\t\t\tpipeline: [{ $project: { coreUser: 1 } }],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$lookup: {\n\t\t\t\t\t\t\t\tfrom: 'users',\n\t\t\t\t\t\t\t\tlocalField: 'influencer',\n\t\t\t\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\t\t\t\tas: 'influencer',\n\t\t\t\t\t\t\t\tpipeline: [{ $project: { coreUser: 1 } }],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$lookup: {\n\t\t\t\t\t\t\t\tfrom: 'shops',\n\t\t\t\t\t\t\t\tlocalField: 'shop',\n\t\t\t\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\t\t\t\tas: 'shop',\n\t\t\t\t\t\t\t\tpipeline: [{ $project: { name: 1 } }],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$unwind: { path: '$shop', preserveNullAndEmptyArrays: true },\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$unwind: { path: '$referralUser', preserveNullAndEmptyArrays: true },\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$unwind: { path: '$influencer', preserveNullAndEmptyArrays: true },\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$addFields: {\n\t\t\t\t\t\t\t\treferringUser: {\n\t\t\t\t\t\t\t\t\t$ifNull: ['$referralUser.coreUser', '$influencer.coreUser'],\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\t{\n\t\t\t\t\t\t\t$project: { referralUser: 0, influencer: 0 },\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// Lookup orders containing coupons for this user\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'orders',\n\t\t\t\t\tlet: { userId: '$_id' },\n\t\t\t\t\tpipeline: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$expr: { $eq: ['$user', '$$userId'] },\n\t\t\t\t\t\t\t\t'adjustedFinance.coupon': { $exists: true },\n\t\t\t\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$lookup: {\n\t\t\t\t\t\t\t\tfrom: 'coupons',\n\t\t\t\t\t\t\t\tlocalField: 'adjustedFinance.coupon.coupon',\n\t\t\t\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\t\t\t\tas: 'couponInfo',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$unwind: '$couponInfo',\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t\t_id: '$adjustedFinance.coupon.coupon',\n\t\t\t\t\t\t\t\tsnap: { $first: '$couponInfo' },\n\t\t\t\t\t\t\t\tcount: { $sum: 1 },\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\tas: 'couponUsage',\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Unwind coupons to classify individually\n\t\t\t{\n\t\t\t\t$unwind: '$couponDocs',\n\t\t\t},\n\n\t\t\t// Filter individual shop and shops categories coupons\n\t\t\tthis.filterShopCoupons(shop, itemType),\n\n\t\t\t// Filter first order only coupons\n\t\t\t...this.filterFirstOrderOnlyCoupons(shop),\n\n\t\t\t// Join usage count for this coupon\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\tusageData: {\n\t\t\t\t\t\t$arrayElemAt: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$filter: {\n\t\t\t\t\t\t\t\t\tinput: '$couponUsage',\n\t\t\t\t\t\t\t\t\tas: 'cu',\n\t\t\t\t\t\t\t\t\tcond: { $eq: ['$$cu._id', '$couponDocs._id'] },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t0,\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// Classify expiration exactly like isCouponExpired()\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\tisExpired: {\n\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t// true only if expirationReason is a non-empty string\n\t\t\t\t\t\t\t{ $gt: [{ $strLenCP: { $ifNull: ['$couponDocs.expirationReason', ''] } }, 0] },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t{ $ifNull: ['$couponDocs.duration.end', false] },\n\t\t\t\t\t\t\t\t\t{ $lt: ['$couponDocs.duration.end', '$$NOW'] }, // consistent “now”\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\tusedCount: { $ifNull: ['$usageData.count', 0] },\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Add exchange rate and secondary currency rounding factor\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\texchangeRate: exchangeRate,\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// Compute and add secondary currency values to coupon documents\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\t// base value\n\t\t\t\t\t'couponDocs.value': {\n\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcase: { $eq: ['$couponDocs.couponType', CouponType.REFERRAL_CODE] },\n\t\t\t\t\t\t\t\t\tthen: referralSettings?.receiver?.value ?? 0,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdefault: '$couponDocs.value',\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\t// value type\n\t\t\t\t\t'couponDocs.valueType': {\n\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcase: { $eq: ['$couponDocs.couponType', CouponType.REFERRAL_CODE] },\n\t\t\t\t\t\t\t\t\tthen: referralSettings?.receiver?.valueType ?? 0,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdefault: '$couponDocs.valueType',\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\t'couponDocs.secondaryCurrencyValue': {\n\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t// If valueType is percentage => null always\n\t\t\t\t\t\t\t{ $eq: ['$couponDocs.valueType', ValueType.PERCENTAGE] },\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tcase: { $eq: ['$couponDocs.couponType', CouponType.REFERRAL_CODE] },\n\t\t\t\t\t\t\t\t\t\t\tthen: secondaryReferralReceiverValue,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tdefault: getRoundSecondaryCurrencyStage({\n\t\t\t\t\t\t\t\t\t\t$multiply: ['$couponDocs.value', exchangeRate],\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\n\t\t\t\t\t'couponDocs.secondaryCurrencyMaxDiscountLimit': {\n\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcase: { $eq: ['$couponDocs.couponType', CouponType.REFERRAL_CODE] },\n\t\t\t\t\t\t\t\t\tthen: null,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdefault: getRoundSecondaryCurrencyStage({\n\t\t\t\t\t\t\t\t$multiply: ['$couponDocs.maxDiscountLimit', exchangeRate],\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\t'couponDocs.secondaryCurrencyMinOrderValue': {\n\t\t\t\t\t\t$switch: {\n\t\t\t\t\t\t\tbranches: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcase: { $eq: ['$couponDocs.couponType', CouponType.REFERRAL_CODE] },\n\t\t\t\t\t\t\t\t\tthen: secondaryReferralReceiverMinOrderAmount,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdefault: getRoundSecondaryCurrencyStage({\n\t\t\t\t\t\t\t\t$multiply: ['$couponDocs.minOrderValue', exchangeRate],\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\n\t\t\t// Category logic\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\tcategory: {\n\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t'$isExpired',\n\t\t\t\t\t\t\t'expired',\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t\t\t{ $gt: ['$usedCount', 0] },\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t\t\t\t\t\t\t{ $not: ['$couponDocs.orderLimitPerUser'] },\n\t\t\t\t\t\t\t\t\t\t\t\t\t{ $lt: ['$usedCount', '$couponDocs.orderLimitPerUser'] },\n\t\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t'available',\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$cond: [{ $gt: ['$usedCount', 0] }, 'used', 'available'],\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},\n\n\t\t\t// Group into arrays\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: '$_id',\n\t\t\t\t\tavailable: {\n\t\t\t\t\t\t$push: {\n\t\t\t\t\t\t\t$cond: [{ $eq: ['$category', 'available'] }, '$couponDocs', '$$REMOVE'],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tused: {\n\t\t\t\t\t\t$push: {\n\t\t\t\t\t\t\t$cond: [{ $eq: ['$category', 'used'] }, '$usageData.snap', '$$REMOVE'],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\texpired: {\n\t\t\t\t\t\t$push: {\n\t\t\t\t\t\t\t$cond: [{ $eq: ['$category', 'expired'] }, '$couponDocs', '$$REMOVE'],\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\t{\n\t\t\t\t$project: {\n\t\t\t\t\t_id: 0,\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\n\t\tconst [results] = await this.userModel.aggregate(pipeline);\n\n\t\tif (!results) {\n\t\t\treturn {\n\t\t\t\tavailable: [],\t\n\t\t\t\tused: [],\n\t\t\t\texpired: [],\n\t\t\t};\n\t\t}\n\n\t\tconst populatedResults = await this.userModel.populate(results, {\n\t\t\tpath: 'available.referringUser',\n\t\t\tmodel: this.coreUserModel,\n\t\t\tselect: { _id: 0, name: 1 },\n\t\t});\n\n\t\treturn populatedResults;\n\t}\n\n\tpublic addLabelsToAllCoupons(coupons: any): any {\n\t\treturn {\n\t\t\tavailable: this.addLabelsToCoupons(coupons.available).reverse(), // Just to make newly added coupon at the top\n\t\t\tused: this.addLabelsToCoupons(coupons.used).reverse(), // Just to make newly added coupon at the top\n\t\t\texpired: this.addLabelsToCoupons(coupons.expired).reverse(), // Just to make newly added coupon at the top\n\t\t};\n\t}\n\n\tpublic addLabelsToCoupons(coupons: any[]): any[] {\n\t\tconst resultsWithLabels = coupons.map(coupon => {\n\t\t\t// couponOfferLabel\n\t\t\tconst valuePart =\n\t\t\t\tcoupon.valueType === 'fixed'\n\t\t\t\t\t? this.formatCurrency(coupon.value, coupon.secondaryCurrencyValue)\n\t\t\t\t\t: `${coupon.value}%`;\n\n\t\t\tconst maxDiscountPart =\n\t\t\t\tcoupon.isMaxDiscountLimitEnabled && coupon.maxDiscountLimit > 0\n\t\t\t\t\t? ` up to ${this.formatCurrency(coupon.maxDiscountLimit, coupon.secondaryCurrencyMaxDiscountLimit)}`\n\t\t\t\t\t: '';\n\n\t\t\tconst influencerPart = coupon.referringUser ? ` (Referred by ${coupon.referringUser.name})` : '';\n\n\t\t\tcoupon.couponOfferLabel = `Save ${valuePart}${maxDiscountPart}${influencerPart}`;\n\n\t\t\t// couponValidityLabel\n\t\t\tlet validityParts: string[] = [];\n\n\t\t\t// 1. Minimum Order\n\t\t\tif (coupon.isMinOrderValueEnabled && coupon.minOrderValue > 0) {\n\t\t\t\tvalidityParts.push(\n\t\t\t\t\t`Minimum order ${this.formatCurrency(coupon.minOrderValue, coupon.secondaryCurrencyMinOrderValue)}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// 2. Order Limit\n\t\t\tif (coupon.isOrderLimitPerUserEnabled && coupon.orderLimitPerUser > 0) {\n\t\t\t\tvalidityParts.push(`applied on ${coupon.orderLimitPerUser} order`);\n\t\t\t}\n\n\t\t\tif(coupon.couponType === CouponType.REFERRAL_CODE || coupon.couponType === CouponType.REFERRAL_REWARD){\n\t\t\t\tvalidityParts = [];\n\t\t\t\tvalidityParts.push(`Applied on 1 Order`);\n\t\t\t}\n\n\t\t\tcoupon.couponValidityLabel = validityParts.join('. ');\n\n\t\t\treturn coupon;\n\t\t});\n\n\t\treturn resultsWithLabels;\n\t}\n\n\tprivate formatCurrency(value: any, secondaryCurrencyValue: any) {\n\t\tif (secondaryCurrencyValue !== null && secondaryCurrencyValue !== undefined) {\n\t\t\treturn 'LBP ' + String(secondaryCurrencyValue);\n\t\t}\n\t\treturn '$' + String(value ?? 0);\n\t}\n\n\tprivate filterShopCoupons(\n\t\tshop: mongoose.Types.ObjectId | undefined,\n\t\titemType: ItemType | undefined\n\t): mongoose.PipelineStage {\n\t\treturn {\n\t\t\t$match: {\n\t\t\t\t$expr: {\n\t\t\t\t\t// If shopId is undefined → skip filtering (always true)\n\t\t\t\t\t$cond: [\n\t\t\t\t\t\t{ $not: [shop] }, // means shopId is null/undefined\n\t\t\t\t\t\ttrue, // skip filtering\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t\t// Case 1: INDIVIDUAL_STORE → shop must match\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t\t{ $eq: ['$couponDocs.couponType', CouponType.INDIVIDUAL_STORE] },\n\t\t\t\t\t\t\t\t\t\t{ $eq: ['$couponDocs.shop._id', shop] },\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t// Case 2: SHOP_CATEGORY\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t\t{ $eq: ['$couponDocs.couponType', CouponType.SHOPS_CATEGORIES] },\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t\t\t\t\t\t// itemType matches\n\t\t\t\t\t\t\t\t\t\t\t\t{ $eq: ['$couponDocs.itemType', itemType] },\n\n\t\t\t\t\t\t\t\t\t\t\t\t// or shopId is inside couponDocs.shops[]\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t$in: [shop, { $ifNull: ['$couponDocs.shops', []] }],\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t// Case 3: All other coupon types → keep\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$not: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$in: [\n\t\t\t\t\t\t\t\t\t\t\t\t'$couponDocs.couponType',\n\t\t\t\t\t\t\t\t\t\t\t\t[CouponType.INDIVIDUAL_STORE, CouponType.SHOPS_CATEGORIES],\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t},\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},\n\t\t};\n\t}\n\n\tprivate filterFirstOrderOnlyCoupons(shop?: mongoose.Types.ObjectId): mongoose.PipelineStage[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'orders',\n\t\t\t\t\tlet: {\n\t\t\t\t\t\tuserId: '$_id',\n\t\t\t\t\t\tshopId: shop ?? '$couponDocs.shop._id',\n\t\t\t\t\t\tcouponShops: { $ifNull: ['$couponDocs.shops', []] },\n\t\t\t\t\t},\n\t\t\t\t\tpipeline: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$expr: {\n\t\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t\t{ $eq: ['$user', '$$userId'] },\n\n\t\t\t\t\t\t\t\t\t\t{ $ne: ['$status', RegularOrderStatus.CANCELLED] },\n\n\t\t\t\t\t\t\t\t\t\t// If shop is provided → only that shop\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t\t\t\t\t{ $ne: ['$$shopId', null] },\n\t\t\t\t\t\t\t\t\t\t\t\t{ $eq: ['$shop', '$$shopId'] },\n\n\t\t\t\t\t\t\t\t\t\t\t\t// Else → any shop in coupon.shops\n\t\t\t\t\t\t\t\t\t\t\t\t{ $in: ['$shop', '$$couponShops'] },\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t},\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\t{\n\t\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t\t_id: null,\n\t\t\t\t\t\t\t\torderedShops: { $addToSet: '$shop' },\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\tas: 'orderStats',\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\torderedShops: {\n\t\t\t\t\t\t$ifNull: [{ $arrayElemAt: ['$orderStats.orderedShops', 0] }, []],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t$addFields: {\n\t\t\t\t\t// Individual store logic\n\t\t\t\t\thasOrderedFromStore: {\n\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t{ $eq: ['$couponDocs.couponType', CouponType.INDIVIDUAL_STORE] },\n\t\t\t\t\t\t\t{ $in: [shop ?? '$couponDocs.shop._id', '$orderedShops'] },\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\n\t\t\t\t\t// Multiple store logic\n\t\t\t\t\thasUnusedShopInCategory: {\n\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t{ $eq: ['$couponDocs.couponType', CouponType.SHOPS_CATEGORIES] },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t\t{ $ifNull: [shop, false] },\n\t\t\t\t\t\t\t\t\t// shop provided → hide if user has ordered from this shop\n\t\t\t\t\t\t\t\t\t{ $in: [shop, '$orderedShops'] },\n\t\t\t\t\t\t\t\t\t// no shop provided → hide if no unused shops\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$eq: [\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t$size: { $setDifference: [{ $ifNull: ['$couponDocs.shops', []] }, '$orderedShops'] },\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\t\t],\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\tfalse,\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\t{\n\t\t\t\t$match: {\n\t\t\t\t\t$expr: {\n\t\t\t\t\t\t$not: {\n\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$in: ['$couponDocs.couponType', [CouponType.INDIVIDUAL_STORE, CouponType.SHOPS_CATEGORIES]],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{ $eq: ['$couponDocs.firstOrderOnly', true] },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$or: ['$hasOrderedFromStore', '$hasUnusedShopInCategory'],\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},\n\t\t];\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"coupon.validation.d.ts","sourceRoot":"/","sources":["modules/coupon/validations/coupon.validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAGN,GAAG,EACH,MAAM,2DAA2D,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAc,MAAM,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AAU1G,eAAO,MAAM,YAAY;;;;;;CAkBxB,CAAC;AAEF,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCtB,CA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,GAAG,CAAC,OAAO,wBAAwB,CAAC,CAAC;AACzE,MAAM,MAAM,mCAAmC,GAAG,GAAG,CAAC,OAAO,sCAAsC,CAAC,CAAC;AACrG,MAAM,MAAM,WAAW,GAAG,GAAG,CAAC,OAAO,cAAc,CAAC,CAAC;AACrD,MAAM,MAAM,wBAAwB,GAAG,GAAG,CAAC,OAAO,2BAA2B,CAAC,CAAC"}
@@ -9,10 +9,10 @@ const dayjs_1 = require("@lyxa.ai/core/dist/utilities/dayjs");
9
9
  exports.couponFields = {
10
10
  code: global_validation_1.ZodValidation.string('Code', {
11
11
  regex: { pattern: new RegExp('^[A-Z0-9]+$'), message: 'Coupon name must be uppercase' },
12
- maxLength: 6,
13
- minLength: 6,
14
- minMessage: 'Coupon must be 6 characters',
15
- maxMessage: 'Coupon must be 6 characters',
12
+ maxLength: 10,
13
+ minLength: 10,
14
+ minMessage: 'Coupon must be 10 characters',
15
+ maxMessage: 'Coupon must be 10 characters',
16
16
  }),
17
17
  orderLimitPerUser: global_validation_1.ZodValidation.number('OrderLimitPerUser')
18
18
  .nonnegative()
@@ -99,16 +99,7 @@ exports.CouponValidationOutputSchema = zod_1.z.object({
99
99
  discountCut: discountCutSchema.optional(),
100
100
  });
101
101
  exports.CouponCodeSchema = zod_1.z.object({
102
- couponCode: global_validation_1.ZodValidation.string('Coupon code', {
103
- minLength: 6,
104
- maxLength: 6,
105
- minMessage: 'Coupon code must be 6 characters',
106
- maxMessage: 'Coupon code must be 6 characters',
107
- regex: {
108
- pattern: /^[A-Z0-9]+$/,
109
- message: 'Coupon must be uppercase and alphanumeric',
110
- },
111
- }),
102
+ couponCode: global_validation_1.ZodValidation.string('Coupon code'),
112
103
  });
113
104
  exports.UpdateCouponStatusSchema = zod_1.z.object({
114
105
  _id: global_validation_1.ZodValidation.objectIdOrStringSchema,