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

Update application backend #95

Merged
merged 2 commits into from
Jan 13, 2025
Merged
Show file tree
Hide file tree
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
56 changes: 12 additions & 44 deletions src/app/(site)/apply/_components/application-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import axios from "axios";
import Loading from "@/components/loading";
import SchoolSuggestion from "./school-suggestion";
import { redirect } from "next/navigation";
import { applicationSchema } from "@/schemas/application";

interface ApplicationState {
name: string;
Expand All @@ -24,58 +25,23 @@ interface ApplicationState {
food: string;
agree: boolean;
}

interface FormAction {
type: string;
payload?: any;
}
const schema = yup
.object({
name: yup.string(),
email: yup
.string()
.email("Invalid email format")
//Matches any .edu email
.matches(/^[a-zA-Z0-9._%+-]+@([a-zA-Z0-9-]+\.)+(edu)$/, {
message: "Must be a .edu email",
excludeEmptyString: true
}),
preferredEmail: yup.string().email("Invalid email format").required(),
phone: yup
.string()
.matches(
/^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$/,
"Invalid phone number format"
),
major: yup.string().min(2),
school: yup.string().min(4),
gradYear: yup
.number()
.typeError("Must be number")
.positive()
.integer()
.min(2023, "Invalid grad year")
.max(2030),
response: yup
.string()
.test("wordCount50", "Must be at least 50 words", (value) => {
if (value) {
const wordCount = value.trim().split(/\s+/).length;
return wordCount >= 50;
}
return false;
})
.test("wordCount500", "Must be less than 500 words", (value) => {
if (value) {
const wordCount = value.trim().split(/\s+/).length;
return wordCount <= 500;
}
return false;
}),

// Reuse existing application schema from /schemas
// and include additional fields
const schema = applicationSchema.concat(
yup.object({
over18: yup.bool().oneOf([true], "You must be 18 or older!"),
waiver: yup.bool().oneOf([true], "You must agree to the waiver!")
})
.required();
);

type FormData = yup.InferType<typeof schema>;

const initialState: ApplicationState = {
name: "",
email: "",
Expand All @@ -91,6 +57,7 @@ const initialState: ApplicationState = {
food: "Vegan",
agree: false
};

const reducer = (
state: ApplicationState,
action: FormAction
Expand Down Expand Up @@ -210,6 +177,7 @@ const ApplicationForm: React.FC<ApplicationProps> = (props) => {
redirect("/error");
}
};

return (
<>
<form className="md:w-full" onSubmit={handleSubmit(onSubmit)}>
Expand Down
2 changes: 1 addition & 1 deletion src/app/(site)/apply/_components/apply-auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const ApplyAuth: React.FC<ApplyAuthProps> = ({ children }) => {
new Date(now) >= new Date(openDate) &&
new Date(now) <= new Date(applicationCloseDate);

if (applicationOpen) {
if (applicationOpen || process.env.NODE_ENV !== "production") {
return <>{children}</>;
}

Expand Down
45 changes: 45 additions & 0 deletions src/app/api/application/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { prisma } from "db";
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";

export async function PUT(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const session = await getServerSession(authOptions);

if (!session) {
return NextResponse.json({ message: "Unauthorized." }, { status: 401 });
}

// Retrieve current user
const user = await prisma.user.findUnique({
where: { email: session?.user?.email as string }
});

if (!user?.isAdmin) {
return NextResponse.json(
{ message: "You're not the admin!" },
{ status: 403 }
);
}

const data = await request.json();
const { approve } = data;

const updatedApplication = await prisma.application.update({
where: { id: params.id },
data: {
approved: approve,
rejected: !approve,
status: approve ? "approved" : "rejected"
}
});

return NextResponse.json(updatedApplication, { status: 200 });
} catch (error) {
return NextResponse.json(error, { status: 500 });
}
}
74 changes: 74 additions & 0 deletions src/app/api/application/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { NextRequest, NextResponse } from "next/server";
import { validate } from "@/middleware/validate";
import { applicationSchema } from "@/schemas/application";
import { prisma } from "db";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";

export async function POST(req: NextRequest) {
try {
const data = await req.json();
return await handleAppRoute(data, req);
} catch (error) {
return NextResponse.json(error, { status: 500 });
}
}

export const handleApplication = async (data: any, request: NextRequest) => {
const session = await getServerSession(authOptions);

if (!session) {
return NextResponse.json({ message: "Unauthorized." }, { status: 401 });
}

if (!data.agree) {
return NextResponse.json(
{ message: "Must agree before submit" },
{ status: 403 }
);
}

const user = await prisma.user.findUnique({
where: { email: session?.user?.email as string },
include: {
application: true
}
});

if (user?.application?.applied) {
return NextResponse.json(
{ message: "You've already submitted an application!" },
{ status: 403 }
);
}

let applicationData = {
name: data.name,
preferredEmail: data.preferredEmail,
school: data.school,
major: data.major,
food: data.food,
class: data.gradYear,
phone: data.phone,
github: data.github,
degree: data.education,
pronouns: data.pronouns,
skillLevel: data.skill,
response: data.response,
userId: user?.id as any,
applied: true,
requirement: true
};

if (data.email !== "") {
// @ts-ignore: ignore email type error
applicationData.email = data.email;
}
await prisma.application.create({
data: applicationData
});

return NextResponse.json(data, { status: 200 });
};

export const handleAppRoute = validate(applicationSchema, handleApplication);
18 changes: 11 additions & 7 deletions src/middleware/validate.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
import { NextRequest, NextResponse } from "next/server";

export function validate(schema: any, handler: NextApiHandler) {
return async (req: NextApiRequest, res: NextApiResponse) => {
if (["POST", "PUT"].includes(req.method as string)) {
type RouteHandler = (data: any, request: NextRequest) => Promise<NextResponse>;

export function validate(schema: any, handler: RouteHandler) {
return async (data: any, request: NextRequest) => {
if (request.method === "POST" || request.method === "PUT") {
try {
req.body = await schema.validate(req.body, {
const validatedData = await schema.validate(data, {
strict: true,
abortEarly: false
});
// Update data with validated values
data = validatedData;
} catch (error) {
return res.status(400).json(error);
return NextResponse.json(error, { status: 400 });
}
}
await handler(req, res);
return await handler(data, request);
};
}
45 changes: 0 additions & 45 deletions src/pages/api/application/[id].ts

This file was deleted.

Loading
Loading