Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: Add getPrice function to calculate final price with discount #12

Merged
merged 1 commit into from
Sep 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
};
Loading