-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #12 from TEDx-SJEC/discount_price
Refactor: Add getPrice function to calculate final price with discount
- Loading branch information
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<number> => { | ||
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; | ||
}; |