Skip to content

Commit

Permalink
Merge pull request #12 from TEDx-SJEC/discount_price
Browse files Browse the repository at this point in the history
Refactor: Add getPrice function to calculate final price with discount
  • Loading branch information
joywin2003 authored Sep 17, 2024
2 parents e4c9b2f + c592865 commit 1712dca
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/app/actions/get-price.ts
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;
};

0 comments on commit 1712dca

Please sign in to comment.