Skip to content

Commit

Permalink
feat: prevent coupon usage if maximum limit is exceeded
Browse files Browse the repository at this point in the history
  • Loading branch information
AbleKSaju committed Sep 18, 2024
1 parent b9b9770 commit ba5d697
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
8 changes: 8 additions & 0 deletions models/baseModels/AppliedCouponCodes/AppliedCouponCodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions models/baseModels/Invoice/Invoice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,10 @@ export abstract class Invoice extends Transactional {
}

await this._updateIsItemsReturned();

if (this.schemaName === ModelNameEnum.SalesInvoice) {
this.updateUsedCountOfCoupons();
}
}

async afterCancel() {
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit ba5d697

Please sign in to comment.