From ba5d6978de1054daba3fcc2af61f6f78caad2dbc Mon Sep 17 00:00:00 2001 From: AbleKSaju <126228406+AbleKSaju@users.noreply.github.com> Date: Wed, 18 Sep 2024 10:41:15 +0530 Subject: [PATCH] feat: prevent coupon usage if maximum limit is exceeded --- .../AppliedCouponCodes/AppliedCouponCodes.ts | 8 ++++++++ models/baseModels/Invoice/Invoice.ts | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/models/baseModels/AppliedCouponCodes/AppliedCouponCodes.ts b/models/baseModels/AppliedCouponCodes/AppliedCouponCodes.ts index 318ec9f45..9a4b74901 100644 --- a/models/baseModels/AppliedCouponCodes/AppliedCouponCodes.ts +++ b/models/baseModels/AppliedCouponCodes/AppliedCouponCodes.ts @@ -23,10 +23,18 @@ export class AppliedCouponCodes extends InvoiceItem { 'pricingRule', 'validFrom', 'validTo', + 'maximumUse', + 'used', ], filters: { name: value as string }, }); + if ((coupon[0]?.maximumUse as number) <= (coupon[0]?.used as number)) { + throw new ValidationError( + 'Coupon code has been used maximum number of times' + ); + } + const applicableCouponCodesNames = await getApplicableCouponCodesName( value as string, this.parentdoc as SalesInvoice diff --git a/models/baseModels/Invoice/Invoice.ts b/models/baseModels/Invoice/Invoice.ts index d08d26e0a..f1512ca57 100644 --- a/models/baseModels/Invoice/Invoice.ts +++ b/models/baseModels/Invoice/Invoice.ts @@ -218,6 +218,10 @@ export abstract class Invoice extends Transactional { } await this._updateIsItemsReturned(); + + if (this.schemaName === ModelNameEnum.SalesInvoice) { + this.updateUsedCountOfCoupons(); + } } async afterCancel() { @@ -527,6 +531,17 @@ export abstract class Invoice extends Transactional { return newReturnDoc; } + updateUsedCountOfCoupons() { + this.coupons?.map(async (coupon) => { + const couponDoc = await this.fyo.doc.getDoc( + ModelNameEnum.CouponCode, + coupon.coupons + ); + + await couponDoc.setAndSync({ used: (couponDoc.used as number) + 1 }); + }); + } + async _updateIsItemsReturned() { if (!this.isReturn || !this.returnAgainst || this.isQuote) { return;