From 11f9b0d46f1b662f58c4a6b7da272d61cc2840ad Mon Sep 17 00:00:00 2001 From: AbleKSaju <126228406+AbleKSaju@users.noreply.github.com> Date: Mon, 26 Aug 2024 11:14:40 +0530 Subject: [PATCH] feat: coupon codes validations and filters --- models/baseModels/CouponCode/CouponCode.ts | 71 +++++++++++++++++++++- 1 file changed, 69 insertions(+), 2 deletions(-) diff --git a/models/baseModels/CouponCode/CouponCode.ts b/models/baseModels/CouponCode/CouponCode.ts index aef79f37..40e00c12 100644 --- a/models/baseModels/CouponCode/CouponCode.ts +++ b/models/baseModels/CouponCode/CouponCode.ts @@ -1,5 +1,13 @@ +import { DocValue } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; -import { FormulaMap, ListViewSettings, ValidationMap } from 'fyo/model/types'; +import { + FiltersMap, + FormulaMap, + ListViewSettings, + ValidationMap, +} from 'fyo/model/types'; +import { ValidationError } from 'fyo/utils/errors'; +import { t } from 'fyo'; import { Money } from 'pesa'; export class CouponCode extends Doc { @@ -22,7 +30,66 @@ export class CouponCode extends Doc { }, }; - validations: ValidationMap = {}; + validations: ValidationMap = { + minAmount: (value: DocValue) => { + if (!value || !this.maxAmount) { + return; + } + + if ((value as Money).isZero() && this.maxAmount.isZero()) { + return; + } + + if ((value as Money).gte(this.maxAmount)) { + throw new ValidationError( + t`Minimum Amount should be less than the Maximum Amount.` + ); + } + }, + maxAmount: (value: DocValue) => { + if (!this.minAmount || !value) { + return; + } + + if (this.minAmount.isZero() && (value as Money).isZero()) { + return; + } + + if ((value as Money).lte(this.minAmount)) { + throw new ValidationError( + t`Maximum Amount should be greater than the Minimum Amount.` + ); + } + }, + validFrom: (value: DocValue) => { + if (!value || !this.validTo) { + return; + } + + if ((value as Date).toISOString() > this.validTo.toISOString()) { + throw new ValidationError( + t`Valid From Date should be less than Valid To Date.` + ); + } + }, + validTo: (value: DocValue) => { + if (!this.validFrom || !value) { + return; + } + + if ((value as Date).toISOString() < this.validFrom.toISOString()) { + throw new ValidationError( + t`Valid To Date should be greater than Valid From Date.` + ); + } + }, + }; + + static filters: FiltersMap = { + pricingRule: () => ({ + isCouponCodeBased: true, + }), + }; static getListViewSettings(): ListViewSettings { return {