From c592865aea96958ef8d86772994225977324a585 Mon Sep 17 00:00:00 2001 From: vyshnav Date: Tue, 17 Sep 2024 19:22:46 +0530 Subject: [PATCH] Refactor: Add getPrice function to calculate final price with discount --- src/app/actions/get-price.ts | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/app/actions/get-price.ts diff --git a/src/app/actions/get-price.ts b/src/app/actions/get-price.ts new file mode 100644 index 0000000..a15c398 --- /dev/null +++ b/src/app/actions/get-price.ts @@ -0,0 +1,36 @@ +"use server"; + +import prisma from "@/server/db"; + +class CouponError extends Error { + constructor(message: string) { + super(message); + this.name = "CouponError"; + } +} + +export const getPrice = async (couponCode?: string): Promise => { + const basePrice = 1000; + if (couponCode) { + const coupon = await prisma.referral.findUnique({ + where: { code: couponCode }, + }); + if (!coupon) { + throw new CouponError("Coupon code not found"); + } + + if (coupon.isUsed) { + throw new CouponError("Coupon code is already used"); + } + const discountPercentage = parseFloat(coupon.discountPercentage ?? "0"); + + if (isNaN(discountPercentage)) { + throw new CouponError("Invalid discount percentage format"); + } + const discountAmount = basePrice * (discountPercentage / 100); + const finalPrice = Math.floor(basePrice - discountAmount); + + return finalPrice; + } + return basePrice; +};