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

New changes to registrations and CTA #92

Closed
wants to merge 7 commits into from
43 changes: 6 additions & 37 deletions src/app/actions/change-role.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,25 @@
"use server";

import prisma from "@/server/db";
import { getServerSideSession } from "@/lib/get-server-session";
import { revalidatePath } from "next/cache";
import getErrorMessage from "@/utils/getErrorMessage";
import { UserRole,ADMIN_USERS_PATH } from "@/constants";

async function updateUserRole(id: string, role: UserRole) {
const VALID_ROLES = Object.values(UserRole);
if (!VALID_ROLES.includes(role)) {
throw new Error(`Invalid role: ${role}`);
}
const session = await getServerSideSession();
if (!session || session.user.role !== UserRole.ADMIN) {
throw new Error(`Unauthorized Access...`);
}
async function updateUserRole(id: string, role: string) {
try {
const updatedUser = await prisma.user.update({
where: { id },
data: { role },
});
revalidatePath(ADMIN_USERS_PATH);
revalidatePath("/admin/users");
return updatedUser;
} catch (error) {
console.error("Error updating user role:", getErrorMessage(error));
throw new Error("Failed to update user role. Please try again later.");
console.error("Error updating user role:", error);
return null;
}
}

export const makeAdmin = async (userId: string) => {
try {
return await updateUserRole(userId, UserRole.ADMIN);
} catch (error) {
console.error("Failed to make user admin:", getErrorMessage(error));
return null;
}
return await updateUserRole(userId, "ADMIN");
};

export const makeParticipant = async (userId: string) => {
try {
return await updateUserRole(userId, UserRole.PARTICIPANT);
} catch (error) {
console.error("Failed to make user participant:", getErrorMessage(error));
return null;
}
};

export const makeCoordinator = async (userId: string) => {
try {
return await updateUserRole(userId, UserRole.COORDINATOR);
} catch (error) {
console.error("Failed to make user coordinator:", getErrorMessage(error));
return null;
}
return await updateUserRole(userId, "PARTICIPANT");
};
51 changes: 11 additions & 40 deletions src/app/actions/create-coupon-code.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,17 @@
"use server";
import { generateCouponCode } from "@/lib/helper";
import prisma from "@/server/db";
import { couponSchema } from "@/utils/zod-schemas";

export const saveCoupon = async (
coupon: string,
createdById: string,
discount: number = 20,
numberOfCoupons: number = 1
coupon: string,
id: string,
discount: string = "20",
) => {
try {
const validatCoupon = couponSchema.parse({ coupon, createdById, discount });

// Check if the coupon already exists
const couponExists = await prisma.referral.findFirst({
where: { code: validatCoupon.coupon },
});
if (couponExists) {
throw new Error("Coupon code already exists");
}

// Create coupons
const createCoupon = async (code: string) => {
return prisma.referral.create({
data: {
code,
isUsed: false,
createdById: validatCoupon.createdById,
discountPercentage: validatCoupon.discount.toString(),
},
});
};

const couponCodes =
numberOfCoupons === 1
? [validatCoupon.coupon]
: Array.from({ length: numberOfCoupons }, () => generateCouponCode(10));

const responses = await Promise.all(couponCodes.map(createCoupon));
return responses;
} catch (error) {
console.error("Error creating coupon:", error);
throw new Error("Failed to create coupon. Please try again later.");
}
const resp = await prisma.referral.create({
data: {
code: coupon,
isUsed: false,
createdById: id,
discountPercentage: discount,
},
});
};
15 changes: 0 additions & 15 deletions src/app/actions/get-payment-count.ts

This file was deleted.

25 changes: 9 additions & 16 deletions src/app/actions/get-user-by-id.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
import prisma from "@/server/db"; // Adjust the import based on your structure

export async function getUserById(userId: string) {
try {
const user = await prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
role: true,
},
});
if (!user) {
throw new Error(`User with ID ${userId} not found`);
}
return user;
} catch (error) {
console.error("Error getting user by id:", error);
throw new Error("Failed to get user. Please try again later.");
}
const user = await prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
role: true, // Include any other fields you need
},
});

return user;
}
14 changes: 0 additions & 14 deletions src/app/actions/get-user-count.ts

This file was deleted.

12 changes: 3 additions & 9 deletions src/app/actions/is-allowed-to-access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,10 @@
import prisma from "@/server/db";

export const isAllowedToAccess = async (email: string): Promise<boolean> => {
if (!email) return false;
try {
const user = await prisma.sjecUser.findFirst({
where: {
email: email,
},
where: {
email: email,
},
});
return user !== null;
} catch (error) {
console.error("Error getting user by email:", error);
return false;
}
};
43 changes: 16 additions & 27 deletions src/app/actions/submit-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,26 @@
import { getServerSideSession } from "@/lib/get-server-session";
import prisma from "@/server/db";
import { FormDataInterface } from "@/types";
import { z } from "zod";

const amountSchema = z.number().positive("Amount must be a positive number.");

export async function submitForm(data: FormDataInterface, amount: number) {
const session = await getServerSideSession();
if (!session) {
throw new Error("User is not authenticated");
return;
}
const validatedAmount = amountSchema.parse(amount);

const totalAmount = Math.round(validatedAmount + validatedAmount * 0.02);

try {
return await prisma.form.create({
data: {
name: data.name,
usn: data.usn,
email: data.email,
foodPreference: data.foodPreference,
contact: data.phone,
designation: data.designation,
paidAmount: totalAmount,
photo: data.photo,
collegeIdCard: data.idCard,
createdById: session.user.id,
entityName: data.entityName,
},
});
} catch (error) {
console.error("Error creating form:", error);
throw new Error("Failed to submit the form. Please try again later.");
}
return await prisma.form.create({
data: {
name: data.name,
usn: data.usn,
email: data.email,
foodPreference: data.foodPreference,
contact: data.phone,
designation: data.designation,
paidAmount: amount,
photo: data.photo,
collegeIdCard: data.idCard,
createdById: session.user.id,
entityName: data.entityName,
},
});
}
58 changes: 8 additions & 50 deletions src/app/admin/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import { Inter } from "next/font/google";
import "./globals.css";
import Providers from "@/components/layout/Provider";
import { AdminNavbar } from "@/components/admin/Navbar/navbar";
import { signIn, useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import { tailChase } from "ldrs";
import { useSession } from "next-auth/react";

const inter = Inter({ subsets: ["latin"] });

Expand All @@ -16,62 +14,22 @@ export default function RootLayout({
}: Readonly<{
children: React.ReactNode;
}>) {
const { data: session, status } = useSession({
const { data: session } = useSession({
required: true,
onUnauthenticated: async () => {
await signIn("google");
},
});

if (typeof window !== "undefined") {
tailChase.register();
}

const [isLoading, setIsLoading] = useState(true);

useEffect(() => {
if (status === "loading") {
setIsLoading(true);
} else {
setIsLoading(false);
}
}, [status]);

if (isLoading || status !== "authenticated" || !session) {
// Show the loading spinner if session is loading or not authenticated
return (
<div className="flex flex-col items-center justify-center min-h-screen">
<l-tail-chase
size={"88"}
speed={"1.75"}
color={"#FF0000"}
></l-tail-chase>
</div>
);
}

if (!session) {
return (
<div className="w-screen h-screen flex justify-center items-center bg-black text-gray-200">
<div className="text-center">
<h1 className="text-3xl font-bold mb-2 text-red-500">Unauthorized</h1>
<p className="text-gray-400">
You need to log in to access this page.
</p>
</div>
<div className="w-screen h-screen flex justify-center items-center">
Unauthorized
</div>
);
}

if (session.user.role !== "ADMIN" && session.user.role !== "COORDINATOR") {
if (session.user.role !== "ADMIN") {
return (
<div className="w-screen h-screen flex justify-center items-center bg-black text-gray-200">
<div className="text-center">
<h1 className="text-3xl font-bold mb-2 text-red-500">Forbidden</h1>
<p className="text-gray-400">
You do not have the required permissions to view this page.
</p>
</div>
<div className="w-screen h-screen flex justify-center items-center">
Forbidden
</div>
);
}
Expand All @@ -82,7 +40,7 @@ export default function RootLayout({
<Providers>
<div className="flex h-screen overflow-hidden">
<AdminNavbar />
<main className="ml-16 md:ml-0 flex-1 overflow-y-auto bg-gray-800">
<main className="flex-1 overflow-auto bg-indigo-50">
{children}
</main>
</div>
Expand Down
31 changes: 0 additions & 31 deletions src/app/admin/loading.tsx

This file was deleted.

Loading
Loading