diff --git a/app/(default)/achievements/page.tsx b/app/(default)/achievements/page.tsx index 1430cb1..2a833bd 100644 --- a/app/(default)/achievements/page.tsx +++ b/app/(default)/achievements/page.tsx @@ -5,7 +5,7 @@ import axios from "axios"; import { onAuthStateChanged } from "firebase/auth"; import { auth } from "@/Firebase"; import { db } from "@/Firebase"; -import { collection, getDocs } from "firebase/firestore"; +import { collection, doc, getDoc, getDocs } from "firebase/firestore"; interface Achiever { imageUrl?: string; @@ -20,27 +20,6 @@ interface Achiever { } function AchievementCard({ achiever }: { achiever: Achiever }) { - const [isAdmin, setIsAdmin] = useState(false); - - useEffect(() => { - onAuthStateChanged(auth, async (user) => { - if (user) { - //get user uuid - const uid = user.uid; - //check if uuid present in firestore - //if present then set isAdmin to true - const querySnapshot = await getDocs(collection(db, "admin")); - querySnapshot.forEach((doc) => { - if (doc.data().uid === uid) { - setIsAdmin(true); - } - }); - } - }); - }); - - - return (
@@ -82,21 +61,20 @@ export default function AchievementsPage() { useEffect(() => { onAuthStateChanged(auth, async (user) => { if (user) { - //get user uuid const uid = user.uid; - //check if uuid present in firestore - //if present then set isAdmin to true - const querySnapshot = await getDocs(collection(db, "admin")); - querySnapshot.forEach((doc) => { - if (doc.data().uid === uid) { + try { + const adminDocRef = await doc(db, "admin", uid); + const adminDocSnap = await getDoc(adminDocRef); + if (adminDocSnap.exists()) { setIsAdmin(true); } - }); + } catch (error) { + console.log("Error getting document:", error); + } } }); }); - useEffect(() => { async function fetchAchievers() { try { @@ -142,7 +120,10 @@ export default function AchievementsPage() { formData.append("portfolio", newAchievement.portfolio || ""); formData.append("internship", newAchievement.internship || ""); formData.append("companyPosition", newAchievement.companyPosition || ""); - formData.append("achievements", JSON.stringify(newAchievement.achievements || [])); + formData.append( + "achievements", + JSON.stringify(newAchievement.achievements || []) + ); const response = await axios.post("/api/achievements", formData); setAchievers((prev) => [...prev, response.data]); setIsModalOpen(false); @@ -174,8 +155,7 @@ export default function AchievementsPage() { Add Achievements
- ) : null - } + ) : null} {isModalOpen && (
diff --git a/app/(default)/events/page.tsx b/app/(default)/events/page.tsx index a2061a1..0d97d0d 100644 --- a/app/(default)/events/page.tsx +++ b/app/(default)/events/page.tsx @@ -1,10 +1,20 @@ "use client"; -import React, { useState, useEffect } from 'react'; -import { db, auth } from '@/Firebase'; -import { collection, addDoc, getDocs, orderBy, query, updateDoc, doc, deleteDoc } from 'firebase/firestore'; -import { onAuthStateChanged } from 'firebase/auth'; -import './EventCard.css'; +import React, { useState, useEffect } from "react"; +import { db, auth } from "@/Firebase"; +import { + collection, + addDoc, + getDocs, + orderBy, + query, + updateDoc, + doc, + deleteDoc, + getDoc, +} from "firebase/firestore"; +import { onAuthStateChanged } from "firebase/auth"; +import "./EventCard.css"; interface Event { eventName: string; @@ -17,14 +27,14 @@ interface Event { const EventCard: React.FC = () => { const [events, setEvents] = useState([]); - const [eventName, setEventName] = useState(''); - const [description, setDescription] = useState(''); - const [imageUrl, setImageUrl] = useState(''); - const [startDate, setStartDate] = useState(''); - const [endDate, setEndDate] = useState(''); + const [eventName, setEventName] = useState(""); + const [description, setDescription] = useState(""); + const [imageUrl, setImageUrl] = useState(""); + const [startDate, setStartDate] = useState(""); + const [endDate, setEndDate] = useState(""); const [formVisible, setFormVisible] = useState(false); const [editFormVisible, setEditFormVisible] = useState(false); - const [eventToEdit, setEventToEdit] = useState(''); + const [eventToEdit, setEventToEdit] = useState(""); const [eventDataToEdit, setEventDataToEdit] = useState(null); const [isAdmin, setIsAdmin] = useState(false); @@ -33,12 +43,16 @@ const EventCard: React.FC = () => { onAuthStateChanged(auth, async (user) => { if (user) { const uid = user.uid; - const querySnapshot = await getDocs(collection(db, 'admin')); - querySnapshot.forEach((doc) => { - if (doc.data().uid === uid) { + try { + const adminDocRef = await doc(db, "admin", uid); + const adminDocSnap = await getDoc(adminDocRef); + console.log("here =", adminDocSnap.exists()); + if (adminDocSnap.exists()) { setIsAdmin(true); } - }); + } catch (error) { + console.log("Error getting document:", error); + } } }); }; @@ -48,7 +62,7 @@ const EventCard: React.FC = () => { useEffect(() => { const fetchEvents = async () => { - const q = query(collection(db, 'events'), orderBy('startDate')); + const q = query(collection(db, "events"), orderBy("startDate")); const querySnapshot = await getDocs(q); const eventsList: Event[] = []; querySnapshot.forEach((doc) => { @@ -74,21 +88,24 @@ const EventCard: React.FC = () => { }; try { - await addDoc(collection(db, 'events'), newEvent); + await addDoc(collection(db, "events"), newEvent); setEvents((prevEvents) => - [...prevEvents, newEvent].sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime()) + [...prevEvents, newEvent].sort( + (a, b) => + new Date(a.startDate).getTime() - new Date(b.startDate).getTime() + ) ); - setEventName(''); - setDescription(''); - setImageUrl(''); - setStartDate(''); - setEndDate(''); + setEventName(""); + setDescription(""); + setImageUrl(""); + setStartDate(""); + setEndDate(""); setFormVisible(false); } catch (error) { - console.error('Error adding document: ', error); + console.error("Error adding document: ", error); } }; @@ -97,7 +114,7 @@ const EventCard: React.FC = () => { if (!eventDataToEdit || !eventDataToEdit.id) return; try { - const eventRef = doc(db, 'events', eventDataToEdit.id); + const eventRef = doc(db, "events", eventDataToEdit.id); await updateDoc(eventRef, { eventName: eventToEdit, description: description, @@ -107,17 +124,29 @@ const EventCard: React.FC = () => { }); setEvents((prevEvents) => - prevEvents.map((event) => - event.id === eventDataToEdit.id - ? { ...eventDataToEdit, eventName, description, imageUrl, startDate, endDate } - : event - ).sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime()) + prevEvents + .map((event) => + event.id === eventDataToEdit.id + ? { + ...eventDataToEdit, + eventName, + description, + imageUrl, + startDate, + endDate, + } + : event + ) + .sort( + (a, b) => + new Date(a.startDate).getTime() - new Date(b.startDate).getTime() + ) ); setEditFormVisible(false); - setEventToEdit(''); + setEventToEdit(""); } catch (error) { - console.error('Error updating document: ', error); + console.error("Error updating document: ", error); } }; @@ -125,12 +154,14 @@ const EventCard: React.FC = () => { if (!eventDataToEdit || !eventDataToEdit.id) return; try { - await deleteDoc(doc(db, 'events', eventDataToEdit.id)); - setEvents((prevEvents) => prevEvents.filter((event) => event.id !== eventDataToEdit.id)); + await deleteDoc(doc(db, "events", eventDataToEdit.id)); + setEvents((prevEvents) => + prevEvents.filter((event) => event.id !== eventDataToEdit.id) + ); setEditFormVisible(false); - setEventToEdit(''); + setEventToEdit(""); } catch (error) { - console.error('Error deleting document: ', error); + console.error("Error deleting document: ", error); } }; @@ -151,9 +182,17 @@ const EventCard: React.FC = () => { }; const currentDate = new Date(); - const upcomingEvents = events.filter(event => new Date(event.startDate) > currentDate); - const ongoingEvents = events.filter(event => new Date(event.startDate) <= currentDate && new Date(event.endDate) >= currentDate); - const pastEvents = events.filter(event => new Date(event.endDate) < currentDate); + const upcomingEvents = events.filter( + (event) => new Date(event.startDate) > currentDate + ); + const ongoingEvents = events.filter( + (event) => + new Date(event.startDate) <= currentDate && + new Date(event.endDate) >= currentDate + ); + const pastEvents = events.filter( + (event) => new Date(event.endDate) < currentDate + ); const renderEventCards = (events: Event[]) => { if (!events || events.length === 0) { @@ -168,11 +207,17 @@ const EventCard: React.FC = () => {
- {event.eventName} + {event.eventName}

{event.eventName}

-

{event.startDate} {event.endDate && ` - ${event.endDate}`}

+

+ {event.startDate} {event.endDate && ` - ${event.endDate}`} +

@@ -191,11 +236,11 @@ const EventCard: React.FC = () => { {isAdmin && ( <> {formVisible && ( -
+
{ )} {editFormVisible && ( - +
{ />
- + )} diff --git a/components/Members.tsx b/components/Members.tsx index 196dfd5..d2f1ba3 100644 --- a/components/Members.tsx +++ b/components/Members.tsx @@ -1,373 +1,405 @@ "use client"; -import React, { useState, useEffect, useRef } from 'react'; +import React, { useState, useEffect, useRef } from "react"; import Card from "./ui/Card"; -import CollapsibleSection from './ui/CollapsibleSection'; +import CollapsibleSection from "./ui/CollapsibleSection"; import ClipLoader from "react-spinners/ClipLoader"; -import { FaRegBell, FaEllipsisV } from 'react-icons/fa'; +import { FaRegBell, FaEllipsisV } from "react-icons/fa"; import { onAuthStateChanged } from "firebase/auth"; import { auth } from "@/Firebase"; import { db } from "@/Firebase"; -import { collection, getDocs } from "firebase/firestore"; +import { collection, doc, getDoc, getDocs } from "firebase/firestore"; interface Member { - id?: string; - name: string; - domain: string; - company?: string; - year: string; + id?: string; + name: string; + domain: string; + company?: string; + year: string; } -const headings = ["Alumni", "Fourth Year", "Third Year", "Second Year", "First Year"]; +const headings = [ + "Alumni", + "Fourth Year", + "Third Year", + "Second Year", + "First Year", +]; export default function Members() { - const [openIndex, setOpenIndex] = useState(headings.indexOf("Alumni")); - const [data, setData] = useState<{ [key: string]: Member[] }>({}); - const [loading, setLoading] = useState(true); - const [showForm, setShowForm] = useState(false); - const [isEditing, setIsEditing] = useState(false); - const [editMemberId, setEditMemberId] = useState(null); - const [newMember, setNewMember] = useState({ - name: '', - domain: '', - company: '', - year: '' - }); - const [menuVisible, setMenuVisible] = useState<{ [key: string]: boolean }>({}); - const formRef = useRef(null); // Reference to the form container - - const handleToggle = (index: number) => { - setOpenIndex(openIndex === index ? -1 : index); - }; - - const [isAdmin, setIsAdmin] = useState(false); - - useEffect(() => { - onAuthStateChanged(auth, async (user) => { - if (user) { - //get user uuid - const uid = user.uid; - //check if uuid present in firestore - //if present then set isAdmin to true - const querySnapshot = await getDocs(collection(db, "admin")); - querySnapshot.forEach((doc) => { - if (doc.data().uid === uid) { - setIsAdmin(true); - } - }); - } - }); - }); - - - const handleAddOrEditMember = async () => { - if (!newMember.name || !newMember.domain || !newMember.year) { - alert("Please fill in all required fields (Name, Domain/Role, and Year)."); - return; - } - + const [openIndex, setOpenIndex] = useState( + headings.indexOf("Alumni") + ); + const [data, setData] = useState<{ [key: string]: Member[] }>({}); + const [loading, setLoading] = useState(true); + const [showForm, setShowForm] = useState(false); + const [isEditing, setIsEditing] = useState(false); + const [editMemberId, setEditMemberId] = useState(null); + const [newMember, setNewMember] = useState({ + name: "", + domain: "", + company: "", + year: "", + }); + const [menuVisible, setMenuVisible] = useState<{ [key: string]: boolean }>( + {} + ); + const formRef = useRef(null); // Reference to the form container + + const handleToggle = (index: number) => { + setOpenIndex(openIndex === index ? -1 : index); + }; + + const [isAdmin, setIsAdmin] = useState(false); + + useEffect(() => { + onAuthStateChanged(auth, async (user) => { + if (user) { + //get user uuid + const uid = user.uid; try { - const method = isEditing ? 'PUT' : 'POST'; - const memberData = isEditing ? { ...newMember, id: editMemberId } : newMember; - - const response = await fetch('/api/membersData', { - method: method, - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(memberData), - }); - - const result = await response.json(); - - if (!response.ok) { - console.error("Network response was not ok.", result); - throw new Error(result.message || 'Network response was not ok.'); - } - - alert(isEditing ? "Member updated successfully" : "Member added successfully"); - setShowForm(false); - setIsEditing(false); - setEditMemberId(null); - setNewMember({ - name: '', - domain: '', - company: '', - year: '' - }); - await fetchData(); - } catch (error) { - console.error("Error adding/updating member:", error); - alert("An error occurred. Check the console for details."); - } - }; - - - const handleEditMember = (member: Member) => { - setNewMember(member); - setIsEditing(true); - setShowForm(true); - setEditMemberId(member.id || null); - // Scroll to the form - setTimeout(() => { - formRef.current?.scrollIntoView({ behavior: 'smooth' }); - }, 0); - }; - - const handleDeleteMember = async (id: string) => { - try { - const response = await fetch('/api/membersData', { - method: 'DELETE', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ id }), - }); - - if (!response.ok) { - throw new Error('Network response was not ok.'); - } - - const result = await response.json(); - - if (result.error) { - console.error("Error deleting member:", result.message); - alert(result.message); - } else { - alert("Member deleted successfully"); - await fetchData(); - } + const adminDocRef = await doc(db, "admin", uid); + const adminDocSnap = await getDoc(adminDocRef); + console.log("here =", adminDocSnap.exists()); + if (adminDocSnap.exists()) { + setIsAdmin(true); + } } catch (error) { - console.error("Error deleting member:", error); + console.log("Error getting document:", error); } - }; - - const toggleMenu = (id: string) => { - setMenuVisible(prev => ({ ...prev, [id]: !prev[id] })); - }; - - useEffect(() => { - fetchData(); - }, []); - - const fetchData = async () => { - setLoading(true); - try { - const response = await fetch('/api/membersData', { - method: 'GET', - headers: { - 'Content-Type': 'application/json', - } - }); - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - - const result: Member[] = await response.json(); - const uniqueMembersMap = new Map(); - - result.forEach((member: Member) => { - const key = `${member.name}-${member.domain}-${member.year}`; - if (!uniqueMembersMap.has(key)) { - uniqueMembersMap.set(key, member); - } - }); - - const uniqueMembers = Array.from(uniqueMembersMap.values()).sort((a, b) => a.name.localeCompare(b.name)); - const fetchedData: { [key: string]: Member[] } = {}; - - for (const heading of headings) { - fetchedData[heading] = uniqueMembers.filter((member: Member) => member.year === heading); - } - - setData(fetchedData); - } catch (error) { - console.error('Error fetching data: ', error); - } finally { - setLoading(false); + } + }); + }); + + const handleAddOrEditMember = async () => { + if (!newMember.name || !newMember.domain || !newMember.year) { + alert( + "Please fill in all required fields (Name, Domain/Role, and Year)." + ); + return; + } + + try { + const method = isEditing ? "PUT" : "POST"; + const memberData = isEditing + ? { ...newMember, id: editMemberId } + : newMember; + + const response = await fetch("/api/membersData", { + method: method, + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(memberData), + }); + + const result = await response.json(); + + if (!response.ok) { + console.error("Network response was not ok.", result); + throw new Error(result.message || "Network response was not ok."); + } + + alert( + isEditing ? "Member updated successfully" : "Member added successfully" + ); + setShowForm(false); + setIsEditing(false); + setEditMemberId(null); + setNewMember({ + name: "", + domain: "", + company: "", + year: "", + }); + await fetchData(); + } catch (error) { + console.error("Error adding/updating member:", error); + alert("An error occurred. Check the console for details."); + } + }; + + const handleEditMember = (member: Member) => { + setNewMember(member); + setIsEditing(true); + setShowForm(true); + setEditMemberId(member.id || null); + // Scroll to the form + setTimeout(() => { + formRef.current?.scrollIntoView({ behavior: "smooth" }); + }, 0); + }; + + const handleDeleteMember = async (id: string) => { + try { + const response = await fetch("/api/membersData", { + method: "DELETE", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ id }), + }); + + if (!response.ok) { + throw new Error("Network response was not ok."); + } + + const result = await response.json(); + + if (result.error) { + console.error("Error deleting member:", result.message); + alert(result.message); + } else { + alert("Member deleted successfully"); + await fetchData(); + } + } catch (error) { + console.error("Error deleting member:", error); + } + }; + + const toggleMenu = (id: string) => { + setMenuVisible((prev) => ({ ...prev, [id]: !prev[id] })); + }; + + useEffect(() => { + fetchData(); + }, []); + + const fetchData = async () => { + setLoading(true); + try { + const response = await fetch("/api/membersData", { + method: "GET", + headers: { + "Content-Type": "application/json", + }, + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const result: Member[] = await response.json(); + const uniqueMembersMap = new Map(); + + result.forEach((member: Member) => { + const key = `${member.name}-${member.domain}-${member.year}`; + if (!uniqueMembersMap.has(key)) { + uniqueMembersMap.set(key, member); } - }; - - return ( -
-

Point Blank's Team

-
- {loading ? ( -
- -
- ) : ( -
- {headings.map((heading, index) => ( - - {heading === "First Year" && ( -
-

- Recruitment Incoming Soon! -

- - -
- )} -
- {data[heading]?.map((profile, cardIndex) => ( -
- -
- {isAdmin ? ( - - ) : null - } - - {menuVisible[profile.id || ''] && ( -
- - -
- )} -
-
- ))} -
-
- } - isOpen={openIndex === index} - onToggle={() => handleToggle(index)} - /> - ))} -
- )} - - {isAdmin ? ( -
- -
- ) : null - } - - {showForm && ( -
-

- {isEditing ? "Edit Member" : "Add New Member"} -

-
- - - - - -
+ Delete + +
+ )} +
+
+ ))}
- )} -
- - ); -} \ No newline at end of file + + } + isOpen={openIndex === index} + onToggle={() => handleToggle(index)} + /> + ))} + + )} + + {isAdmin ? ( +
+ +
+ ) : null} + + {showForm && ( +
+

+ {isEditing ? "Edit Member" : "Add New Member"} +

+
+ + + + + +
+
+ )} + + + ); +}