import { Expose, Transform } from 'class-transformer' import { isEmpty, isNil } from 'lodash' import { CountryCode, parseISO } from '../utils' import { BaseModel } from './base.model' import { DiscountTypes } from './enums/discount_type.enum' export class DiscountCoupon extends BaseModel { id: string name: string code: string @Expose({ name: 'discount_type' }) discountType: DiscountTypes @Expose({ name: 'discount_amount' }) discountAmount: number @Expose({ name: 'created_by_id' }) createdById: string @Expose({ name: 'updated_by_id' }) updatedById: string @Expose({ name: 'partner_id' }) partnerId: string enabled: boolean @Expose({ name: 'country_codes' }) countryCodes: CountryCode[] @Transform(value => parseISO(value), { toClassOnly: true }) @Expose({ name: 'created_at' }) createdAt: Date @Transform(value => parseISO(value), { toClassOnly: true }) @Expose({ name: 'updated_at' }) updatedAt?: Date @Transform(value => parseISO(value), { toClassOnly: true }) @Expose({ name: 'begins_at' }) beginsAt: Date @Transform(value => parseISO(value), { toClassOnly: true }) @Expose({ name: 'ends_at' }) endsAt?: Date @Expose({ name: 'plan_discount_coupons' }) planDiscountCoupons: any get planIds(): string[] { return (this.planDiscountCoupons || []).map(plan_discount_coupon => plan_discount_coupon.plan_id) } public apply(amount: number): number { return Number( this.discountType === DiscountTypes.PERCENTAGE ? ((1 - this.discountAmount / 100) * amount).toFixed(2) : amount - this.discountAmount, ) } public allows(planId: string): boolean { return isNil(planId) || isEmpty(this.planIds) || this.planIds.includes(planId) } public get isInactive(): boolean { return !this.isActive } public get isActive(): boolean { const now = new Date() const active = this.beginsAt <= now return isNil(this.endsAt) ? active : active && this.endsAt >= now } public isValid({ planId }: { planId?: string }): boolean { return this.enabled && this.isActive && this.allows(planId) } }