From b88a35f518645aa67acb5dd1fbb1e5eb069d0ad7 Mon Sep 17 00:00:00 2001 From: 2004yash <134356616+2004yash@users.noreply.github.com> Date: Mon, 23 Sep 2024 19:35:52 +0530 Subject: [PATCH] added edit option in leads page --- components/leadspage.tsx | 497 ++++++++++++++++++++++++++------------- package-lock.json | 1 + 2 files changed, 338 insertions(+), 160 deletions(-) diff --git a/components/leadspage.tsx b/components/leadspage.tsx index 90185d6..f884d2d 100644 --- a/components/leadspage.tsx +++ b/components/leadspage.tsx @@ -1,11 +1,14 @@ "use client"; + import React, { useState, useEffect } from 'react'; import { getAuth, onAuthStateChanged } from 'firebase/auth'; -import { getFirestore, doc, getDoc, setDoc, collection, getDocs, addDoc } from 'firebase/firestore'; +import { getFirestore, doc, getDoc, getDocs, collection, addDoc, updateDoc, deleteDoc } from 'firebase/firestore'; import { getStorage, ref, uploadBytes, getDownloadURL } from 'firebase/storage'; import { auth } from "@/Firebase"; import { db } from "@/Firebase"; +import { ClipLoader } from 'react-spinners'; // If you're using react-spinners + interface Lead { id: string; @@ -17,28 +20,50 @@ interface Lead { } const Leads: React.FC = () => { + const [loading, setLoading] = useState(true); + const [showForm, setShowForm] = useState(false); const [isAdminLoggedIn, setIsAdminLoggedIn] = useState(false); const [currentLeads, setCurrentLeads] = useState([]); const [alumniLeads, setAlumniLeads] = useState([]); + const [selectedLead, setSelectedLead] = useState(null); // For editing leads - useEffect(() => { - // const auth = getAuth(); - // const db = getFirestore(); + // Fetch leads from Firestore + const fetchLeads = async () => { + try { + const leadsRef = collection(db, "leads"); + const querySnapshot = await getDocs(leadsRef); + const currentLeads: Lead[] = []; + const alumniLeads: Lead[] = []; + querySnapshot.forEach((doc) => { + const leadData = doc.data() as Lead; + if (leadData.position === "Current") { + currentLeads.push({ ...leadData, id: doc.id }); + } else { + alumniLeads.push({ ...leadData, id: doc.id }); + } + }); + + setCurrentLeads(currentLeads); + setAlumniLeads(alumniLeads); + await fetchLeads(); + setLoading(false); + } catch (error) { + console.error("Error fetching leads:", error); + setLoading(false); + } + }; + + useEffect(() => { const checkAdmin = async (uid: string) => { try { - console.log(uid); const docRef = doc(db, "admin", uid); const docSnap = await getDoc(docRef); if (docSnap.exists()) { - console.log("helo") setIsAdminLoggedIn(true); - console.log("checked") - // isAdminLoggedIn(true); } else { setIsAdminLoggedIn(false); - console.log(docRef) } } catch (error) { console.error("Error checking admin status:", error); @@ -54,33 +79,74 @@ const Leads: React.FC = () => { } }); - // Fetch leads from Firestore - const fetchLeads = async () => { - const leadsRef = collection(db, "leads"); - const querySnapshot = await getDocs(leadsRef); - const currentLeads: Lead[] = []; - const alumniLeads: Lead[] = []; + fetchLeads(); // Call fetchLeads when component mounts - querySnapshot.forEach((doc) => { - const leadData = doc.data() as Lead; - if (leadData.position === "Current") { - currentLeads.push({ ...leadData, id: doc.id }); - } else { - alumniLeads.push({ ...leadData, id: doc.id }); - } - }); + return () => unsubscribe(); + }, []); - setCurrentLeads(currentLeads); - setAlumniLeads(alumniLeads); - }; + const handleAddOrEditLead = async () => { + if (!selectedLead?.name || !selectedLead?.position) { + alert("Please fill in all required fields (Name and Position)."); + return; + } - fetchLeads(); + try { + const leadData = { ...selectedLead }; + const storage = getStorage(); - return () => unsubscribe(); - }, []); + let imageUrl = selectedLead.imageUrl; + + if (selectedLead.imageUrl && selectedLead.imageUrl.startsWith("blob")) { + const imageRef = ref(storage, `images/${selectedLead.name}`); + const imageBlob = await fetch(selectedLead.imageUrl).then((r) => r.blob()); + await uploadBytes(imageRef, imageBlob); + imageUrl = await getDownloadURL(imageRef); + } + + if (selectedLead.id) { + // Update lead in Firestore + await updateDoc(doc(db, 'leads', selectedLead.id), { + ...leadData, + imageUrl: imageUrl, + }); + alert("Lead updated successfully"); + } else { + // Add new lead to Firestore + await addDoc(collection(db, 'leads'), { + ...leadData, + imageUrl: imageUrl, + }); + alert("Lead added successfully"); + } + + setShowForm(false); + setSelectedLead(null); + await fetchLeads(); // Refresh leads after adding/editing + } catch (error) { + console.error("Error adding/updating lead:", error); + alert("An error occurred. Check the console for details."); + } + }; + + const handleEditLead = (lead: Lead) => { + setSelectedLead(lead); + setShowForm(true); + }; + + const handleDeleteLead = async (id: string) => { + try { + await deleteDoc(doc(db, 'leads', id)); + alert("Lead deleted successfully"); + await fetchLeads(); // Refresh leads after deleting + } catch (error) { + console.error("Error deleting lead:", error); + alert("An error occurred. Check the console for details."); + } + }; const toggleForm = () => { setShowForm(!showForm); + setSelectedLead(null); // Reset form for new lead }; return ( @@ -101,14 +167,20 @@ const Leads: React.FC = () => { zIndex: 1000, }} > - Add Lead + {selectedLead ? 'Edit Lead' : 'Add Lead'} )} - {showForm && } + {showForm && ( + + )} - - + + ); }; @@ -116,9 +188,12 @@ const Leads: React.FC = () => { interface LeadSectionProps { title: string; leads: Lead[]; + onEdit: (lead: Lead) => void; + onDelete: (id: string) => void; + isAdminLoggedIn: boolean; // Added prop to handle admin check } -const LeadSection: React.FC = ({ title, leads }) => ( +const LeadSection: React.FC = ({ title, leads, onEdit, onDelete, isAdminLoggedIn }) => (

= ({ title, leads }) => ( margin: '0 auto', }}> {leads.map((lead) => ( -
+
isAdminLoggedIn && (e.currentTarget.style.transform = 'scale(1.05)')} + onMouseLeave={(e) => isAdminLoggedIn && (e.currentTarget.style.transform = 'scale(1)')} + onClick={() => isAdminLoggedIn && onEdit(lead)} // Only allow edit on click if admin + >
= ({ title, leads }) => ( textAlign: 'center', }}>

{lead.name}

-

{lead.position}

{lead.organization}

{lead.additionalInfo}

+ {isAdminLoggedIn && ( + + )}
))} @@ -172,139 +272,216 @@ const LeadSection: React.FC = ({ title, leads }) => ( interface LeadFormProps { closeForm: () => void; + selectedLead: Lead | null; + onLeadUpdate: () => void; } -const LeadForm: React.FC = ({ closeForm }) => { - const [newLead, setNewLead] = useState>({ - name: '', - position: 'Current', - organization: '', - additionalInfo: '', - }); - const [image, setImage] = useState(null); - - const handleChange = (e: React.ChangeEvent) => { - setNewLead({ - ...newLead, - [e.target.name]: e.target.value, - }); +const LeadForm: React.FC = ({ closeForm, selectedLead, onLeadUpdate }) => { + const [lead, setLead] = useState( + selectedLead || { id: '', name: '', position: '', organization: '', additionalInfo: '', imageUrl: '' } + ); + + const handleChange = (e: React.ChangeEvent) => { + const { name, value } = e.target; + setLead((prevLead) => ({ ...prevLead, [name]: value })); }; - const handleImageChange = (e: React.ChangeEvent) => { + const handleFileChange = (e: React.ChangeEvent) => { if (e.target.files && e.target.files[0]) { - setImage(e.target.files[0]); + setLead((prevLead) => ({ + ...prevLead, + imageUrl: URL.createObjectURL(e.target.files[0]), + })); } }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); - if (!newLead.name || !image) { - alert("Please provide the lead name and image."); - return; - } - - const db = getFirestore(); - const storage = getStorage(); - - try { - // Upload the image to Firebase Storage - const imageRef = ref(storage, `images/${newLead.name}`); - await uploadBytes(imageRef, image); - const imageUrl = await getDownloadURL(imageRef); - - // Add lead to Firestore - await addDoc(collection(db, 'leads'), { - ...newLead, - imageUrl: imageUrl, - }); - - console.log("New Lead Submitted:", { ...newLead, imageUrl }); - closeForm(); - } catch (error) { - console.error("Error adding new lead:", error); - } + await onLeadUpdate(); // Call onLeadUpdate to refresh the leads + closeForm(); // Close the form after submission }; return ( -
-

Add New Lead

-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-