2
0
mirror of https://github.com/frappe/books.git synced 2024-11-15 09:54:04 +00:00
books/models/baseModels/AppliedCouponCodes/AppliedCouponCodes.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

101 lines
2.8 KiB
TypeScript
Raw Normal View History

2024-09-11 10:41:16 +00:00
import { DocValue } from 'fyo/core/types';
2024-09-11 10:38:41 +00:00
import { ValidationMap } from 'fyo/model/types';
2024-09-11 10:41:16 +00:00
import { ValidationError } from 'fyo/utils/errors';
import { ModelNameEnum } from 'models/types';
import { Money } from 'pesa';
2024-09-11 10:38:41 +00:00
import { InvoiceItem } from '../InvoiceItem/InvoiceItem';
import { getApplicableCouponCodesName } from 'models/helpers';
import { SalesInvoice } from '../SalesInvoice/SalesInvoice';
2024-09-11 10:38:41 +00:00
export class AppliedCouponCodes extends InvoiceItem {
coupons?: string;
2024-09-11 10:41:16 +00:00
validations: ValidationMap = {
coupons: async (value: DocValue) => {
if (!value) {
return;
}
const coupon = await this.fyo.db.getAll(ModelNameEnum.CouponCode, {
fields: [
'minAmount',
'maxAmount',
'pricingRule',
'validFrom',
'validTo',
'maximumUse',
'used',
2024-09-11 10:41:16 +00:00
],
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
);
if (!applicableCouponCodesNames?.length) {
throw new ValidationError(
this.fyo.t`Coupon ${
value as string
} is not applicable for applied items.`
);
}
2024-09-11 10:41:16 +00:00
const couponExist = this.parentdoc?.coupons?.some(
(coupon) => coupon?.coupons === value
);
if (couponExist) {
throw new ValidationError(
this.fyo.t`${value as string} already applied.`
);
}
if (
(coupon[0].minAmount as Money).gte(
this.parentdoc?.grandTotal as Money
) &&
!(coupon[0].minAmount as Money).isZero()
) {
throw new ValidationError(
this.fyo.t`The Grand Total must exceed ${
(coupon[0].minAmount as Money).float
} to apply the coupon ${value as string}.`
);
}
if (
(coupon[0].maxAmount as Money).lte(
this.parentdoc?.grandTotal as Money
) &&
!(coupon[0].maxAmount as Money).isZero()
) {
throw new ValidationError(
this.fyo.t`The Grand Total must be less than ${
(coupon[0].maxAmount as Money).float
} to apply this coupon.`
);
}
if ((coupon[0].validFrom as Date) > (this.parentdoc?.date as Date)) {
throw new ValidationError(
this.fyo.t`Valid From Date should be less than Valid To Date.`
);
}
if ((coupon[0].validTo as Date) < (this.parentdoc?.date as Date)) {
throw new ValidationError(
this.fyo.t`Valid To Date should be greater than Valid From Date.`
);
}
},
};
2024-09-11 10:38:41 +00:00
}