Skip to content

Commit

Permalink
add calendar server actions, UI, home page
Browse files Browse the repository at this point in the history
  • Loading branch information
AdityaRaj0001 committed Jun 27, 2024
1 parent deafbdf commit 038d6f4
Show file tree
Hide file tree
Showing 14 changed files with 845 additions and 129 deletions.
167 changes: 167 additions & 0 deletions src/app/actions/EventActions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
"use server";
import { z } from "zod";
import connectMongoDB from "@/lib/db";
import Event from "@/models/events";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { auth } from "@/auth";

// Define the schema for event validation
const EventSchema = z.object({
date: z.number().min(1, "Date is required."),
title: z.string().min(1, "Title is required."),
venue: z.string().min(1, "Venue is required."),
time: z.string().min(1, "Time is required."),
about: z.string().min(1, "About is required."),
});

// Server action to add an event
export async function addEvent(prevState, formData) {
const session = await auth();
const club = session?.user.email.split("@")[0];

const validatedFields = EventSchema.safeParse({
date: parseInt(formData.get("date")),
title: formData.get("title"),
venue: formData.get("venue"),
time: formData.get("time"), // Updated from timing to time
about: formData.get("about"),
});

// If form validation fails, return errors early. Otherwise, continue.
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: "Missing or invalid fields. Failed to add event.",
};
}

// Extract validated data
const { date, title, venue, time, about } = validatedFields.data;
const eventObject = {
date,
title,
venue,
time,
about,
};

// Insert data into the database
try {
await connectMongoDB();
const event = await Event.findOne({ club });

if (event) {
event.events.push(eventObject);
await event.save();
} else {
await Event.create({
events: [eventObject],
club,
});
}
} catch (error) {
// If a database error occurs, return a more specific error.
return {
message: "Database Error: Failed to add event.",
};
}

// Revalidate the cache for the events page and redirect the user.
revalidatePath("/dashboard/events");
}

export async function updateEvent(prevState, formData) {
// Get the user's session and club
const session = await auth();
const club = session?.user.email.split("@")[0];

// Extract the event index and updated fields from form data

const validatedFields = EventSchema.safeParse({
date: parseInt(formData.get("date")),
title: formData.get("title"),
venue: formData.get("venue"),
time: formData.get("time"),
about: formData.get("about"),
});
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: "Missing or invalid fields. Failed to add event.",
};
}

// Extract validated data
const { title, venue, time, about, date } = validatedFields.data;
const updatedEventObj = {
date,
title,
about,
venue,
time,
};

try {
await connectMongoDB(); // Connect to the database
// Find the event for the specified club
const event = await Event.findOne({ club });

const foundEventObjectIndex = event.events.findIndex(
(e) => e.date === date
);

event.events[foundEventObjectIndex] = updatedEventObj;

// Save the updated event
await event.save();
} catch (error) {
return {
message: "Database Error: Failed to update event.",
status: 500,
};
}

revalidatePath("/dashboard/events");
}

export async function deleteEventByDate(date) {
const session = await auth();
const club = session?.user.email.split("@")[0];

try {
await connectMongoDB();
const event = await Event.findOne({ club });

if (!event) {
return {
message: "Event not found for the club",
status: 404,
};
}

// Filter out the event at the specified index
const updatedEvents = event.events.filter((event) => event.date !== date);

// If the event to delete was not found
if (updatedEvents.length === event.events.length) {
return {
message: "Event not found",
status: 404,
};
}

event.events = updatedEvents;
await event.save();
} catch (error) {
console.error("Error deleting event:", error);
return {
message: "Database Error: Failed to delete event.",
status: 500,
};
}

// Revalidate the cache for the events page
revalidatePath("/dashboard/events");
redirect("/dashboard/events");
}
42 changes: 42 additions & 0 deletions src/app/actions/EventData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import Event from "@/models/events";
import connectMongoDB from "@/lib/db";
import { unstable_noStore as noStore } from "next/cache";

export async function getEventsForClub(club) {
noStore(); // Ensure no caching is done
try {
await connectMongoDB();
const eventRecord = await Event.findOne({ club });

if (!eventRecord) {
return [];
}
return eventRecord.events;
} catch (error) {
return {
message: "Database Error: Failed to retrieve events.",
};
}
}

// Server action to get events for a club on a specific date
export async function getEventsForClubAndDate(club, date) {
noStore(); // Ensure no caching is done
try {
await connectMongoDB();
const eventRecord = await Event.findOne({ club });

if (!eventRecord) {
return {};
}

const foundEventObject = eventRecord.events.findOne((e) => e.date === date);
console.log("founded", foundEventObject);

return foundEventObject;
} catch (error) {
return {
message: "Database Error: Failed to retrieve events.",
};
}
}
35 changes: 27 additions & 8 deletions src/app/dashboard/events/page.jsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,38 @@
import React from "react";
import { MonthCalendar } from "@/components/Calendar";
import { MonthCalendar } from "@/components/Events/Calendar";
import { auth } from "@/auth";
import { getEventsForClub } from "@/app/actions/EventData";

const Page = () => {
const Page = async () => {
const monthNames = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const month = new Date().getMonth(); // Call the function to get the month
const year= new Date().getFullYear()
const year = new Date().getFullYear();
const monthName = monthNames[month];
const session = await auth();
const club = session?.user.email.split("@")[0];
const events = await getEventsForClub(club);
// console.log(events)

return (
<>
<h1 className="w-full pl-6">{monthName} {year} Calendar</h1>
<MonthCalendar />
<div className="w-full h-full flex items-center justify-center flex-col">
<h1 className="w-full text-center font-bold">
{monthName} {year}
</h1>
<MonthCalendar serializedEvents={JSON.stringify(events)}/>
</div>
</>
);
};
Expand Down
4 changes: 3 additions & 1 deletion src/app/page.jsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import Achievements from "@/components/Home/Achievements";
import OurSchedule from "@/components/Home/OurSchedule";
import Gallery from "@/components/Home/Gallery";
import OurTeam from "@/components/Home/OurTeam";
import OurProjects from "@/components/Home/OurProjects";
import GalleryCarousel from "@/components/Home/Carousel";
// import GalleryCarousel from "@/components/Home/Carousel";
import Hero from "@/components/Home/Hero";
import OurBlogs from "@/components/Home/OurBlogs";

Expand All @@ -11,6 +12,7 @@ export default function Home() {
return (
<>
<Hero />
<OurSchedule/>
<Achievements />
<Gallery />
<OurTeam />
Expand Down
90 changes: 0 additions & 90 deletions src/components/Calendar.jsx

This file was deleted.

Loading

0 comments on commit 038d6f4

Please sign in to comment.