@lyxa.ai/marketing 1.0.36 → 1.0.38

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 (25) hide show
  1. package/dist/lib/index.d.ts +27 -0
  2. package/dist/lib/index.d.ts.map +1 -1
  3. package/dist/lib/modules/coupon/services/coupon.service.d.ts.map +1 -1
  4. package/dist/lib/modules/coupon/services/coupon.service.js +2 -1
  5. package/dist/lib/modules/coupon/services/coupon.service.js.map +1 -1
  6. package/dist/lib/modules/marketing/routers/marketing.router.d.ts +27 -0
  7. package/dist/lib/modules/marketing/routers/marketing.router.d.ts.map +1 -1
  8. package/dist/lib/modules/marketing/routers/marketing.router.js +12 -0
  9. package/dist/lib/modules/marketing/routers/marketing.router.js.map +1 -1
  10. package/dist/lib/modules/marketing/services/marketing.service.d.ts +9 -0
  11. package/dist/lib/modules/marketing/services/marketing.service.d.ts.map +1 -1
  12. package/dist/lib/modules/marketing/services/marketing.service.js +229 -0
  13. package/dist/lib/modules/marketing/services/marketing.service.js.map +1 -1
  14. package/dist/lib/modules/punch-marketing-history/services/punch-marketing-history.service.d.ts.map +1 -1
  15. package/dist/lib/modules/punch-marketing-history/services/punch-marketing-history.service.js +5 -0
  16. package/dist/lib/modules/punch-marketing-history/services/punch-marketing-history.service.js.map +1 -1
  17. package/dist/types/index.d.ts +27 -0
  18. package/dist/types/index.d.ts.map +1 -1
  19. package/dist/types/modules/coupon/services/coupon.service.d.ts.map +1 -1
  20. package/dist/types/modules/marketing/routers/marketing.router.d.ts +27 -0
  21. package/dist/types/modules/marketing/routers/marketing.router.d.ts.map +1 -1
  22. package/dist/types/modules/marketing/services/marketing.service.d.ts +9 -0
  23. package/dist/types/modules/marketing/services/marketing.service.d.ts.map +1 -1
  24. package/dist/types/modules/punch-marketing-history/services/punch-marketing-history.service.d.ts.map +1 -1
  25. package/package.json +2 -2
@@ -541,6 +541,235 @@ let MarketingService = class MarketingService {
541
541
  });
542
542
  await Promise.all(promises);
543
543
  }
544
+ async calculateMarketingSpent(marketingId) {
545
+ const marketing = await this.model.findById(marketingId).lean();
546
+ if (!marketing) {
547
+ throw new Error('Marketing not found');
548
+ }
549
+ let amount = 0;
550
+ switch (marketing.marketingType) {
551
+ case enum_2.MarketingType.FREE_DELIVERY:
552
+ amount = await this.calculateFreeDeliverySpent(marketingId);
553
+ break;
554
+ case enum_2.MarketingType.DISCOUNT:
555
+ case enum_2.MarketingType.BUY1GET1:
556
+ amount = await this.calculateItemBasedSpent(marketingId);
557
+ break;
558
+ case enum_2.MarketingType.PUNCH_MARKETING:
559
+ amount = await this.calculatePunchMarketingSpent(marketingId);
560
+ break;
561
+ default:
562
+ amount = 0;
563
+ }
564
+ return {
565
+ amount,
566
+ marketingType: marketing.marketingType,
567
+ };
568
+ }
569
+ async calculateItemBasedSpent(marketingId) {
570
+ const pipeline = [
571
+ {
572
+ $match: {
573
+ $and: [{ marketings: { $exists: true } }, { marketings: { $ne: null } }],
574
+ status: { $ne: enum_1.RegularOrderStatus.CANCELLED },
575
+ marketings: marketingId,
576
+ },
577
+ },
578
+ {
579
+ $lookup: {
580
+ from: 'lineItems',
581
+ localField: 'cart',
582
+ foreignField: 'cart',
583
+ as: 'lineItems',
584
+ },
585
+ },
586
+ { $unwind: '$lineItems' },
587
+ {
588
+ $lookup: {
589
+ from: 'marketings',
590
+ localField: 'lineItems.marketings',
591
+ foreignField: '_id',
592
+ as: 'marketing',
593
+ },
594
+ },
595
+ { $unwind: '$marketing' },
596
+ {
597
+ $match: {
598
+ 'marketing._id': marketingId,
599
+ },
600
+ },
601
+ {
602
+ $group: {
603
+ _id: null,
604
+ totalCompanyDiscount: {
605
+ $sum: '$lineItems.calculationSnap.itemDiscountByCompany',
606
+ },
607
+ totalShopDiscount: {
608
+ $sum: '$lineItems.calculationSnap.itemDiscountByShop',
609
+ },
610
+ totalB1G1Company: {
611
+ $sum: '$lineItems.calculationSnap.b1g1DiscountByCompany',
612
+ },
613
+ totalB1G1Shop: {
614
+ $sum: '$lineItems.calculationSnap.b1g1DiscountByShop',
615
+ },
616
+ },
617
+ },
618
+ ];
619
+ const [result] = await this.orderModel.aggregate(pipeline);
620
+ if (!result)
621
+ return 0;
622
+ return (result.totalCompanyDiscount + result.totalShopDiscount + result.totalB1G1Company + result.totalB1G1Shop);
623
+ }
624
+ async calculateFreeDeliverySpent(marketingId) {
625
+ const pipeline = [
626
+ {
627
+ $match: {
628
+ $and: [{ marketings: { $exists: true } }, { marketings: { $ne: null } }],
629
+ status: { $ne: enum_1.RegularOrderStatus.CANCELLED },
630
+ marketings: marketingId,
631
+ },
632
+ },
633
+ {
634
+ $lookup: {
635
+ from: 'marketings',
636
+ localField: 'marketings',
637
+ foreignField: '_id',
638
+ as: 'marketing',
639
+ },
640
+ },
641
+ { $unwind: '$marketing' },
642
+ {
643
+ $match: {
644
+ 'marketing._id': marketingId,
645
+ 'marketing.marketingType': enum_2.MarketingType.FREE_DELIVERY,
646
+ },
647
+ },
648
+ {
649
+ $group: {
650
+ _id: null,
651
+ totalFreeDeliveryCompany: {
652
+ $sum: '$adjustedFinance.freeDelivery.companyCut',
653
+ },
654
+ totalFreeDeliveryShop: {
655
+ $sum: '$adjustedFinance.freeDelivery.shopCut',
656
+ },
657
+ },
658
+ },
659
+ ];
660
+ const [result] = await this.orderModel.aggregate(pipeline);
661
+ if (!result)
662
+ return 0;
663
+ return result.totalFreeDeliveryCompany + result.totalFreeDeliveryShop;
664
+ }
665
+ async calculatePunchMarketingSpent(marketingId) {
666
+ const pipeline = [
667
+ {
668
+ $match: {
669
+ $and: [{ marketings: { $exists: true } }, { marketings: { $ne: null } }],
670
+ status: { $ne: enum_1.RegularOrderStatus.CANCELLED },
671
+ marketings: marketingId,
672
+ },
673
+ },
674
+ {
675
+ $group: {
676
+ _id: null,
677
+ totalPunchDiscount: {
678
+ $sum: {
679
+ $ifNull: ['$adjustedFinance.pricing.punchMarketingDiscount', 0],
680
+ },
681
+ },
682
+ },
683
+ },
684
+ ];
685
+ const [result] = await this.orderModel.aggregate(pipeline);
686
+ return result?.totalPunchDiscount ?? 0;
687
+ }
688
+ async incrementMarketingSpentFromOrder(orderId) {
689
+ const order = (await this.orderModel
690
+ .findById(orderId)
691
+ .populate('lineItems'));
692
+ if (!order || !order.marketings?.length) {
693
+ return;
694
+ }
695
+ const marketingSpendMap = this.calculateMarketingSpendPerOrder(order);
696
+ const bulkOps = [...marketingSpendMap.entries()].map(([marketingId, amountSpent]) => ({
697
+ updateOne: {
698
+ filter: { _id: marketingId },
699
+ update: { $inc: { amountSpent } },
700
+ },
701
+ }));
702
+ if (bulkOps.length) {
703
+ await this.model.bulkWrite(bulkOps);
704
+ }
705
+ await this.expireMarketingsExceedingSpendLimits(Array.from(marketingSpendMap.keys()));
706
+ return 'Marketing amount spent incremented successfully';
707
+ }
708
+ async decrementMarketingSpentFromOrder(orderId) {
709
+ const order = (await this.orderModel
710
+ .findById(orderId)
711
+ .populate('lineItems'));
712
+ if (!order || !order.marketings?.length) {
713
+ return;
714
+ }
715
+ const marketingSpendMap = this.calculateMarketingSpendPerOrder(order);
716
+ const bulkOps = [...marketingSpendMap.entries()].map(([marketingId, amountSpent]) => ({
717
+ updateOne: {
718
+ filter: { _id: marketingId },
719
+ update: { $inc: { amountSpent: -amountSpent } },
720
+ },
721
+ }));
722
+ if (bulkOps.length) {
723
+ await this.model.bulkWrite(bulkOps);
724
+ }
725
+ await this.unExpireMarketingsBelowSpendLimits(Array.from(marketingSpendMap.keys()));
726
+ return 'Marketing amount spent decremented successfully';
727
+ }
728
+ async expireMarketingsExceedingSpendLimits(marketingIds) {
729
+ await this.model.updateMany({
730
+ _id: { $in: marketingIds },
731
+ isSpendLimitEnabled: true,
732
+ status: { $ne: enum_1.MarketingStatus.EXPIRED },
733
+ $expr: { $gte: ['$amountSpent', '$spendLimit'] },
734
+ }, { $set: { status: enum_1.MarketingStatus.EXPIRED } });
735
+ }
736
+ async unExpireMarketingsBelowSpendLimits(marketingIds) {
737
+ await this.model.updateMany({
738
+ _id: { $in: marketingIds },
739
+ isSpendLimitEnabled: true,
740
+ status: enum_1.MarketingStatus.EXPIRED,
741
+ $expr: { $lt: ['$amountSpent', '$spendLimit'] },
742
+ }, { $set: { status: enum_1.MarketingStatus.ACTIVE } });
743
+ }
744
+ calculateMarketingSpendPerOrder(order) {
745
+ const spendMap = new Map();
746
+ const addSpend = (marketingId, amount) => {
747
+ if (!amount || amount <= 0)
748
+ return;
749
+ spendMap.set(marketingId, (spendMap.get(marketingId) ?? 0) + amount);
750
+ };
751
+ for (const lineItem of order.lineItems ?? []) {
752
+ for (const marketingId of lineItem.marketings ?? []) {
753
+ const snap = lineItem.calculationSnap ?? {};
754
+ addSpend(marketingId._id, (Number(snap.itemDiscountByCompany) || 0) +
755
+ (Number(snap.itemDiscountByShop) || 0) +
756
+ (Number(snap.b1g1DiscountByCompany) || 0) +
757
+ (Number(snap.b1g1DiscountByShop) || 0));
758
+ }
759
+ }
760
+ if (order.adjustedFinance?.freeDelivery) {
761
+ for (const marketingId of order.marketings ?? []) {
762
+ addSpend(marketingId._id, (order.adjustedFinance.freeDelivery.companyCut ?? 0) +
763
+ (order.adjustedFinance.freeDelivery.shopCut ?? 0));
764
+ }
765
+ }
766
+ if (order.adjustedFinance?.pricing?.punchMarketingDiscount) {
767
+ for (const marketingId of order.marketings ?? []) {
768
+ addSpend(marketingId._id, order.adjustedFinance.pricing.punchMarketingDiscount);
769
+ }
770
+ }
771
+ return spendMap;
772
+ }
544
773
  };
545
774
  exports.MarketingService = MarketingService;
546
775
  exports.MarketingService = MarketingService = __decorate([
@@ -1 +1 @@
1
- {"version":3,"file":"marketing.service.js","sourceRoot":"/","sources":["modules/marketing/services/marketing.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAA4C;AAC5C,yCAAyC;AACzC,8DAA2D;AAE3D,sEASmD;AAenD,wEAA6G;AAE7G,8FAI4D;AAC5D,iGAAoG;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CAAC;gBACH,CAAC;YACF,CAAC;QACF,CAAC,CAAC,CAAC;QAEH,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC7B,CAAC;CACD,CAAA;AA1oBY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,gBAAO,GAAE;;GACG,gBAAgB,CA0oB5B;AAEY,QAAA,gBAAgB,GAAG,gBAAS,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC","sourcesContent":["import Container, { Service } from 'typedi';\nimport { TRPCError } from '@trpc/server';\nimport { dayjs } from '@lyxa.ai/core/dist/utilities/dayjs';\nimport { DocumentType, mongoose, ReturnModelType } from '@typegoose/typegoose';\nimport {\n\tBuy1Get1Marketing,\n\tDiscountMarketing,\n\tMarketingModel,\n\tMarketing as Model,\n\tRegularOrder,\n\tRegularOrderModel,\n\tShop,\n\tShopModel,\n} from '@lyxa.ai/core/dist/libraries/mongo/models';\nimport {\n\tAllMarketingsDTO,\n\tAllMarketingsValidationDTO,\n\tCreateProductMarketingDTO,\n\tProductEntireMenuMarketingHandlerDTO,\n\tUpdateMarketingDTO as UpdateDTO,\n} from '@modules/marketing/validations';\nimport {\n\tFilterDTO,\n\tPaginatedResponse,\n\tDeleteDTO,\n\tGetByIdInputDTO,\n} from '@lyxa.ai/core/dist/utilities/validation';\nimport { SoftDeleteModel } from '@lyxa.ai/core/dist/libraries/mongo/plugins/soft-delete-plugin';\nimport { createRawDocumentPaginatorObject, PaginatorOptions } from '@lyxa.ai/core/dist/utilities/pagination';\nimport { ModelType } from '@typegoose/typegoose/lib/types';\nimport {\n\tfilterRelevantChanges,\n\tgetChangedFields,\n\tpublishSyncSingleShopSectionsInCacheProcessEvent,\n} from '@lyxa.ai/core/dist/utilities/events-common-methods';\nimport { AdminActivityLogsEvent } from '@lyxa.ai/core/dist/libraries/event/events/admin-logs-event';\nimport {\n\tAdminLogsUpdatedFieldsType,\n\tMarketingStatus,\n\tRegularOrderStatus,\n} from '@lyxa.ai/core/dist/utilities/enum';\nimport { publishEvent } from '@lyxa.ai/core/dist/libraries/event';\nimport { BaseEvent } from '@lyxa.ai/core/dist/libraries/event/BaseEvent';\nimport {\n\tbuy1Get1MarketingService,\n\tdiscountMarketingService,\n\tfeaturedMarketingService,\n\tfreeDeliveryMarketingService,\n\tproductMarketingService,\n\tpunchMarketingService,\n} from '.';\nimport { MarketingType } from '@lyxa.ai/core/dist/utilities/enum';\nimport {\n\tconflictError,\n\tinternalServerError,\n\tnotFoundError,\n\tunauthorizedError,\n} from '@lyxa.ai/core/dist/utilities/error-common';\nimport { ChangeStreamOperationTypes } from '@lyxa.ai/core/dist/libraries/event/events/mongo-stream-changes-batch-process-shops-event';\n\n@Service()\nexport class MarketingService {\n\tprivate model: typeof MarketingModel & SoftDeleteModel<Model>;\n\tprivate shopModel: typeof ShopModel & SoftDeleteModel<Shop>;\n\tprivate orderModel: typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\n\n\tconstructor() {\n\t\tthis.model = MarketingModel as typeof MarketingModel & SoftDeleteModel<Model>;\n\t\tthis.shopModel = ShopModel as typeof ShopModel & SoftDeleteModel<Shop>;\n\t\tthis.orderModel = RegularOrderModel as typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\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(\n\t\tdata: AllMarketingsValidationDTO,\n\t\tadmin?: mongoose.Types.ObjectId\n\t): Promise<DocumentType<Model>> {\n\t\tconst now = dayjs().toDate();\n\n\t\tconst existingRecord = await this.model.findOne({\n\t\t\tshop: data.shop,\n\t\t\tmarketingType: data.marketingType,\n\t\t\t'duration.end': { $gt: now },\n\t\t\tstatus: MarketingStatus.ACTIVE,\n\t\t});\n\n\t\tif (existingRecord) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'CONFLICT',\n\t\t\t\tmessage: `This shop already has a ${data.marketingType} marketing`,\n\t\t\t});\n\t\t}\n\n\t\tif (data.isEntireMenu) {\n\t\t\tconst existingMarketing = await this.model.findOne({\n\t\t\t\tshop: data.shop,\n\t\t\t\t'duration.start': { $lt: now },\n\t\t\t\t'duration.end': { $gt: now },\n\t\t\t\tstatus: MarketingStatus.ACTIVE,\n\t\t\t\tmarketingType: { $in: [MarketingType.BUY1GET1, MarketingType.DISCOUNT] },\n\t\t\t});\n\n\t\t\tif (existingMarketing) {\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'CONFLICT',\n\t\t\t\t\tmessage: `Cannot create marketing for entire menu while another product based marketing exists for the shop`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (data.products && data.products.length > 0) {\n\t\t\tconst productIds = data.products.map((product: CreateProductMarketingDTO) => product.product);\n\n\t\t\tconst hasDuplicates = new Set(productIds.map(String)).size !== productIds.length;\n\n\t\t\tif (hasDuplicates) {\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\t\tmessage: `Product list contains duplicate products`,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst isAvailable = await productMarketingService.checkProductMarketingAvailability(productIds);\n\n\t\t\tif (!isAvailable) {\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'CONFLICT',\n\t\t\t\t\tmessage: `Product list contains products which already have marketing applied`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (admin) {\n\t\t\tdata.admin = admin;\n\t\t}\n\n\t\tlet marketing: AllMarketingsDTO;\n\n\t\tswitch (data.marketingType) {\n\t\t\tcase MarketingType.DISCOUNT: {\n\t\t\t\tmarketing = await discountMarketingService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.BUY1GET1: {\n\t\t\t\tmarketing = await buy1Get1MarketingService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.FEATURED: {\n\t\t\t\tif (!admin) {\n\t\t\t\t\tthrow new TRPCError({\n\t\t\t\t\t\tcode: 'UNAUTHORIZED',\n\t\t\t\t\t\tmessage: `Only admin is allowed to create ${data.marketingType} marketing`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tmarketing = await featuredMarketingService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.FREE_DELIVERY: {\n\t\t\t\tmarketing = await freeDeliveryMarketingService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.PUNCH_MARKETING: {\n\t\t\t\tmarketing = await punchMarketingService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tmarketing = await this.model.create(data, admin);\n\t\t\t}\n\t\t}\n\n\t\tawait this.model.populate(marketing, {\n\t\t\tpath: 'shop',\n\t\t\tmodel: this.shopModel,\n\t\t\tselect: '_id name shopId',\n\t\t});\n\n\t\tif (admin) {\n\t\t\tthis.logMarketingAdminAction(\n\t\t\t\tadmin,\n\t\t\t\tAdminLogsUpdatedFieldsType.ACTIVATED_MARKETING_PROMOTIONS,\n\t\t\t\t'',\n\t\t\t\tmarketing\n\t\t\t);\n\t\t}\n\t\tif (marketing)\n\t\t\tpublishSyncSingleShopSectionsInCacheProcessEvent({\n\t\t\t\tshopId: data.shop,\n\t\t\t\toperation: ChangeStreamOperationTypes.UPDATE,\n\t\t\t});\n\t\treturn marketing;\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(data: GetByIdInputDTO): Promise<DocumentType<Model>> {\n\t\tconst select = data.select || '';\n\t\tconst populate = data.populate || [];\n\t\tconst result = await this.model\n\t\t\t.findOne({\n\t\t\t\t_id: data._id,\n\t\t\t})\n\t\t\t.select(select)\n\t\t\t.populate(populate);\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 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,\n\t\t\t\tselect: data?.select,\n\t\t\t\tpopulate: data?.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 record\n\t * @param data Data to update\n\t */\n\tpublic async update(\n\t\t_id: mongoose.Types.ObjectId,\n\t\tdata: UpdateDTO,\n\t\tadmin?: mongoose.Types.ObjectId\n\t): Promise<DocumentType<Model>> {\n\t\tlet marketing: AllMarketingsDTO;\n\n\t\tconst oldMarketing = await this.model.findById(_id).populate({\n\t\t\tpath: 'shop',\n\t\t\tselect: '_id name shopId',\n\t\t});\n\n\t\tif (!oldMarketing) {\n\t\t\tnotFoundError('Could not find marketing');\n\t\t}\n\n\t\tif (\n\t\t\tdata.status &&\n\t\t\tdata.status === MarketingStatus.ACTIVE &&\n\t\t\toldMarketing.status === MarketingStatus.PAUSED\n\t\t) {\n\t\t\tawait this.verifyUnpauseConditions(_id);\n\t\t}\n\n\t\tswitch (oldMarketing.marketingType) {\n\t\t\tcase MarketingType.DISCOUNT: {\n\t\t\t\tmarketing = await discountMarketingService.update(_id, data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.BUY1GET1: {\n\t\t\t\tmarketing = await buy1Get1MarketingService.update(_id, data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.FEATURED: {\n\t\t\t\tif (!admin) {\n\t\t\t\t\tunauthorizedError(`Only admin is allowed to update ${data.marketingType} marketing`);\n\t\t\t\t}\n\t\t\t\tmarketing = await featuredMarketingService.update(_id, data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.FREE_DELIVERY: {\n\t\t\t\tmarketing = await freeDeliveryMarketingService.update(_id, data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.PUNCH_MARKETING: {\n\t\t\t\tmarketing = await punchMarketingService.update(_id, data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tmarketing = await this.model\n\t\t\t\t\t.findOneAndUpdate(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t_id: _id,\n\t\t\t\t\t\t\tdeletedAt: null,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdata,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnew: true,\n\t\t\t\t\t\t\trunValidators: true,\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t\t.populate({\n\t\t\t\t\t\tpath: 'shop',\n\t\t\t\t\t\tselect: '_id name shopId',\n\t\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (!marketing) {\n\t\t\tinternalServerError('Could not update marketing');\n\t\t}\n\n\t\tif (admin) {\n\t\t\tconst allChanges = getChangedFields(oldMarketing, marketing);\n\t\t\tconst relevantChanges = filterRelevantChanges(allChanges, data);\n\n\t\t\tif (Object.keys(relevantChanges).includes('status')) {\n\t\t\t\tif (data.status == MarketingStatus.ACTIVE) {\n\t\t\t\t\tthis.logMarketingAdminAction(\n\t\t\t\t\t\tadmin,\n\t\t\t\t\t\tAdminLogsUpdatedFieldsType.CONTINUED_MARKETING_PROMOTIONS,\n\t\t\t\t\t\toldMarketing,\n\t\t\t\t\t\tmarketing\n\t\t\t\t\t);\n\t\t\t\t} else if (data.status == MarketingStatus.PAUSED) {\n\t\t\t\t\tthis.logMarketingAdminAction(\n\t\t\t\t\t\tadmin,\n\t\t\t\t\t\tAdminLogsUpdatedFieldsType.PAUSED_MARKETING_PROMOTIONS,\n\t\t\t\t\t\toldMarketing,\n\t\t\t\t\t\tmarketing\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.logMarketingAdminAction(\n\t\t\t\tadmin,\n\t\t\t\tAdminLogsUpdatedFieldsType.EDITED_MARKETING_PROMOTIONS,\n\t\t\t\toldMarketing,\n\t\t\t\tmarketing\n\t\t\t);\n\t\t}\n\n\t\tif (data.status) {\n\t\t\tawait productMarketingService.syncProductMarketingInfo(_id);\n\t\t}\n\n\t\tpublishSyncSingleShopSectionsInCacheProcessEvent({\n\t\t\tshopId: marketing.shop,\n\t\t\toperation: ChangeStreamOperationTypes.UPDATE,\n\t\t});\n\n\t\treturn marketing;\n\t}\n\n\tprivate async verifyUnpauseConditions(marketingId: mongoose.Types.ObjectId): Promise<void> {\n\t\tconst marketing = await this.model.findOne({ _id: marketingId, deletedAt: null }).populate('products');\n\t\tif (!marketing) return;\n\n\t\tif ([MarketingType.BUY1GET1, MarketingType.DISCOUNT].includes(marketing.marketingType)) {\n\t\t\tconst typedMarketing = marketing as DocumentType<DiscountMarketing | Buy1Get1Marketing>;\n\t\t\tconst productIds = typedMarketing.products.map((product: any) => product.product);\n\t\t\tconst isAvailable = await productMarketingService.checkProductMarketingAvailability(productIds);\n\n\t\t\tif (!isAvailable) {\n\t\t\t\tconflictError(\"You can't activate discount and B1G1 on the same items at the same time\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async logMarketingAdminAction(\n\t\tadmin: mongoose.Types.ObjectId,\n\t\tactionType: AdminLogsUpdatedFieldsType,\n\t\toldDocument?: any,\n\t\tnewDocument?: any\n\t) {\n\t\tconst adminActivityLogsEvent: BaseEvent<Record<string, unknown>> = new AdminActivityLogsEvent({\n\t\t\tadmin,\n\t\t\tupdatedField: actionType,\n\t\t\toldDocument: oldDocument ?? '',\n\t\t\tnewDocument: newDocument ?? '',\n\t\t});\n\t\tawait publishEvent(adminActivityLogsEvent);\n\t}\n\n\t/**\n\t * Delete record\n\t * @param data Data for delete\n\t */\n\tpublic async deleteById(data: DeleteDTO, admin?: mongoose.Types.ObjectId): Promise<string> {\n\t\tconst { _id, softDelete } = data;\n\n\t\tconst record = await this.model.findById(_id).populate({\n\t\t\tpath: 'shop',\n\t\t\tselect: '_id name shopId',\n\t\t});\n\n\t\tif (!record) {\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\trecord.status = MarketingStatus.DELETED;\n\t\tawait record.save();\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: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Unable to delete marketing',\n\t\t\t});\n\t\t}\n\n\t\tif (admin) {\n\t\t\tthis.logMarketingAdminAction(admin, AdminLogsUpdatedFieldsType.DELETED_MARKETING_PROMOTIONS, record);\n\t\t}\n\n\t\tproductMarketingService.deleteMany({ marketing: data._id }, data.softDelete);\n\t\tpublishSyncSingleShopSectionsInCacheProcessEvent({\n\t\t\tshopId: record.shop._id,\n\t\t\toperation: ChangeStreamOperationTypes.DELETE,\n\t\t});\n\t\treturn 'Record deleted successfully';\n\t}\n\n\tpublic async handleNewProductForEntireMenuMarketing(data: ProductEntireMenuMarketingHandlerDTO) {\n\t\tconst existingMarketing = await this.model.findOne({\n\t\t\tshop: data.shop,\n\t\t\tmarketingType: { $in: [MarketingType.BUY1GET1, MarketingType.DISCOUNT] },\n\t\t\t'duration.end': { $gt: new Date() },\n\t\t\tstatus: MarketingStatus.ACTIVE,\n\t\t\tisEntireMenu: true,\n\t\t});\n\n\t\t// check if existing marketing\n\t\tif (existingMarketing) {\n\t\t\tconst isAvailable = await productMarketingService.checkProductMarketingAvailability([data.product]);\n\t\t\tif (isAvailable) {\n\t\t\t\tconst productMarketingData: CreateProductMarketingDTO = {\n\t\t\t\t\tproduct: data.product,\n\t\t\t\t\tmarketing: existingMarketing._id,\n\t\t\t\t};\n\t\t\t\tif (existingMarketing.marketingType == MarketingType.BUY1GET1) {\n\t\t\t\t\tproductMarketingData.isBuy1Get1 = true;\n\t\t\t\t}\n\t\t\t\tif (existingMarketing.marketingType == MarketingType.DISCOUNT) {\n\t\t\t\t\tproductMarketingData.value = (existingMarketing as DocumentType<DiscountMarketing>).value;\n\t\t\t\t\tproductMarketingData.valueType = (existingMarketing as DocumentType<DiscountMarketing>).valueType;\n\t\t\t\t}\n\t\t\t\tconst result = await productMarketingService.create(productMarketingData);\n\n\t\t\t\tconsole.log(`Created product marketing: ${result}`);\n\t\t\t}\n\t\t}\n\n\t\treturn 'Product handled successfully';\n\t}\n\n\tpublic async evaluateMarketingSpendLimits(marketings: mongoose.Types.ObjectId[]) {\n\t\tthis.evaluateItemBasedMarketings(marketings);\n\t\tthis.evalulateFreeDeliveryMarketings(marketings);\n\n\t\treturn 'Evaluated spend limits';\n\t}\n\n\tprivate async evaluateItemBasedMarketings(marketings: mongoose.Types.ObjectId[]) {\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\t/**\n\t\t\t * Only orders that reference at least one of the target marketings\n\t\t\t * (fast pre-filter)\n\t\t\t */\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t$and: [{ marketings: { $exists: true } }, { marketings: { $ne: null } }],\n\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\t$expr: {\n\t\t\t\t\t\t$gt: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$size: {\n\t\t\t\t\t\t\t\t\t$setIntersection: ['$marketings', marketings],\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/**\n\t\t\t * Lookup line items\n\t\t\t */\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'lineItems',\n\t\t\t\t\tlocalField: 'cart',\n\t\t\t\t\tforeignField: 'cart',\n\t\t\t\t\tas: 'lineItems',\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t/**\n\t\t\t * Unwind line items\n\t\t\t */\n\t\t\t{\n\t\t\t\t$unwind: '$lineItems',\n\t\t\t},\n\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'marketings',\n\t\t\t\t\tlocalField: 'lineItems.marketings',\n\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\tas: 'marketing',\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t/**\n\t\t\t * Unwind marketing IDs\n\t\t\t */\n\t\t\t{\n\t\t\t\t$unwind: '$marketing',\n\t\t\t},\n\n\t\t\t/**\n\t\t\t * Group by marketing ID\n\t\t\t */\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: '$marketing._id',\n\t\t\t\t\tmarketingType: { $first: '$marketing.marketingType' },\n\t\t\t\t\tspendLimit: { $first: '$marketing.spendLimit' },\n\t\t\t\t\tisSpendLimitEnabled: { $first: '$marketing.isSpendLimitEnabled' },\n\n\t\t\t\t\ttotalCompanyDiscount: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$marketing.marketingType', MarketingType.DISCOUNT] },\n\t\t\t\t\t\t\t\t'$lineItems.calculationSnap.itemDiscountByCompany',\n\t\t\t\t\t\t\t\t0,\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\ttotalShopDiscount: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$marketing.marketingType', MarketingType.DISCOUNT] },\n\t\t\t\t\t\t\t\t'$lineItems.calculationSnap.itemDiscountByShop',\n\t\t\t\t\t\t\t\t0,\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// B1G1 fields\n\t\t\t\t\ttotalB1G1Company: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$marketing.marketingType', MarketingType.BUY1GET1] },\n\t\t\t\t\t\t\t\t'$lineItems.calculationSnap.b1g1DiscountByCompany',\n\t\t\t\t\t\t\t\t0,\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\ttotalB1G1Shop: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$marketing.marketingType', MarketingType.BUY1GET1] },\n\t\t\t\t\t\t\t\t'$lineItems.calculationSnap.b1g1DiscountByShop',\n\t\t\t\t\t\t\t\t0,\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\tconst promises: Promise<any>[] = [];\n\n\t\tresult?.forEach(async marketing => {\n\t\t\tif (marketing.isSpendLimitEnabled) {\n\t\t\t\tconst totalSpent =\n\t\t\t\t\tmarketing.totalCompanyDiscount +\n\t\t\t\t\tmarketing.totalShopDiscount +\n\t\t\t\t\tmarketing.totalB1G1Company +\n\t\t\t\t\tmarketing.totalB1G1Shop;\n\n\t\t\t\tif (totalSpent >= marketing.spendLimit) {\n\t\t\t\t\tawait this.model.findByIdAndUpdate(marketing._id, {\n\t\t\t\t\t\tstatus: MarketingStatus.EXPIRED,\n\t\t\t\t\t});\n\n\t\t\t\t\tpromises.push(productMarketingService.syncProductMarketingInfo(marketing._id));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tawait Promise.all(promises);\n\t}\n\n\tprivate async evalulateFreeDeliveryMarketings(marketings: mongoose.Types.ObjectId[]) {\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\t/**\n\t\t\t * Only orders that reference at least one of the target marketings\n\t\t\t * (fast pre-filter)\n\t\t\t */\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t$and: [{ marketings: { $exists: true } }, { marketings: { $ne: null } }],\n\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\t$expr: {\n\t\t\t\t\t\t$gt: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$size: {\n\t\t\t\t\t\t\t\t\t$setIntersection: ['$marketings', marketings],\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{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'marketings',\n\t\t\t\t\tlocalField: 'marketings',\n\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\tas: 'marketing',\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t{\n\t\t\t\t$unwind: '$marketing',\n\t\t\t},\n\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t'marketing.marketingType': MarketingType.FREE_DELIVERY,\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t/**\n\t\t\t * Group by marketing ID\n\t\t\t */\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: '$marketing._id',\n\t\t\t\t\tmarketingType: { $first: '$marketing.marketingType' },\n\t\t\t\t\tspendLimit: { $first: '$marketing.spendLimit' },\n\t\t\t\t\tisSpendLimitEnabled: { $first: '$marketing.isSpendLimitEnabled' },\n\n\t\t\t\t\ttotalFreeDeliveryCompany: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$marketing.marketingType', MarketingType.FREE_DELIVERY] },\n\t\t\t\t\t\t\t\t'$adjustedFinance.freeDelivery.companyCut',\n\t\t\t\t\t\t\t\t0,\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\ttotalFreeDeliveryShop: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$marketing.marketingType', MarketingType.FREE_DELIVERY] },\n\t\t\t\t\t\t\t\t'$adjustedFinance.freeDelivery.shopCut',\n\t\t\t\t\t\t\t\t0,\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\tconst promises: Promise<any>[] = [];\n\n\t\tresult?.forEach(marketing => {\n\t\t\tif (marketing.isSpendLimitEnabled) {\n\t\t\t\tconst totalSpent = marketing.totalFreeDeliveryCompany + marketing.totalFreeDeliveryShop;\n\n\t\t\t\tif (totalSpent >= marketing.spendLimit) {\n\t\t\t\t\tpromises.push(\n\t\t\t\t\t\tthis.model.findByIdAndUpdate(marketing._id, {\n\t\t\t\t\t\t\tstatus: MarketingStatus.EXPIRED,\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\tawait Promise.all(promises);\n\t}\n}\n\nexport const marketingService = Container.get(MarketingService);\n"]}
1
+ {"version":3,"file":"marketing.service.js","sourceRoot":"/","sources":["modules/marketing/services/marketing.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAA4C;AAC5C,yCAAyC;AACzC,8DAA2D;AAE3D,sEAUmD;AAenD,wEAA6G;AAE7G,8FAI4D;AAC5D,iGAAoG;AACpG,4DAI2C;AAC3C,8DAAkE;AAElE,wBAOW;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AkB,CAAC,IAAI,CAAC,CAAC,CACvC,CAAC;YACH,CAAC;QACF,CAAC;QAKD,IAAI,KAAK,CAAC,eAAe,EAAE,YAAY,EAAE,CAAC;YACzC,KAAK,MAAM,WAAW,IAAI,KAAK,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC;gBAClD,QAAQ,CACP,WAAW,CAAC,GAAG,EACf,CAAC,KAAK,CAAC,eAAe,CAAC,YAAY,CAAC,UAAU,IAAI,CAAC,CAAC;oBACnD,CAAC,KAAK,CAAC,eAAe,CAAC,YAAY,CAAC,OAAO,IAAI,CAAC,CAAC,CAClD,CAAC;YACH,CAAC;QACF,CAAC;QAKD,IAAI,KAAK,CAAC,eAAe,EAAE,OAAO,EAAE,sBAAsB,EAAE,CAAC;YAC5D,KAAK,MAAM,WAAW,IAAI,KAAK,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC;gBAClD,QAAQ,CAAC,WAAW,CAAC,GAAG,EAAE,KAAK,CAAC,eAAe,CAAC,OAAO,CAAC,sBAAsB,CAAC,CAAC;YACjF,CAAC;QACF,CAAC;QAED,OAAO,QAAQ,CAAC;IACjB,CAAC;CACD,CAAA;AA96BY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,gBAAO,GAAE;;GACG,gBAAgB,CA86B5B;AAEY,QAAA,gBAAgB,GAAG,gBAAS,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC","sourcesContent":["import Container, { Service } from 'typedi';\nimport { TRPCError } from '@trpc/server';\nimport { dayjs } from '@lyxa.ai/core/dist/utilities/dayjs';\nimport { DocumentType, mongoose, ReturnModelType } from '@typegoose/typegoose';\nimport {\n\tBuy1Get1Marketing,\n\tDiscountMarketing,\n\tLineItem,\n\tMarketingModel,\n\tMarketing as Model,\n\tRegularOrder,\n\tRegularOrderModel,\n\tShop,\n\tShopModel,\n} from '@lyxa.ai/core/dist/libraries/mongo/models';\nimport {\n\tAllMarketingsDTO,\n\tAllMarketingsValidationDTO,\n\tCreateProductMarketingDTO,\n\tProductEntireMenuMarketingHandlerDTO,\n\tUpdateMarketingDTO as UpdateDTO,\n} from '@modules/marketing/validations';\nimport {\n\tFilterDTO,\n\tPaginatedResponse,\n\tDeleteDTO,\n\tGetByIdInputDTO,\n} from '@lyxa.ai/core/dist/utilities/validation';\nimport { SoftDeleteModel } from '@lyxa.ai/core/dist/libraries/mongo/plugins/soft-delete-plugin';\nimport { createRawDocumentPaginatorObject, PaginatorOptions } from '@lyxa.ai/core/dist/utilities/pagination';\nimport { ModelType } from '@typegoose/typegoose/lib/types';\nimport {\n\tfilterRelevantChanges,\n\tgetChangedFields,\n\tpublishSyncSingleShopSectionsInCacheProcessEvent,\n} from '@lyxa.ai/core/dist/utilities/events-common-methods';\nimport { AdminActivityLogsEvent } from '@lyxa.ai/core/dist/libraries/event/events/admin-logs-event';\nimport {\n\tAdminLogsUpdatedFieldsType,\n\tMarketingStatus,\n\tRegularOrderStatus,\n} from '@lyxa.ai/core/dist/utilities/enum';\nimport { publishEvent } from '@lyxa.ai/core/dist/libraries/event';\nimport { BaseEvent } from '@lyxa.ai/core/dist/libraries/event/BaseEvent';\nimport {\n\tbuy1Get1MarketingService,\n\tdiscountMarketingService,\n\tfeaturedMarketingService,\n\tfreeDeliveryMarketingService,\n\tproductMarketingService,\n\tpunchMarketingService,\n} from '.';\nimport { MarketingType } from '@lyxa.ai/core/dist/utilities/enum';\nimport {\n\tconflictError,\n\tinternalServerError,\n\tnotFoundError,\n\tunauthorizedError,\n} from '@lyxa.ai/core/dist/utilities/error-common';\nimport { ChangeStreamOperationTypes } from '@lyxa.ai/core/dist/libraries/event/events/mongo-stream-changes-batch-process-shops-event';\n\n@Service()\nexport class MarketingService {\n\tprivate model: typeof MarketingModel & SoftDeleteModel<Model>;\n\tprivate shopModel: typeof ShopModel & SoftDeleteModel<Shop>;\n\tprivate orderModel: typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\n\n\tconstructor() {\n\t\tthis.model = MarketingModel as typeof MarketingModel & SoftDeleteModel<Model>;\n\t\tthis.shopModel = ShopModel as typeof ShopModel & SoftDeleteModel<Shop>;\n\t\tthis.orderModel = RegularOrderModel as typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\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(\n\t\tdata: AllMarketingsValidationDTO,\n\t\tadmin?: mongoose.Types.ObjectId\n\t): Promise<DocumentType<Model>> {\n\t\tconst now = dayjs().toDate();\n\n\t\tconst existingRecord = await this.model.findOne({\n\t\t\tshop: data.shop,\n\t\t\tmarketingType: data.marketingType,\n\t\t\t'duration.end': { $gt: now },\n\t\t\tstatus: MarketingStatus.ACTIVE,\n\t\t});\n\n\t\tif (existingRecord) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'CONFLICT',\n\t\t\t\tmessage: `This shop already has a ${data.marketingType} marketing`,\n\t\t\t});\n\t\t}\n\n\t\tif (data.isEntireMenu) {\n\t\t\tconst existingMarketing = await this.model.findOne({\n\t\t\t\tshop: data.shop,\n\t\t\t\t'duration.start': { $lt: now },\n\t\t\t\t'duration.end': { $gt: now },\n\t\t\t\tstatus: MarketingStatus.ACTIVE,\n\t\t\t\tmarketingType: { $in: [MarketingType.BUY1GET1, MarketingType.DISCOUNT] },\n\t\t\t});\n\n\t\t\tif (existingMarketing) {\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'CONFLICT',\n\t\t\t\t\tmessage: `Cannot create marketing for entire menu while another product based marketing exists for the shop`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (data.products && data.products.length > 0) {\n\t\t\tconst productIds = data.products.map((product: CreateProductMarketingDTO) => product.product);\n\n\t\t\tconst hasDuplicates = new Set(productIds.map(String)).size !== productIds.length;\n\n\t\t\tif (hasDuplicates) {\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\t\tmessage: `Product list contains duplicate products`,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst isAvailable = await productMarketingService.checkProductMarketingAvailability(productIds);\n\n\t\t\tif (!isAvailable) {\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'CONFLICT',\n\t\t\t\t\tmessage: `Product list contains products which already have marketing applied`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (admin) {\n\t\t\tdata.admin = admin;\n\t\t}\n\n\t\tlet marketing: AllMarketingsDTO;\n\n\t\tswitch (data.marketingType) {\n\t\t\tcase MarketingType.DISCOUNT: {\n\t\t\t\tmarketing = await discountMarketingService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.BUY1GET1: {\n\t\t\t\tmarketing = await buy1Get1MarketingService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.FEATURED: {\n\t\t\t\tif (!admin) {\n\t\t\t\t\tthrow new TRPCError({\n\t\t\t\t\t\tcode: 'UNAUTHORIZED',\n\t\t\t\t\t\tmessage: `Only admin is allowed to create ${data.marketingType} marketing`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tmarketing = await featuredMarketingService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.FREE_DELIVERY: {\n\t\t\t\tmarketing = await freeDeliveryMarketingService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.PUNCH_MARKETING: {\n\t\t\t\tmarketing = await punchMarketingService.create(data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tmarketing = await this.model.create(data, admin);\n\t\t\t}\n\t\t}\n\n\t\tawait this.model.populate(marketing, {\n\t\t\tpath: 'shop',\n\t\t\tmodel: this.shopModel,\n\t\t\tselect: '_id name shopId',\n\t\t});\n\n\t\tif (admin) {\n\t\t\tthis.logMarketingAdminAction(\n\t\t\t\tadmin,\n\t\t\t\tAdminLogsUpdatedFieldsType.ACTIVATED_MARKETING_PROMOTIONS,\n\t\t\t\t'',\n\t\t\t\tmarketing\n\t\t\t);\n\t\t}\n\t\tif (marketing)\n\t\t\tpublishSyncSingleShopSectionsInCacheProcessEvent({\n\t\t\t\tshopId: data.shop,\n\t\t\t\toperation: ChangeStreamOperationTypes.UPDATE,\n\t\t\t});\n\t\treturn marketing;\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(data: GetByIdInputDTO): Promise<DocumentType<Model>> {\n\t\tconst select = data.select || '';\n\t\tconst populate = data.populate || [];\n\t\tconst result = await this.model\n\t\t\t.findOne({\n\t\t\t\t_id: data._id,\n\t\t\t})\n\t\t\t.select(select)\n\t\t\t.populate(populate);\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 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,\n\t\t\t\tselect: data?.select,\n\t\t\t\tpopulate: data?.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 record\n\t * @param data Data to update\n\t */\n\tpublic async update(\n\t\t_id: mongoose.Types.ObjectId,\n\t\tdata: UpdateDTO,\n\t\tadmin?: mongoose.Types.ObjectId\n\t): Promise<DocumentType<Model>> {\n\t\tlet marketing: AllMarketingsDTO;\n\n\t\tconst oldMarketing = await this.model.findById(_id).populate({\n\t\t\tpath: 'shop',\n\t\t\tselect: '_id name shopId',\n\t\t});\n\n\t\tif (!oldMarketing) {\n\t\t\tnotFoundError('Could not find marketing');\n\t\t}\n\n\t\tif (\n\t\t\tdata.status &&\n\t\t\tdata.status === MarketingStatus.ACTIVE &&\n\t\t\toldMarketing.status === MarketingStatus.PAUSED\n\t\t) {\n\t\t\tawait this.verifyUnpauseConditions(_id);\n\t\t}\n\n\t\tswitch (oldMarketing.marketingType) {\n\t\t\tcase MarketingType.DISCOUNT: {\n\t\t\t\tmarketing = await discountMarketingService.update(_id, data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.BUY1GET1: {\n\t\t\t\tmarketing = await buy1Get1MarketingService.update(_id, data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.FEATURED: {\n\t\t\t\tif (!admin) {\n\t\t\t\t\tunauthorizedError(`Only admin is allowed to update ${data.marketingType} marketing`);\n\t\t\t\t}\n\t\t\t\tmarketing = await featuredMarketingService.update(_id, data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.FREE_DELIVERY: {\n\t\t\t\tmarketing = await freeDeliveryMarketingService.update(_id, data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase MarketingType.PUNCH_MARKETING: {\n\t\t\t\tmarketing = await punchMarketingService.update(_id, data);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tmarketing = await this.model\n\t\t\t\t\t.findOneAndUpdate(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t_id: _id,\n\t\t\t\t\t\t\tdeletedAt: null,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdata,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnew: true,\n\t\t\t\t\t\t\trunValidators: true,\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t\t.populate({\n\t\t\t\t\t\tpath: 'shop',\n\t\t\t\t\t\tselect: '_id name shopId',\n\t\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (!marketing) {\n\t\t\tinternalServerError('Could not update marketing');\n\t\t}\n\n\t\tif (admin) {\n\t\t\tconst allChanges = getChangedFields(oldMarketing, marketing);\n\t\t\tconst relevantChanges = filterRelevantChanges(allChanges, data);\n\n\t\t\tif (Object.keys(relevantChanges).includes('status')) {\n\t\t\t\tif (data.status == MarketingStatus.ACTIVE) {\n\t\t\t\t\tthis.logMarketingAdminAction(\n\t\t\t\t\t\tadmin,\n\t\t\t\t\t\tAdminLogsUpdatedFieldsType.CONTINUED_MARKETING_PROMOTIONS,\n\t\t\t\t\t\toldMarketing,\n\t\t\t\t\t\tmarketing\n\t\t\t\t\t);\n\t\t\t\t} else if (data.status == MarketingStatus.PAUSED) {\n\t\t\t\t\tthis.logMarketingAdminAction(\n\t\t\t\t\t\tadmin,\n\t\t\t\t\t\tAdminLogsUpdatedFieldsType.PAUSED_MARKETING_PROMOTIONS,\n\t\t\t\t\t\toldMarketing,\n\t\t\t\t\t\tmarketing\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.logMarketingAdminAction(\n\t\t\t\tadmin,\n\t\t\t\tAdminLogsUpdatedFieldsType.EDITED_MARKETING_PROMOTIONS,\n\t\t\t\toldMarketing,\n\t\t\t\tmarketing\n\t\t\t);\n\t\t}\n\n\t\tif (data.status) {\n\t\t\tawait productMarketingService.syncProductMarketingInfo(_id);\n\t\t}\n\n\t\tpublishSyncSingleShopSectionsInCacheProcessEvent({\n\t\t\tshopId: marketing.shop,\n\t\t\toperation: ChangeStreamOperationTypes.UPDATE,\n\t\t});\n\n\t\treturn marketing;\n\t}\n\n\tprivate async verifyUnpauseConditions(marketingId: mongoose.Types.ObjectId): Promise<void> {\n\t\tconst marketing = await this.model.findOne({ _id: marketingId, deletedAt: null }).populate('products');\n\t\tif (!marketing) return;\n\n\t\tif ([MarketingType.BUY1GET1, MarketingType.DISCOUNT].includes(marketing.marketingType)) {\n\t\t\tconst typedMarketing = marketing as DocumentType<DiscountMarketing | Buy1Get1Marketing>;\n\t\t\tconst productIds = typedMarketing.products.map((product: any) => product.product);\n\t\t\tconst isAvailable = await productMarketingService.checkProductMarketingAvailability(productIds);\n\n\t\t\tif (!isAvailable) {\n\t\t\t\tconflictError(\"You can't activate discount and B1G1 on the same items at the same time\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async logMarketingAdminAction(\n\t\tadmin: mongoose.Types.ObjectId,\n\t\tactionType: AdminLogsUpdatedFieldsType,\n\t\toldDocument?: any,\n\t\tnewDocument?: any\n\t) {\n\t\tconst adminActivityLogsEvent: BaseEvent<Record<string, unknown>> = new AdminActivityLogsEvent({\n\t\t\tadmin,\n\t\t\tupdatedField: actionType,\n\t\t\toldDocument: oldDocument ?? '',\n\t\t\tnewDocument: newDocument ?? '',\n\t\t});\n\t\tawait publishEvent(adminActivityLogsEvent);\n\t}\n\n\t/**\n\t * Delete record\n\t * @param data Data for delete\n\t */\n\tpublic async deleteById(data: DeleteDTO, admin?: mongoose.Types.ObjectId): Promise<string> {\n\t\tconst { _id, softDelete } = data;\n\n\t\tconst record = await this.model.findById(_id).populate({\n\t\t\tpath: 'shop',\n\t\t\tselect: '_id name shopId',\n\t\t});\n\n\t\tif (!record) {\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\trecord.status = MarketingStatus.DELETED;\n\t\tawait record.save();\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: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Unable to delete marketing',\n\t\t\t});\n\t\t}\n\n\t\tif (admin) {\n\t\t\tthis.logMarketingAdminAction(admin, AdminLogsUpdatedFieldsType.DELETED_MARKETING_PROMOTIONS, record);\n\t\t}\n\n\t\tproductMarketingService.deleteMany({ marketing: data._id }, data.softDelete);\n\t\tpublishSyncSingleShopSectionsInCacheProcessEvent({\n\t\t\tshopId: record.shop._id,\n\t\t\toperation: ChangeStreamOperationTypes.DELETE,\n\t\t});\n\t\treturn 'Record deleted successfully';\n\t}\n\n\tpublic async handleNewProductForEntireMenuMarketing(data: ProductEntireMenuMarketingHandlerDTO) {\n\t\tconst existingMarketing = await this.model.findOne({\n\t\t\tshop: data.shop,\n\t\t\tmarketingType: { $in: [MarketingType.BUY1GET1, MarketingType.DISCOUNT] },\n\t\t\t'duration.end': { $gt: new Date() },\n\t\t\tstatus: MarketingStatus.ACTIVE,\n\t\t\tisEntireMenu: true,\n\t\t});\n\n\t\t// check if existing marketing\n\t\tif (existingMarketing) {\n\t\t\tconst isAvailable = await productMarketingService.checkProductMarketingAvailability([data.product]);\n\t\t\tif (isAvailable) {\n\t\t\t\tconst productMarketingData: CreateProductMarketingDTO = {\n\t\t\t\t\tproduct: data.product,\n\t\t\t\t\tmarketing: existingMarketing._id,\n\t\t\t\t};\n\t\t\t\tif (existingMarketing.marketingType == MarketingType.BUY1GET1) {\n\t\t\t\t\tproductMarketingData.isBuy1Get1 = true;\n\t\t\t\t}\n\t\t\t\tif (existingMarketing.marketingType == MarketingType.DISCOUNT) {\n\t\t\t\t\tproductMarketingData.value = (existingMarketing as DocumentType<DiscountMarketing>).value;\n\t\t\t\t\tproductMarketingData.valueType = (existingMarketing as DocumentType<DiscountMarketing>).valueType;\n\t\t\t\t}\n\t\t\t\tconst result = await productMarketingService.create(productMarketingData);\n\n\t\t\t\tconsole.log(`Created product marketing: ${result}`);\n\t\t\t}\n\t\t}\n\n\t\treturn 'Product handled successfully';\n\t}\n\n\tpublic async evaluateMarketingSpendLimits(marketings: mongoose.Types.ObjectId[]) {\n\t\tthis.evaluateItemBasedMarketings(marketings);\n\t\tthis.evalulateFreeDeliveryMarketings(marketings);\n\n\t\treturn 'Evaluated spend limits';\n\t}\n\n\tprivate async evaluateItemBasedMarketings(marketings: mongoose.Types.ObjectId[]) {\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\t/**\n\t\t\t * Only orders that reference at least one of the target marketings\n\t\t\t * (fast pre-filter)\n\t\t\t */\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t$and: [{ marketings: { $exists: true } }, { marketings: { $ne: null } }],\n\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\t$expr: {\n\t\t\t\t\t\t$gt: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$size: {\n\t\t\t\t\t\t\t\t\t$setIntersection: ['$marketings', marketings],\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/**\n\t\t\t * Lookup line items\n\t\t\t */\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'lineItems',\n\t\t\t\t\tlocalField: 'cart',\n\t\t\t\t\tforeignField: 'cart',\n\t\t\t\t\tas: 'lineItems',\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t/**\n\t\t\t * Unwind line items\n\t\t\t */\n\t\t\t{\n\t\t\t\t$unwind: '$lineItems',\n\t\t\t},\n\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'marketings',\n\t\t\t\t\tlocalField: 'lineItems.marketings',\n\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\tas: 'marketing',\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t/**\n\t\t\t * Unwind marketing IDs\n\t\t\t */\n\t\t\t{\n\t\t\t\t$unwind: '$marketing',\n\t\t\t},\n\n\t\t\t/**\n\t\t\t * Group by marketing ID\n\t\t\t */\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: '$marketing._id',\n\t\t\t\t\tmarketingType: { $first: '$marketing.marketingType' },\n\t\t\t\t\tspendLimit: { $first: '$marketing.spendLimit' },\n\t\t\t\t\tisSpendLimitEnabled: { $first: '$marketing.isSpendLimitEnabled' },\n\n\t\t\t\t\ttotalCompanyDiscount: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$marketing.marketingType', MarketingType.DISCOUNT] },\n\t\t\t\t\t\t\t\t'$lineItems.calculationSnap.itemDiscountByCompany',\n\t\t\t\t\t\t\t\t0,\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\ttotalShopDiscount: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$marketing.marketingType', MarketingType.DISCOUNT] },\n\t\t\t\t\t\t\t\t'$lineItems.calculationSnap.itemDiscountByShop',\n\t\t\t\t\t\t\t\t0,\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// B1G1 fields\n\t\t\t\t\ttotalB1G1Company: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$marketing.marketingType', MarketingType.BUY1GET1] },\n\t\t\t\t\t\t\t\t'$lineItems.calculationSnap.b1g1DiscountByCompany',\n\t\t\t\t\t\t\t\t0,\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\ttotalB1G1Shop: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$marketing.marketingType', MarketingType.BUY1GET1] },\n\t\t\t\t\t\t\t\t'$lineItems.calculationSnap.b1g1DiscountByShop',\n\t\t\t\t\t\t\t\t0,\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\tconst promises: Promise<any>[] = [];\n\n\t\tresult?.forEach(async marketing => {\n\t\t\tif (marketing.isSpendLimitEnabled) {\n\t\t\t\tconst totalSpent =\n\t\t\t\t\tmarketing.totalCompanyDiscount +\n\t\t\t\t\tmarketing.totalShopDiscount +\n\t\t\t\t\tmarketing.totalB1G1Company +\n\t\t\t\t\tmarketing.totalB1G1Shop;\n\n\t\t\t\tif (totalSpent >= marketing.spendLimit) {\n\t\t\t\t\tawait this.model.findByIdAndUpdate(marketing._id, {\n\t\t\t\t\t\tstatus: MarketingStatus.EXPIRED,\n\t\t\t\t\t});\n\n\t\t\t\t\tpromises.push(productMarketingService.syncProductMarketingInfo(marketing._id));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tawait Promise.all(promises);\n\t}\n\n\tprivate async evalulateFreeDeliveryMarketings(marketings: mongoose.Types.ObjectId[]) {\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\t/**\n\t\t\t * Only orders that reference at least one of the target marketings\n\t\t\t * (fast pre-filter)\n\t\t\t */\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t$and: [{ marketings: { $exists: true } }, { marketings: { $ne: null } }],\n\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\t$expr: {\n\t\t\t\t\t\t$gt: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$size: {\n\t\t\t\t\t\t\t\t\t$setIntersection: ['$marketings', marketings],\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{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'marketings',\n\t\t\t\t\tlocalField: 'marketings',\n\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\tas: 'marketing',\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t{\n\t\t\t\t$unwind: '$marketing',\n\t\t\t},\n\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t'marketing.marketingType': MarketingType.FREE_DELIVERY,\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t/**\n\t\t\t * Group by marketing ID\n\t\t\t */\n\t\t\t{\n\t\t\t\t$group: {\n\t\t\t\t\t_id: '$marketing._id',\n\t\t\t\t\tmarketingType: { $first: '$marketing.marketingType' },\n\t\t\t\t\tspendLimit: { $first: '$marketing.spendLimit' },\n\t\t\t\t\tisSpendLimitEnabled: { $first: '$marketing.isSpendLimitEnabled' },\n\n\t\t\t\t\ttotalFreeDeliveryCompany: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$marketing.marketingType', MarketingType.FREE_DELIVERY] },\n\t\t\t\t\t\t\t\t'$adjustedFinance.freeDelivery.companyCut',\n\t\t\t\t\t\t\t\t0,\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\ttotalFreeDeliveryShop: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$marketing.marketingType', MarketingType.FREE_DELIVERY] },\n\t\t\t\t\t\t\t\t'$adjustedFinance.freeDelivery.shopCut',\n\t\t\t\t\t\t\t\t0,\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\tconst promises: Promise<any>[] = [];\n\n\t\tresult?.forEach(marketing => {\n\t\t\tif (marketing.isSpendLimitEnabled) {\n\t\t\t\tconst totalSpent = marketing.totalFreeDeliveryCompany + marketing.totalFreeDeliveryShop;\n\n\t\t\t\tif (totalSpent >= marketing.spendLimit) {\n\t\t\t\t\tpromises.push(\n\t\t\t\t\t\tthis.model.findByIdAndUpdate(marketing._id, {\n\t\t\t\t\t\t\tstatus: MarketingStatus.EXPIRED,\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\tawait Promise.all(promises);\n\t}\n\n\tpublic async calculateMarketingSpent(marketingId: mongoose.Types.ObjectId): Promise<any> {\n\t\tconst marketing = await this.model.findById(marketingId).lean();\n\n\t\tif (!marketing) {\n\t\t\tthrow new Error('Marketing not found');\n\t\t}\n\n\t\tlet amount = 0;\n\n\t\tswitch (marketing.marketingType) {\n\t\t\tcase MarketingType.FREE_DELIVERY:\n\t\t\t\tamount = await this.calculateFreeDeliverySpent(marketingId);\n\t\t\t\tbreak;\n\n\t\t\tcase MarketingType.DISCOUNT:\n\t\t\tcase MarketingType.BUY1GET1:\n\t\t\t\tamount = await this.calculateItemBasedSpent(marketingId);\n\t\t\t\tbreak;\n\n\t\t\tcase MarketingType.PUNCH_MARKETING:\n\t\t\t\tamount = await this.calculatePunchMarketingSpent(marketingId);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tamount = 0;\n\t\t}\n\n\t\treturn {\n\t\t\tamount,\n\t\t\tmarketingType: marketing.marketingType,\n\t\t};\n\t}\n\n\tprivate async calculateItemBasedSpent(marketingId: mongoose.Types.ObjectId): Promise<number> {\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t$and: [{ marketings: { $exists: true } }, { marketings: { $ne: null } }],\n\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\tmarketings: marketingId,\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: 'lineItems',\n\t\t\t\t\tlocalField: 'cart',\n\t\t\t\t\tforeignField: 'cart',\n\t\t\t\t\tas: 'lineItems',\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ $unwind: '$lineItems' },\n\t\t\t{\n\t\t\t\t$lookup: {\n\t\t\t\t\tfrom: 'marketings',\n\t\t\t\t\tlocalField: 'lineItems.marketings',\n\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\tas: 'marketing',\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ $unwind: '$marketing' },\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t'marketing._id': marketingId,\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\ttotalCompanyDiscount: {\n\t\t\t\t\t\t$sum: '$lineItems.calculationSnap.itemDiscountByCompany',\n\t\t\t\t\t},\n\t\t\t\t\ttotalShopDiscount: {\n\t\t\t\t\t\t$sum: '$lineItems.calculationSnap.itemDiscountByShop',\n\t\t\t\t\t},\n\t\t\t\t\ttotalB1G1Company: {\n\t\t\t\t\t\t$sum: '$lineItems.calculationSnap.b1g1DiscountByCompany',\n\t\t\t\t\t},\n\t\t\t\t\ttotalB1G1Shop: {\n\t\t\t\t\t\t$sum: '$lineItems.calculationSnap.b1g1DiscountByShop',\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\tif (!result) return 0;\n\n\t\treturn (\n\t\t\tresult.totalCompanyDiscount + result.totalShopDiscount + result.totalB1G1Company + result.totalB1G1Shop\n\t\t);\n\t}\n\n\tprivate async calculateFreeDeliverySpent(marketingId: mongoose.Types.ObjectId): Promise<number> {\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t$and: [{ marketings: { $exists: true } }, { marketings: { $ne: null } }],\n\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\tmarketings: marketingId,\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: 'marketings',\n\t\t\t\t\tlocalField: 'marketings',\n\t\t\t\t\tforeignField: '_id',\n\t\t\t\t\tas: 'marketing',\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ $unwind: '$marketing' },\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t'marketing._id': marketingId,\n\t\t\t\t\t'marketing.marketingType': MarketingType.FREE_DELIVERY,\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\ttotalFreeDeliveryCompany: {\n\t\t\t\t\t\t$sum: '$adjustedFinance.freeDelivery.companyCut',\n\t\t\t\t\t},\n\t\t\t\t\ttotalFreeDeliveryShop: {\n\t\t\t\t\t\t$sum: '$adjustedFinance.freeDelivery.shopCut',\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\tif (!result) return 0;\n\n\t\treturn result.totalFreeDeliveryCompany + result.totalFreeDeliveryShop;\n\t}\n\n\tprivate async calculatePunchMarketingSpent(marketingId: mongoose.Types.ObjectId): Promise<number> {\n\t\tconst pipeline: mongoose.PipelineStage[] = [\n\t\t\t{\n\t\t\t\t$match: {\n\t\t\t\t\t$and: [{ marketings: { $exists: true } }, { marketings: { $ne: null } }],\n\t\t\t\t\tstatus: { $ne: RegularOrderStatus.CANCELLED },\n\t\t\t\t\tmarketings: marketingId,\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\ttotalPunchDiscount: {\n\t\t\t\t\t\t$sum: {\n\t\t\t\t\t\t\t$ifNull: ['$adjustedFinance.pricing.punchMarketingDiscount', 0],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\n\t\tconst [result] = await this.orderModel.aggregate(pipeline);\n\n\t\treturn result?.totalPunchDiscount ?? 0;\n\t}\n\n\tpublic async incrementMarketingSpentFromOrder(orderId: mongoose.Types.ObjectId): Promise<any> {\n\t\tconst order = (await this.orderModel\n\t\t\t.findById(orderId)\n\t\t\t.populate('lineItems')) as DocumentType<RegularOrder> & { lineItems: DocumentType<LineItem>[] };\n\n\t\tif (!order || !order.marketings?.length) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst marketingSpendMap = this.calculateMarketingSpendPerOrder(order);\n\n\t\tconst bulkOps = [...marketingSpendMap.entries()].map(([marketingId, amountSpent]) => ({\n\t\t\tupdateOne: {\n\t\t\t\tfilter: { _id: marketingId },\n\t\t\t\tupdate: { $inc: { amountSpent } },\n\t\t\t},\n\t\t}));\n\n\t\tif (bulkOps.length) {\n\t\t\tawait this.model.bulkWrite(bulkOps);\n\t\t}\n\n\t\tawait this.expireMarketingsExceedingSpendLimits(Array.from(marketingSpendMap.keys()));\n\n\t\treturn 'Marketing amount spent incremented successfully';\n\t}\n\n\tpublic async decrementMarketingSpentFromOrder(orderId: mongoose.Types.ObjectId): Promise<any> {\n\t\tconst order = (await this.orderModel\n\t\t\t.findById(orderId)\n\t\t\t.populate('lineItems')) as DocumentType<RegularOrder> & { lineItems: DocumentType<LineItem>[] };\n\n\t\tif (!order || !order.marketings?.length) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst marketingSpendMap = this.calculateMarketingSpendPerOrder(order);\n\n\t\tconst bulkOps = [...marketingSpendMap.entries()].map(([marketingId, amountSpent]) => ({\n\t\t\tupdateOne: {\n\t\t\t\tfilter: { _id: marketingId },\n\t\t\t\tupdate: { $inc: { amountSpent: -amountSpent } },\n\t\t\t},\n\t\t}));\n\n\t\tif (bulkOps.length) {\n\t\t\tawait this.model.bulkWrite(bulkOps);\n\t\t}\n\n\t\tawait this.unExpireMarketingsBelowSpendLimits(Array.from(marketingSpendMap.keys()));\n\n\t\treturn 'Marketing amount spent decremented successfully';\n\t}\n\n\tprivate async expireMarketingsExceedingSpendLimits(marketingIds: mongoose.Types.ObjectId[]) {\n\t\tawait this.model.updateMany(\n\t\t\t{\n\t\t\t\t_id: { $in: marketingIds },\n\t\t\t\tisSpendLimitEnabled: true,\n\t\t\t\tstatus: { $ne: MarketingStatus.EXPIRED },\n\t\t\t\t$expr: { $gte: ['$amountSpent', '$spendLimit'] },\n\t\t\t},\n\t\t\t{ $set: { status: MarketingStatus.EXPIRED } }\n\t\t);\n\t}\n\n\tprivate async unExpireMarketingsBelowSpendLimits(marketingIds: mongoose.Types.ObjectId[]) {\n\t\tawait this.model.updateMany(\n\t\t\t{\n\t\t\t\t_id: { $in: marketingIds },\n\t\t\t\tisSpendLimitEnabled: true,\n\t\t\t\tstatus: MarketingStatus.EXPIRED,\n\t\t\t\t$expr: { $lt: ['$amountSpent', '$spendLimit'] },\n\t\t\t},\n\t\t\t{ $set: { status: MarketingStatus.ACTIVE } }\n\t\t);\n\t}\n\n\tprivate calculateMarketingSpendPerOrder(\n\t\torder: DocumentType<RegularOrder> & { lineItems: DocumentType<LineItem>[] }\n\t): Map<mongoose.Types.ObjectId, number> {\n\t\tconst spendMap = new Map<mongoose.Types.ObjectId, number>();\n\n\t\tconst addSpend = (marketingId: mongoose.Types.ObjectId, amount: number) => {\n\t\t\tif (!amount || amount <= 0) return;\n\t\t\tspendMap.set(marketingId, (spendMap.get(marketingId) ?? 0) + amount);\n\t\t};\n\n\t\t/**\n\t\t * ITEM-BASED (DISCOUNT / B1G1)\n\t\t */\n\t\tfor (const lineItem of order.lineItems ?? []) {\n\t\t\tfor (const marketingId of lineItem.marketings ?? []) {\n\t\t\t\tconst snap = lineItem.calculationSnap ?? {};\n\t\t\t\taddSpend(\n\t\t\t\t\tmarketingId._id,\n\t\t\t\t\t(Number(snap.itemDiscountByCompany) || 0) +\n\t\t\t\t\t\t(Number(snap.itemDiscountByShop) || 0) +\n\t\t\t\t\t\t(Number(snap.b1g1DiscountByCompany) || 0) +\n\t\t\t\t\t\t(Number(snap.b1g1DiscountByShop) || 0)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * FREE DELIVERY\n\t\t */\n\t\tif (order.adjustedFinance?.freeDelivery) {\n\t\t\tfor (const marketingId of order.marketings ?? []) {\n\t\t\t\taddSpend(\n\t\t\t\t\tmarketingId._id,\n\t\t\t\t\t(order.adjustedFinance.freeDelivery.companyCut ?? 0) +\n\t\t\t\t\t\t(order.adjustedFinance.freeDelivery.shopCut ?? 0)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * PUNCH MARKETING\n\t\t */\n\t\tif (order.adjustedFinance?.pricing?.punchMarketingDiscount) {\n\t\t\tfor (const marketingId of order.marketings ?? []) {\n\t\t\t\taddSpend(marketingId._id, order.adjustedFinance.pricing.punchMarketingDiscount);\n\t\t\t}\n\t\t}\n\n\t\treturn spendMap;\n\t}\n}\n\nexport const marketingService = Container.get(MarketingService);\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"punch-marketing-history.service.d.ts","sourceRoot":"/","sources":["modules/punch-marketing-history/services/punch-marketing-history.service.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAmB,MAAM,sBAAsB,CAAC;AAC/E,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAElG,OAAO,EAAE,SAAS,EAAE,MAAM,gCAAgC,CAAC;AAC3D,OAAO,EAEN,qBAAqB,IAAI,KAAK,EAK9B,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACN,8BAA8B,IAAI,SAAS,EAC3C,mBAAmB,EACnB,8BAA8B,IAAI,SAAS,EAC3C,MAAM,8CAA8C,CAAC;AAWtD,OAAO,EAAE,yBAAyB,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAK3F,qBACa,4BAA4B;IACxC,OAAO,CAAC,KAAK,CAA6D;IAC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
+ {"version":3,"file":"punch-marketing-history.service.d.ts","sourceRoot":"/","sources":["modules/punch-marketing-history/services/punch-marketing-history.service.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAmB,MAAM,sBAAsB,CAAC;AAC/E,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAElG,OAAO,EAAE,SAAS,EAAE,MAAM,gCAAgC,CAAC;AAC3D,OAAO,EAEN,qBAAqB,IAAI,KAAK,EAK9B,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACN,8BAA8B,IAAI,SAAS,EAC3C,mBAAmB,EACnB,8BAA8B,IAAI,SAAS,EAC3C,MAAM,8CAA8C,CAAC;AAWtD,OAAO,EAAE,yBAAyB,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAK3F,qBACa,4BAA4B;IACxC,OAAO,CAAC,KAAK,CAA6D;IAC1E,OAAO,CAAC,cAAc,CAA+D;IACrF,OAAO,CAAC,UAAU,CAA2D;;IAYhE,MAAM,CAAC,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IAQrD,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,QAAQ,CAAC,KAAK,CAAC,QAAQ,GAAG,OAAO,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IAkB5E,IAAI,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,OAAO,CAAC,iBAAiB,CAAC,YAAY,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAyB3F,gBAAgB,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,GAAG,CAAC;IAuCzD,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IA2BjE,UAAU,CAAC,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC;IAmB5C,oBAAoB,CAChC,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC,QAAQ,EAC/B,OAAO,EAAE,QAAQ,CAAC,KAAK,CAAC,QAAQ,GAC9B,OAAO,CAAC,MAAM,CAAC;YAqDJ,gBAAgB;IA+CjB,yBAAyB,CAAC,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAC,KAAK,CAAC,QAAQ;IAoC3F,gBAAgB,CAAC,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,yBAAyB,CAAC;IAiD7E,cAAc,CAAC,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC;CA4CvG;AAED,eAAO,MAAM,4BAA4B,8BAA8C,CAAC"}
@@ -258,6 +258,11 @@ let PunchMarketingHistoryService = class PunchMarketingHistoryService {
258
258
  });
259
259
  if (!punchHistory)
260
260
  (0, error_common_1.notFoundError)('No valid punch coupon available');
261
+ await this.orderModel.findByIdAndUpdate(orderId, {
262
+ $push: {
263
+ marketings: punchHistory.marketing,
264
+ },
265
+ });
261
266
  }
262
267
  async getPunchDiscount(data) {
263
268
  const punchHistory = await this.model.findOne({
@@ -1 +1 @@
1
- {"version":3,"file":"punch-marketing-history.service.js","sourceRoot":"/","sources":["modules/punch-marketing-history/services/punch-marketing-history.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,4EAA0E;AAC1E,iDAA4C;AAC5C,yCAAyC;AAGzC,wEAA6G;AAE7G,sEAOmD;AAOnD,4DAM2C;AAC3C,8DAA2D;AAG3D,oEAA2E;AAC3E,gEAAgG;AAChG,wCAA6C;AAGtC,IAAM,4BAA4B,GAAlC,MAAM,4BAA4B;IAChC,KAAK,CAA6D;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KAAK,EAAE,CAAC,IAAI,CAAC;YACb,UAAU,EAAE,IAAI;YAChB,eAAe,EAAE,CAAC;YAClB,aAAa,EAAE,IAAI;YACnB,cAAc,EAAE,KAAK;YACrB,MAAM,EAAE,aAAM,CAAC,MAAM;YACrB,gBAAgB,EAAE,IAAI;YACtB,SAAS,EAAE,YAAY,CAAC,WAAW;YACnC,SAAS,EAAE,YAAY,CAAC,WAAW;YACnC,sBAAsB,EACrB,YAAY,CAAC,eAAe,KAAK,gBAAS,CAAC,KAAK;gBAC/C,CAAC,CAAC,IAAA,+BAAsB,EAAC,YAAY,CAAC,WAAW,GAAG,YAAY,CAAC;gBACjE,CAAC,CAAC,IAAI;YACR,iCAAiC,EAAE,IAAI;YACvC,8BAA8B,EAAE,IAAI;SACpC,CAAC;QACF,OAAO,WAAW,CAAC;IACpB,CAAC;CACD,CAAA;AAzXY,oEAA4B;uCAA5B,4BAA4B;IADxC,IAAA,gBAAO,GAAE;;GACG,4BAA4B,CAyXxC;AAEY,QAAA,4BAA4B,GAAG,gBAAS,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC","sourcesContent":["import { notFoundError } from '@lyxa.ai/core/dist/utilities/error-common';\nimport Container, { Service } from 'typedi';\nimport { TRPCError } from '@trpc/server';\nimport { DocumentType, mongoose, ReturnModelType } from '@typegoose/typegoose';\nimport { FilterDTO, PaginatedResponse, DeleteDTO } from '@lyxa.ai/core/dist/utilities/validation';\nimport { createRawDocumentPaginatorObject, PaginatorOptions } from '@lyxa.ai/core/dist/utilities/pagination';\nimport { ModelType } from '@typegoose/typegoose/lib/types';\nimport {\n\tPunchMarketingHistoryModel,\n\tPunchMarketingHistory as Model,\n\tPunchMarketingModel,\n\tPunchMarketing,\n\tRegularOrder,\n\tRegularOrderModel,\n} from '@lyxa.ai/core/dist/libraries/mongo/models';\nimport {\n\tCreatePunchMarketingHistoryDTO as CreateDTO,\n\tGetByUserAndShopDTO,\n\tUpdatePunchMarketingHistoryDTO as UpdateDTO,\n} from '@modules/punch-marketing-history/validations';\nimport { SoftDeleteModel } from '@lyxa.ai/core/dist/libraries/mongo/plugins/soft-delete-plugin';\nimport {\n\tCouponType,\n\tMarketingType,\n\tPunchMarketingStatus,\n\tStatus,\n\tValueType,\n} from '@lyxa.ai/core/dist/utilities/enum';\nimport { dayjs } from '@lyxa.ai/core/dist/utilities/dayjs';\nimport { PunchMarketingSchema, PunchMarketingValidationSchema } from '@modules/marketing/validations';\nimport { CouponValidationOutputDTO, ValidateCouponDTO } from '@modules/coupon/validations';\nimport { convertToSecondary } from '@lyxa.ai/core/dist/utilities/currency';\nimport { roundBaseCurrency, roundSecondaryCurrency } from '@lyxa.ai/core/dist/utilities/shared';\nimport { getLibraries } from '@lyxa.ai/core';\n\n@Service()\nexport class PunchMarketingHistoryService {\n\tprivate model: typeof PunchMarketingHistoryModel & SoftDeleteModel<Model>;\n\tprivate marketingModel: typeof PunchMarketingModel & SoftDeleteModel<PunchMarketing>;\n\tprivate orderModel: typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\n\n\tconstructor() {\n\t\tthis.model = PunchMarketingHistoryModel as typeof PunchMarketingHistoryModel & SoftDeleteModel<Model>;\n\t\tthis.marketingModel = PunchMarketingModel as typeof PunchMarketingModel & SoftDeleteModel<PunchMarketing>;\n\t\tthis.orderModel = RegularOrderModel as typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\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: CreateDTO): Promise<DocumentType<Model>> {\n\t\treturn await this.model.create(data);\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.findOne({\n\t\t\t_id: id,\n\t\t\tdeletedAt: null,\n\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 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,\n\t\t\t\tselect: data?.select,\n\t\t\t\tpopulate: data?.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 * Get Record\n\t * @param UserId ShopId to find records\n\t */\n\tpublic async getByUserAndShop(data: GetByUserAndShopDTO): Promise<any> {\n\t\tlet result = await this.model.findOne({\n\t\t\tuser: data.userId,\n\t\t\tshop: data.shopId,\n\t\t\texpiryDate: { $gt: new Date() },\n\t\t\tcompletedAt: null,\n\t\t\tstatus: PunchMarketingStatus.ACTIVE,\n\t\t});\n\n\t\tif (result) return result;\n\n\t\tconst marketing = await this.marketingModel.findOne({\n\t\t\tmarketingType: MarketingType.PUNCH_MARKETING,\n\t\t\tshop: data.shopId,\n\t\t\tstatus: Status.ACTIVE,\n\t\t\t'duration.start': { $lt: new Date() },\n\t\t\t'duration.end': { $gt: new Date() },\n\t\t});\n\n\t\tif (!marketing) notFoundError('No Punch Marketing is Active For This Shop...');\n\n\t\treturn {\n\t\t\tuser: data.userId,\n\t\t\tshop: data.shopId,\n\t\t\tmarketing: marketing!._id,\n\t\t\ttargetOrder: marketing.targetOrders,\n\t\t\tminimumOrderValue: marketing.minimumOrderValue,\n\t\t\tcompletedOrder: 0,\n\t\t\tcouponValueType: marketing.couponValueType,\n\t\t\tcouponValue: marketing.couponValue,\n\t\t\tcouponDurationInDays: marketing.couponDurationInDays,\n\t\t};\n\t}\n\n\t/**\n\t * Update record\n\t * @param id ID of the record\n\t * @param data Data to update\n\t */\n\tpublic async update(id: string, data: UpdateDTO): Promise<DocumentType<Model>> {\n\t\tconst record = await this.model.findOneAndUpdate(\n\t\t\t{\n\t\t\t\t_id: id,\n\t\t\t\tdeletedAt: null,\n\t\t\t},\n\t\t\tdata,\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 (!record) {\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\treturn record;\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 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\treturn 'Record deleted successfully';\n\t}\n\n\t/**\n\t * Increment punch history for user\n\t * @param userId User ID\n\t * @param orderId Order ID\n\t */\n\tpublic async incrementUserHistory(\n\t\tuserId: mongoose.Types.ObjectId,\n\t\torderId: mongoose.Types.ObjectId\n\t): Promise<string> {\n\t\tconsole.log('here we go');\n\t\tconst order = await this.orderModel.findById(orderId);\n\n\t\tif (!order || order.user.toString != userId.toString) {\n\t\t\tnotFoundError('Order not found');\n\t\t}\n\n\t\tconst existingHistory = await this.model.findOne({\n\t\t\tuser: userId,\n\t\t\tshop: order.shop,\n\t\t\texpiryDate: { $gt: new Date() },\n\t\t\tcompletedAt: null,\n\t\t\tstatus: PunchMarketingStatus.ACTIVE,\n\t\t});\n\n\t\tif (existingHistory) {\n\t\t\tif (order.finance.pricing.subtotal ?? 0 >= existingHistory.minimumOrderValue) {\n\t\t\t\tconst completedAt =\n\t\t\t\t\texistingHistory.targetOrder == existingHistory.completedOrder + 1 ? new Date() : null;\n\t\t\t\tconst couponExpiryDate = completedAt\n\t\t\t\t\t? dayjs(completedAt).add(existingHistory.couponDurationInDays, 'day').toDate()\n\t\t\t\t\t: null;\n\t\t\t\tconst status = completedAt ? PunchMarketingStatus.COMPLETED : PunchMarketingStatus.ACTIVE;\n\n\t\t\t\tawait this.model.findByIdAndUpdate(\n\t\t\t\t\texistingHistory._id,\n\t\t\t\t\t{\n\t\t\t\t\t\t$inc: {\n\t\t\t\t\t\t\tcompletedOrder: 1,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcompletedAt,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\tcouponExpiryDate,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tnew: true,\n\t\t\t\t\t\trunValidators: true,\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tawait this.createNewHistory(userId, order);\n\t\t}\n\n\t\treturn 'Record updated successfully';\n\t}\n\n\t/**\n\t * Create new history with current punch marketing of the shop\n\t * @param userId User ID\n\t * @param order Order document\n\t */\n\tprivate async createNewHistory(userId: mongoose.Types.ObjectId, order: DocumentType<RegularOrder>) {\n\t\tconst marketing = await this.marketingModel.findOne({\n\t\t\tmarketingType: MarketingType.PUNCH_MARKETING,\n\t\t\tshop: order.shop,\n\t\t\tstatus: Status.ACTIVE,\n\t\t\t'duration.start': { $lt: new Date() },\n\t\t\t'duration.end': { $gt: new Date() },\n\t\t});\n\n\t\tif (!marketing) notFoundError('Marketing Not Found');\n\n\t\tconst expiryDate = dayjs().add(marketing.dayLimit, 'day').toDate();\n\t\tconst couponDurationInDays = marketing!.couponDurationInDays;\n\t\tconst couponValue = marketing!.couponValue;\n\t\tconst couponValueType = marketing!.couponValueType;\n\t\tconst targetOrder = marketing!.targetOrders;\n\t\tconst minimumOrderValue = marketing!.minimumOrderValue;\n\t\tconst completedOrder = 1;\n\t\tconst status =\n\t\t\tmarketing!.targetOrders == completedOrder\n\t\t\t\t? PunchMarketingStatus.COMPLETED\n\t\t\t\t: PunchMarketingStatus.ACTIVE;\n\t\tconst completedAt = marketing!.targetOrders == completedOrder ? new Date() : null;\n\t\tconst couponExpiryDate = completedAt\n\t\t\t? dayjs(completedAt).add(marketing!.couponDurationInDays, 'day').toDate()\n\t\t\t: null;\n\n\t\tif (order.finance.pricing.subtotal ?? 0 >= marketing.minimumOrderValue) {\n\t\t\tconst data: CreateDTO = {\n\t\t\t\tuser: userId as mongoose.Types.ObjectId,\n\t\t\t\tshop: order!.shop as mongoose.Types.ObjectId,\n\t\t\t\tmarketing: marketing!._id as mongoose.Types.ObjectId,\n\t\t\t\ttargetOrder,\n\t\t\t\tminimumOrderValue,\n\t\t\t\tcompletedOrder,\n\t\t\t\tstatus,\n\t\t\t\tcouponValueType,\n\t\t\t\tcouponValue,\n\t\t\t\tcouponDurationInDays,\n\t\t\t\texpiryDate,\n\t\t\t\t...(completedAt && { completedAt }),\n\t\t\t\t...(couponExpiryDate && { couponExpiryDate }),\n\t\t\t};\n\t\t\tawait this.create(data);\n\t\t}\n\t}\n\n\tpublic async applyPunchDiscountToOrder(userId: mongoose.Types.ObjectId, orderId: mongoose.Types.ObjectId) {\n\t\tconst order = await this.orderModel.findById(orderId);\n\t\tif (!order) notFoundError('Order not found');\n\n\t\tconst punchHistory = await this.model.findOneAndUpdate(\n\t\t\t{\n\t\t\t\tuser: userId,\n\t\t\t\tshop: order.shop,\n\t\t\t\tcouponExpiryDate: { $gte: new Date() },\n\t\t\t\tstatus: PunchMarketingStatus.COMPLETED,\n\t\t\t},\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\torder: orderId,\n\t\t\t\t\tstatus: PunchMarketingStatus.COUPON_USED,\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 (!punchHistory) notFoundError('No valid punch coupon available');\n\t}\n\n\t/**\n\t * Get punch discount\n\t * @param data Data to use for validating discount\n\t */\n\tpublic async getPunchDiscount(data: ValidateCouponDTO): Promise<CouponValidationOutputDTO> {\n\t\tconst punchHistory = await this.model.findOne({\n\t\t\tuser: data.user,\n\t\t\tshop: data.shop,\n\t\t\tcouponExpiryDate: { $gte: new Date() },\n\t\t\tstatus: PunchMarketingStatus.COMPLETED,\n\t\t});\n\n\t\tif (!punchHistory) {\n\t\t\treturn {\n\t\t\t\tisValid: false,\n\t\t\t};\n\t\t}\n\n\t\tlet discountAmount =\n\t\t\tpunchHistory.couponValueType == ValueType.FIXED\n\t\t\t\t? punchHistory.couponValue\n\t\t\t\t: roundBaseCurrency((punchHistory.couponValue / 100) * data.amountBeforeCoupon);\n\n\t\tlet secondaryDiscountAmount =\n\t\t\tpunchHistory.couponValueType == ValueType.FIXED\n\t\t\t\t? await convertToSecondary(punchHistory.couponValue)\n\t\t\t\t: roundSecondaryCurrency((punchHistory.couponValue / 100) * data.secondaryAmountBeforeCoupon);\n\n\t\tif (discountAmount > data.amountBeforeCoupon) {\n\t\t\tdiscountAmount = data.amountBeforeCoupon;\n\t\t}\n\t\tif (secondaryDiscountAmount > data.secondaryAmountBeforeCoupon) {\n\t\t\tsecondaryDiscountAmount = data.secondaryAmountBeforeCoupon;\n\t\t}\n\n\t\treturn {\n\t\t\tisValid: true,\n\t\t\tdiscountAmount,\n\t\t\tsecondaryDiscountAmount,\n\t\t\tamountAfterCoupon: Math.max(0, roundBaseCurrency(data.amountBeforeCoupon - discountAmount)),\n\t\t\tsecondaryAmountAfterCoupon: Math.max(\n\t\t\t\t0,\n\t\t\t\troundSecondaryCurrency(data.secondaryAmountBeforeCoupon - secondaryDiscountAmount)\n\t\t\t),\n\t\t\tdiscountCut: {\n\t\t\t\tcompanyCut: 0,\n\t\t\t\tsecondaryCompanyCut: 0,\n\t\t\t\tshopCut: discountAmount,\n\t\t\t\tsecondaryShopCut: secondaryDiscountAmount,\n\t\t\t},\n\t\t};\n\t}\n\n\tpublic async getPunchCoupon(user: mongoose.Types.ObjectId, shop: mongoose.Types.ObjectId): Promise<any> {\n\t\tconst punchHistory = await this.model.findOne({\n\t\t\tuser: user,\n\t\t\tshop: shop,\n\t\t\tcouponExpiryDate: { $gte: new Date() },\n\t\t\tstatus: PunchMarketingStatus.COMPLETED,\n\t\t});\n\t\tif (!punchHistory) return null;\n\n\t\tconst settings = await getLibraries().getCachedSettingsService().getSettings();\n\t\tconst exchangeRate = settings?.currencySetting?.exchangeRate ?? 0;\n\n\t\tconst punchCoupon = {\n\t\t\t_id: null,\n\t\t\tcode: 'punch',\n\t\t\tcouponType: CouponType.INDIVIDUAL_USER,\n\t\t\torderLimitPerUser: 1,\n\t\t\tcreatedBy: null,\n\t\t\tdeletedAt: null,\n\t\t\tvalueType: punchHistory.couponValueType,\n\t\t\tvalue: punchHistory.couponValue,\n\t\t\tmaxDiscountLimit: null,\n\t\t\tduration: {\n\t\t\t\tstart: punchHistory.completedAt,\n\t\t\t\tend: punchHistory.couponExpiryDate,\n\t\t\t},\n\t\t\tshops: [shop],\n\t\t\tspendLimit: null,\n\t\t\ttotalOrderLimit: 1,\n\t\t\tminOrderValue: null,\n\t\t\tforNewUserOnly: false,\n\t\t\tstatus: Status.ACTIVE,\n\t\t\texpirationReason: null,\n\t\t\tcreatedAt: punchHistory.completedAt,\n\t\t\tupdatedAt: punchHistory.completedAt,\n\t\t\tsecondaryCurrencyValue:\n\t\t\t\tpunchHistory.couponValueType === ValueType.FIXED\n\t\t\t\t\t? roundSecondaryCurrency(punchHistory.couponValue * exchangeRate)\n\t\t\t\t\t: null,\n\t\t\tsecondaryCurrencyMaxDiscountLimit: null,\n\t\t\tsecondaryCurrencyMinOrderValue: null,\n\t\t};\n\t\treturn punchCoupon;\n\t}\n}\n\nexport const punchMarketingHistoryService = Container.get(PunchMarketingHistoryService);\n"]}
1
+ {"version":3,"file":"punch-marketing-history.service.js","sourceRoot":"/","sources":["modules/punch-marketing-history/services/punch-marketing-history.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,4EAA0E;AAC1E,iDAA4C;AAC5C,yCAAyC;AAGzC,wEAA6G;AAE7G,sEAOmD;AAOnD,4DAM2C;AAC3C,8DAA2D;AAG3D,oEAA2E;AAC3E,gEAAgG;AAChG,wCAA6C;AAGtC,IAAM,4BAA4B,GAAlC,MAAM,4BAA4B;IAChC,KAAK,CAA6D;IAClE,cAAc,CAA+D;IAC7E,UAAU,CAA2D;IAE7E;QACC,IAAI,CAAC,KAAK,GAAG,mCAAwF,CAAC;QACtG,IAAI,CAAC,cAAc,GAAG,4BAAmF,CAAC;QAC1G,IAAI,CAAC,UAAU,GAAG,0BAA6E,CAAC;IACjG,CAAC;IAMM,KAAK,CAAC,MAAM,CAAC,IAAe;QAClC,OAAO,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACtC,CAAC;IAMM,KAAK,CAAC,QAAQ,CAAC,EAAoC;QACzD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC;YACvC,GAAG,EAAE,EAAE;YACP,SAAS,EAAE,IAAI;SACf,CAAC,CAAC;QACH,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,IAAI,kBAAS,CAAC;gBACnB,IAAI,EAAE,WAAW;gBACjB,OAAO,EAAE,kBAAkB;aAC3B,CAAC,CAAC;QACJ,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;IAMM,KAAK,CAAC,IAAI,CAAC,IAAyB;QAC1C,IAAI,CAAC;YACJ,MAAM,QAAQ,GAAG,IAAA,6CAAgC,EAAC,IAAI,CAAC,KAA2C,CAAC,CAAC;YACpG,MAAM,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BAA4B,CAAC,CAAC","sourcesContent":["import { notFoundError } from '@lyxa.ai/core/dist/utilities/error-common';\nimport Container, { Service } from 'typedi';\nimport { TRPCError } from '@trpc/server';\nimport { DocumentType, mongoose, ReturnModelType } from '@typegoose/typegoose';\nimport { FilterDTO, PaginatedResponse, DeleteDTO } from '@lyxa.ai/core/dist/utilities/validation';\nimport { createRawDocumentPaginatorObject, PaginatorOptions } from '@lyxa.ai/core/dist/utilities/pagination';\nimport { ModelType } from '@typegoose/typegoose/lib/types';\nimport {\n\tPunchMarketingHistoryModel,\n\tPunchMarketingHistory as Model,\n\tPunchMarketingModel,\n\tPunchMarketing,\n\tRegularOrder,\n\tRegularOrderModel,\n} from '@lyxa.ai/core/dist/libraries/mongo/models';\nimport {\n\tCreatePunchMarketingHistoryDTO as CreateDTO,\n\tGetByUserAndShopDTO,\n\tUpdatePunchMarketingHistoryDTO as UpdateDTO,\n} from '@modules/punch-marketing-history/validations';\nimport { SoftDeleteModel } from '@lyxa.ai/core/dist/libraries/mongo/plugins/soft-delete-plugin';\nimport {\n\tCouponType,\n\tMarketingType,\n\tPunchMarketingStatus,\n\tStatus,\n\tValueType,\n} from '@lyxa.ai/core/dist/utilities/enum';\nimport { dayjs } from '@lyxa.ai/core/dist/utilities/dayjs';\nimport { PunchMarketingSchema, PunchMarketingValidationSchema } from '@modules/marketing/validations';\nimport { CouponValidationOutputDTO, ValidateCouponDTO } from '@modules/coupon/validations';\nimport { convertToSecondary } from '@lyxa.ai/core/dist/utilities/currency';\nimport { roundBaseCurrency, roundSecondaryCurrency } from '@lyxa.ai/core/dist/utilities/shared';\nimport { getLibraries } from '@lyxa.ai/core';\n\n@Service()\nexport class PunchMarketingHistoryService {\n\tprivate model: typeof PunchMarketingHistoryModel & SoftDeleteModel<Model>;\n\tprivate marketingModel: typeof PunchMarketingModel & SoftDeleteModel<PunchMarketing>;\n\tprivate orderModel: typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\n\n\tconstructor() {\n\t\tthis.model = PunchMarketingHistoryModel as typeof PunchMarketingHistoryModel & SoftDeleteModel<Model>;\n\t\tthis.marketingModel = PunchMarketingModel as typeof PunchMarketingModel & SoftDeleteModel<PunchMarketing>;\n\t\tthis.orderModel = RegularOrderModel as typeof RegularOrderModel & SoftDeleteModel<RegularOrder>;\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: CreateDTO): Promise<DocumentType<Model>> {\n\t\treturn await this.model.create(data);\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.findOne({\n\t\t\t_id: id,\n\t\t\tdeletedAt: null,\n\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 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,\n\t\t\t\tselect: data?.select,\n\t\t\t\tpopulate: data?.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 * Get Record\n\t * @param UserId ShopId to find records\n\t */\n\tpublic async getByUserAndShop(data: GetByUserAndShopDTO): Promise<any> {\n\t\tlet result = await this.model.findOne({\n\t\t\tuser: data.userId,\n\t\t\tshop: data.shopId,\n\t\t\texpiryDate: { $gt: new Date() },\n\t\t\tcompletedAt: null,\n\t\t\tstatus: PunchMarketingStatus.ACTIVE,\n\t\t});\n\n\t\tif (result) return result;\n\n\t\tconst marketing = await this.marketingModel.findOne({\n\t\t\tmarketingType: MarketingType.PUNCH_MARKETING,\n\t\t\tshop: data.shopId,\n\t\t\tstatus: Status.ACTIVE,\n\t\t\t'duration.start': { $lt: new Date() },\n\t\t\t'duration.end': { $gt: new Date() },\n\t\t});\n\n\t\tif (!marketing) notFoundError('No Punch Marketing is Active For This Shop...');\n\n\t\treturn {\n\t\t\tuser: data.userId,\n\t\t\tshop: data.shopId,\n\t\t\tmarketing: marketing!._id,\n\t\t\ttargetOrder: marketing.targetOrders,\n\t\t\tminimumOrderValue: marketing.minimumOrderValue,\n\t\t\tcompletedOrder: 0,\n\t\t\tcouponValueType: marketing.couponValueType,\n\t\t\tcouponValue: marketing.couponValue,\n\t\t\tcouponDurationInDays: marketing.couponDurationInDays,\n\t\t};\n\t}\n\n\t/**\n\t * Update record\n\t * @param id ID of the record\n\t * @param data Data to update\n\t */\n\tpublic async update(id: string, data: UpdateDTO): Promise<DocumentType<Model>> {\n\t\tconst record = await this.model.findOneAndUpdate(\n\t\t\t{\n\t\t\t\t_id: id,\n\t\t\t\tdeletedAt: null,\n\t\t\t},\n\t\t\tdata,\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 (!record) {\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\treturn record;\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 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\treturn 'Record deleted successfully';\n\t}\n\n\t/**\n\t * Increment punch history for user\n\t * @param userId User ID\n\t * @param orderId Order ID\n\t */\n\tpublic async incrementUserHistory(\n\t\tuserId: mongoose.Types.ObjectId,\n\t\torderId: mongoose.Types.ObjectId\n\t): Promise<string> {\n\t\tconsole.log('here we go');\n\t\tconst order = await this.orderModel.findById(orderId);\n\n\t\tif (!order || order.user.toString != userId.toString) {\n\t\t\tnotFoundError('Order not found');\n\t\t}\n\n\t\tconst existingHistory = await this.model.findOne({\n\t\t\tuser: userId,\n\t\t\tshop: order.shop,\n\t\t\texpiryDate: { $gt: new Date() },\n\t\t\tcompletedAt: null,\n\t\t\tstatus: PunchMarketingStatus.ACTIVE,\n\t\t});\n\n\t\tif (existingHistory) {\n\t\t\tif (order.finance.pricing.subtotal ?? 0 >= existingHistory.minimumOrderValue) {\n\t\t\t\tconst completedAt =\n\t\t\t\t\texistingHistory.targetOrder == existingHistory.completedOrder + 1 ? new Date() : null;\n\t\t\t\tconst couponExpiryDate = completedAt\n\t\t\t\t\t? dayjs(completedAt).add(existingHistory.couponDurationInDays, 'day').toDate()\n\t\t\t\t\t: null;\n\t\t\t\tconst status = completedAt ? PunchMarketingStatus.COMPLETED : PunchMarketingStatus.ACTIVE;\n\n\t\t\t\tawait this.model.findByIdAndUpdate(\n\t\t\t\t\texistingHistory._id,\n\t\t\t\t\t{\n\t\t\t\t\t\t$inc: {\n\t\t\t\t\t\t\tcompletedOrder: 1,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcompletedAt,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\tcouponExpiryDate,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tnew: true,\n\t\t\t\t\t\trunValidators: true,\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tawait this.createNewHistory(userId, order);\n\t\t}\n\n\t\treturn 'Record updated successfully';\n\t}\n\n\t/**\n\t * Create new history with current punch marketing of the shop\n\t * @param userId User ID\n\t * @param order Order document\n\t */\n\tprivate async createNewHistory(userId: mongoose.Types.ObjectId, order: DocumentType<RegularOrder>) {\n\t\tconst marketing = await this.marketingModel.findOne({\n\t\t\tmarketingType: MarketingType.PUNCH_MARKETING,\n\t\t\tshop: order.shop,\n\t\t\tstatus: Status.ACTIVE,\n\t\t\t'duration.start': { $lt: new Date() },\n\t\t\t'duration.end': { $gt: new Date() },\n\t\t});\n\n\t\tif (!marketing) notFoundError('Marketing Not Found');\n\n\t\tconst expiryDate = dayjs().add(marketing.dayLimit, 'day').toDate();\n\t\tconst couponDurationInDays = marketing!.couponDurationInDays;\n\t\tconst couponValue = marketing!.couponValue;\n\t\tconst couponValueType = marketing!.couponValueType;\n\t\tconst targetOrder = marketing!.targetOrders;\n\t\tconst minimumOrderValue = marketing!.minimumOrderValue;\n\t\tconst completedOrder = 1;\n\t\tconst status =\n\t\t\tmarketing!.targetOrders == completedOrder\n\t\t\t\t? PunchMarketingStatus.COMPLETED\n\t\t\t\t: PunchMarketingStatus.ACTIVE;\n\t\tconst completedAt = marketing!.targetOrders == completedOrder ? new Date() : null;\n\t\tconst couponExpiryDate = completedAt\n\t\t\t? dayjs(completedAt).add(marketing!.couponDurationInDays, 'day').toDate()\n\t\t\t: null;\n\n\t\tif (order.finance.pricing.subtotal ?? 0 >= marketing.minimumOrderValue) {\n\t\t\tconst data: CreateDTO = {\n\t\t\t\tuser: userId as mongoose.Types.ObjectId,\n\t\t\t\tshop: order!.shop as mongoose.Types.ObjectId,\n\t\t\t\tmarketing: marketing!._id as mongoose.Types.ObjectId,\n\t\t\t\ttargetOrder,\n\t\t\t\tminimumOrderValue,\n\t\t\t\tcompletedOrder,\n\t\t\t\tstatus,\n\t\t\t\tcouponValueType,\n\t\t\t\tcouponValue,\n\t\t\t\tcouponDurationInDays,\n\t\t\t\texpiryDate,\n\t\t\t\t...(completedAt && { completedAt }),\n\t\t\t\t...(couponExpiryDate && { couponExpiryDate }),\n\t\t\t};\n\t\t\tawait this.create(data);\n\t\t}\n\t}\n\n\tpublic async applyPunchDiscountToOrder(userId: mongoose.Types.ObjectId, orderId: mongoose.Types.ObjectId) {\n\t\tconst order = await this.orderModel.findById(orderId);\n\t\tif (!order) notFoundError('Order not found');\n\n\t\tconst punchHistory = await this.model.findOneAndUpdate(\n\t\t\t{\n\t\t\t\tuser: userId,\n\t\t\t\tshop: order.shop,\n\t\t\t\tcouponExpiryDate: { $gte: new Date() },\n\t\t\t\tstatus: PunchMarketingStatus.COMPLETED,\n\t\t\t},\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\torder: orderId,\n\t\t\t\t\tstatus: PunchMarketingStatus.COUPON_USED,\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 (!punchHistory) notFoundError('No valid punch coupon available');\n\n\t\tawait this.orderModel.findByIdAndUpdate(orderId, {\n\t\t\t$push: {\n\t\t\t\tmarketings: punchHistory.marketing,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Get punch discount\n\t * @param data Data to use for validating discount\n\t */\n\tpublic async getPunchDiscount(data: ValidateCouponDTO): Promise<CouponValidationOutputDTO> {\n\t\tconst punchHistory = await this.model.findOne({\n\t\t\tuser: data.user,\n\t\t\tshop: data.shop,\n\t\t\tcouponExpiryDate: { $gte: new Date() },\n\t\t\tstatus: PunchMarketingStatus.COMPLETED,\n\t\t});\n\n\t\tif (!punchHistory) {\n\t\t\treturn {\n\t\t\t\tisValid: false,\n\t\t\t};\n\t\t}\n\n\t\tlet discountAmount =\n\t\t\tpunchHistory.couponValueType == ValueType.FIXED\n\t\t\t\t? punchHistory.couponValue\n\t\t\t\t: roundBaseCurrency((punchHistory.couponValue / 100) * data.amountBeforeCoupon);\n\n\t\tlet secondaryDiscountAmount =\n\t\t\tpunchHistory.couponValueType == ValueType.FIXED\n\t\t\t\t? await convertToSecondary(punchHistory.couponValue)\n\t\t\t\t: roundSecondaryCurrency((punchHistory.couponValue / 100) * data.secondaryAmountBeforeCoupon);\n\n\t\tif (discountAmount > data.amountBeforeCoupon) {\n\t\t\tdiscountAmount = data.amountBeforeCoupon;\n\t\t}\n\t\tif (secondaryDiscountAmount > data.secondaryAmountBeforeCoupon) {\n\t\t\tsecondaryDiscountAmount = data.secondaryAmountBeforeCoupon;\n\t\t}\n\n\t\treturn {\n\t\t\tisValid: true,\n\t\t\tdiscountAmount,\n\t\t\tsecondaryDiscountAmount,\n\t\t\tamountAfterCoupon: Math.max(0, roundBaseCurrency(data.amountBeforeCoupon - discountAmount)),\n\t\t\tsecondaryAmountAfterCoupon: Math.max(\n\t\t\t\t0,\n\t\t\t\troundSecondaryCurrency(data.secondaryAmountBeforeCoupon - secondaryDiscountAmount)\n\t\t\t),\n\t\t\tdiscountCut: {\n\t\t\t\tcompanyCut: 0,\n\t\t\t\tsecondaryCompanyCut: 0,\n\t\t\t\tshopCut: discountAmount,\n\t\t\t\tsecondaryShopCut: secondaryDiscountAmount,\n\t\t\t},\n\t\t};\n\t}\n\n\tpublic async getPunchCoupon(user: mongoose.Types.ObjectId, shop: mongoose.Types.ObjectId): Promise<any> {\n\t\tconst punchHistory = await this.model.findOne({\n\t\t\tuser: user,\n\t\t\tshop: shop,\n\t\t\tcouponExpiryDate: { $gte: new Date() },\n\t\t\tstatus: PunchMarketingStatus.COMPLETED,\n\t\t});\n\t\tif (!punchHistory) return null;\n\n\t\tconst settings = await getLibraries().getCachedSettingsService().getSettings();\n\t\tconst exchangeRate = settings?.currencySetting?.exchangeRate ?? 0;\n\n\t\tconst punchCoupon = {\n\t\t\t_id: null,\n\t\t\tcode: 'punch',\n\t\t\tcouponType: CouponType.INDIVIDUAL_USER,\n\t\t\torderLimitPerUser: 1,\n\t\t\tcreatedBy: null,\n\t\t\tdeletedAt: null,\n\t\t\tvalueType: punchHistory.couponValueType,\n\t\t\tvalue: punchHistory.couponValue,\n\t\t\tmaxDiscountLimit: null,\n\t\t\tduration: {\n\t\t\t\tstart: punchHistory.completedAt,\n\t\t\t\tend: punchHistory.couponExpiryDate,\n\t\t\t},\n\t\t\tshops: [shop],\n\t\t\tspendLimit: null,\n\t\t\ttotalOrderLimit: 1,\n\t\t\tminOrderValue: null,\n\t\t\tforNewUserOnly: false,\n\t\t\tstatus: Status.ACTIVE,\n\t\t\texpirationReason: null,\n\t\t\tcreatedAt: punchHistory.completedAt,\n\t\t\tupdatedAt: punchHistory.completedAt,\n\t\t\tsecondaryCurrencyValue:\n\t\t\t\tpunchHistory.couponValueType === ValueType.FIXED\n\t\t\t\t\t? roundSecondaryCurrency(punchHistory.couponValue * exchangeRate)\n\t\t\t\t\t: null,\n\t\t\tsecondaryCurrencyMaxDiscountLimit: null,\n\t\t\tsecondaryCurrencyMinOrderValue: null,\n\t\t};\n\t\treturn punchCoupon;\n\t}\n}\n\nexport const punchMarketingHistoryService = Container.get(PunchMarketingHistoryService);\n"]}
@@ -689,6 +689,33 @@ declare const marketingMicroServiceRouter: import("@trpc/server").TRPCBuiltRoute
689
689
  };
690
690
  meta: object;
691
691
  }>;
692
+ calculateMarketingSpent: import("@trpc/server").TRPCMutationProcedure<{
693
+ input: string | import("mongoose").Types.ObjectId;
694
+ output: {
695
+ success: boolean;
696
+ message: string;
697
+ data: any;
698
+ };
699
+ meta: object;
700
+ }>;
701
+ incrementMarketingSpentFromOrder: import("@trpc/server").TRPCMutationProcedure<{
702
+ input: string | import("mongoose").Types.ObjectId;
703
+ output: {
704
+ success: boolean;
705
+ message: string;
706
+ data: any;
707
+ };
708
+ meta: object;
709
+ }>;
710
+ decrementMarketingSpentFromOrder: import("@trpc/server").TRPCMutationProcedure<{
711
+ input: string | import("mongoose").Types.ObjectId;
712
+ output: {
713
+ success: boolean;
714
+ message: string;
715
+ data: any;
716
+ };
717
+ meta: object;
718
+ }>;
692
719
  }>>;
693
720
  couponRouter: import("@trpc/server").TRPCBuiltRouter<{
694
721
  ctx: import("@lyxa.ai/core/dist/libraries/trpc/context").LyxaHTTPContext;