Open
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
7 changes: 6 additions & 1 deletion components/dashboard/Sidebar.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import styles from "../../styles/components/Sidebar.module.scss";
import { SocialLinks } from "../common/SocialLinks/SocialLinks";
import { FaHome } from "react-icons/fa";
import { MdAccountCircle, MdLogout, MdExplore } from "react-icons/md";
import { BiCalendarEvent } from "react-icons/bi";
import { BiCalendarEvent, BiBadgeCheck } from "react-icons/bi";
import { AiFillTrophy, AiOutlineMenu } from "react-icons/ai";
import { SidebarItem } from "./SidebarItem";
import { useState } from "react";
Expand DownExpand Up@@ -32,6 +32,11 @@ const sidebarItems = [
icon: <BiCalendarEvent />,
path: "/dashboard/events",
},
{
title: "Certificates",
icon: <BiBadgeCheck />,
path: "/dashboard/certificates",
},
{
title: "Explore",
icon: <MdExplore />,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"engines": {
"node": "24.x"
"node": "24.x"
},
"scripts": {
"dev": "next dev",
Expand All@@ -30,7 +30,7 @@
"google-spreadsheet": "^4.0.2",
"moment": "^2.29.4",
"next": "13.2.2",
"next-auth": "^4.23.1",
"next-auth": "4.24.5",
"next-pwa": "^5.6.0",
"next-redux-wrapper": "^8.1.0",
"next-seo": "^6.1.0",
Expand Down
356 changes: 356 additions & 0 deletions pages/dashboard/certificates.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
import React, { useEffect, useState, useCallback } from "react";
import { GetServerSidePropsContext } from "next";
import { useSession } from "next-auth/react";
import DashboardLayout from "../../components/layout/DashboardLayout";
import getServerCookieData from "../../lib/getServerCookieData";
import getCookieData from "../../lib/getCookieData";
import {
getCertificates,
createCertificate,
deleteCertificate,
downloadCertificate,
massMailCertificates,
uploadCsvCertificates,
uploadTemplate,
getEvents,
Certificate,
} from "../../repository/certificates";
import styles from "../../styles/pages/certificates.module.scss";

type Status = {
type: "success" | "error" | "info";
message: string;
} | null;

function Certificates() {
const { data: session } = useSession();
const { data: cookieData } = getCookieData(session);
const token = cookieData?.token;

const [events, setEvents] = useState<any[]>([]);
const [selectedEventId, setSelectedEventId] = useState<number | "">("");
const [certificates, setCertificates] = useState<Certificate[]>([]);
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState<Status>(null);

const [templateFile, setTemplateFile] = useState<File | null>(null);
const [csvFile, setCsvFile] = useState<File | null>(null);

const [singleName, setSingleName] = useState("");
const [singleEmail, setSingleEmail] = useState("");

const fetchEvents = useCallback(async () => {
if (!token) return;
try {
const data = await getEvents(token);
setEvents(Array.isArray(data) ? data : []);
} catch {
setStatus({ type: "error", message: "Failed to load events." });
}
}, [token]);

const fetchCertificates = useCallback(async () => {
if (!token || !selectedEventId) return;
setLoading(true);
try {
const data = await getCertificates(token, selectedEventId as number);
setCertificates(Array.isArray(data) ? data : []);
} catch {
setCertificates([]);
} finally {
setLoading(false);
}
}, [token, selectedEventId]);

useEffect(() => {
fetchEvents();
}, [fetchEvents]);

useEffect(() => {
if (selectedEventId) fetchCertificates();
}, [selectedEventId, fetchCertificates]);

const showStatus = (type: NonNullable<Status>["type"], message: string) => {
setStatus({ type, message });
setTimeout(() => setStatus(null), 5000);
};

const handleUploadTemplate = async () => {
if (!templateFile || !selectedEventId || !token) return;
try {
await uploadTemplate(selectedEventId as number, templateFile, token);
showStatus("success", "Template uploaded successfully.");
setTemplateFile(null);
} catch (e: any) {
showStatus("error", e?.message || "Template upload failed.");
}
};

const handleUploadCsv = async () => {
if (!csvFile || !selectedEventId || !token) return;
try {
const msg = await uploadCsvCertificates(
selectedEventId as number,
csvFile,
token
);
showStatus("success", msg as string);
setCsvFile(null);
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "CSV import failed.");
}
};

const handleGenerateSingle = async () => {
if (!singleName.trim() || !singleEmail.trim() || !selectedEventId || !token)
return;
try {
const cert = await createCertificate(
{
recipientName: singleName.trim(),
recipientEmail: singleEmail.trim(),
event: { id: selectedEventId as number },
issueDate: new Date().toISOString().split("T")[0],
},
token
);
showStatus("success", `Certificate created for ${cert.recipientName}.`);
setSingleName("");
setSingleEmail("");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to create certificate.");
}
};

const handleDelete = async (id: number) => {
if (!token) return;
try {
await deleteCertificate(id, token);
showStatus("success", "Certificate deleted.");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to delete certificate.");
}
};

const handleMassMail = async () => {
if (!selectedEventId || !token) return;
try {
const msg = await massMailCertificates(
selectedEventId as number,
token
);
showStatus("info", msg as string);
} catch (e: any) {
showStatus("error", e?.message || "Mass mail failed.");
}
};

const selectedEvent = events.find((e) => e.id === selectedEventId);

return (
<DashboardLayout
title="Certificates | ACM at PEC"
heading="Certificate Management"
>
<div className={styles.certificatesPage}>
{status && (
<div className={styles[status.type]}>{status.message}</div>
)}

<div className={styles.sectionCard}>
<h2>Select Event</h2>
<div className={styles.eventSelector}>
<select
value={selectedEventId}
onChange={(e) =>
setSelectedEventId(
e.target.value ? Number(e.target.value) : ""
)
}
>
<option value="">-- Choose an event --</option>
{events.map((event) => (
<option key={event.id} value={event.id}>
{event.title}
</option>
))}
</select>
</div>
</div>

{selectedEventId && (
<>
<div className={styles.sectionCard}>
<h2>
Upload PDF Template{" "}
<span className={styles.badgeTemplate}>
{selectedEvent?.template ? "Replace" : "Required"}
</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
Upload a Canva PDF with AcroForm fields:{" "}
<code>recipient_name</code>, <code>event_name</code>,{" "}
<code>issue_date</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".pdf"
onChange={(e) =>
setTemplateFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!templateFile}
onClick={handleUploadTemplate}
>
Upload
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>
Bulk Import from CSV{" "}
<span className={styles.badgeCsv}>CSV</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
CSV must have columns: <code>Name</code>, <code>Email</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".csv"
onChange={(e) =>
setCsvFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!csvFile}
onClick={handleUploadCsv}
>
Import
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>Generate Single Certificate</h2>
<div className={styles.singleForm}>
<input
placeholder="Recipient Name"
value={singleName}
onChange={(e) => setSingleName(e.target.value)}
/>
<input
placeholder="Recipient Email"
type="email"
value={singleEmail}
onChange={(e) => setSingleEmail(e.target.value)}
/>
<button
className={styles.generateBtn}
disabled={!singleName.trim() || !singleEmail.trim()}
onClick={handleGenerateSingle}
>
Create
</button>
</div>
</div>

<div className={styles.sectionCard}>
<div className={styles.actionRow}>
<h2 style={{ margin: 0, flex: 1 }}>
Certificates ({certificates.length})
</h2>
<button
className={styles.massMailBtn}
disabled={certificates.length === 0}
onClick={handleMassMail}
>
Mass Mail All
</button>
</div>

{loading ? (
<div className={styles.emptyState}>Loading...</div>
) : certificates.length === 0 ? (
<div className={styles.emptyState}>
No certificates yet. Import via CSV or create one manually.
</div>
) : (
<div className={styles.tableWrapper}>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Issue Date</th>
<th style={{ textAlign: "right" }}>Actions</th>
</tr>
</thead>
<tbody>
{certificates.map((cert) => (
<tr key={cert.id}>
<td>{cert.recipientName}</td>
<td>{cert.recipientEmail}</td>
<td>{cert.issueDate}</td>
<td style={{ textAlign: "right" }}>
<a
href={downloadCertificate(cert.id)}
className={styles.downloadBtn}
style={{
display: "inline-block",
textDecoration: "none",
marginRight: "0.5rem",
}}
>
Download
</a>
<button
className={styles.dangerBtn}
onClick={() => handleDelete(cert.id)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</>
)}
</div>
</DashboardLayout>
);
}

export default Certificates;

export async function getServerSideProps(context: GetServerSidePropsContext) {
const { data } = getServerCookieData(context);
const token = data?.token;

if (!token) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}

return { props: {} };
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Open
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
7 changes: 6 additions & 1 deletion components/dashboard/Sidebar.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import styles from "../../styles/components/Sidebar.module.scss";
import { SocialLinks } from "../common/SocialLinks/SocialLinks";
import { FaHome } from "react-icons/fa";
import { MdAccountCircle, MdLogout, MdExplore } from "react-icons/md";
import { BiCalendarEvent } from "react-icons/bi";
import { BiCalendarEvent, BiBadgeCheck } from "react-icons/bi";
import { AiFillTrophy, AiOutlineMenu } from "react-icons/ai";
import { SidebarItem } from "./SidebarItem";
import { useState } from "react";
Expand DownExpand Up@@ -32,6 +32,11 @@ const sidebarItems = [
icon: <BiCalendarEvent />,
path: "/dashboard/events",
},
{
title: "Certificates",
icon: <BiBadgeCheck />,
path: "/dashboard/certificates",
},
{
title: "Explore",
icon: <MdExplore />,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"engines": {
"node": "24.x"
"node": "24.x"
},
"scripts": {
"dev": "next dev",
Expand All@@ -30,7 +30,7 @@
"google-spreadsheet": "^4.0.2",
"moment": "^2.29.4",
"next": "13.2.2",
"next-auth": "^4.23.1",
"next-auth": "4.24.5",
"next-pwa": "^5.6.0",
"next-redux-wrapper": "^8.1.0",
"next-seo": "^6.1.0",
Expand Down
356 changes: 356 additions & 0 deletions pages/dashboard/certificates.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
import React, { useEffect, useState, useCallback } from "react";
import { GetServerSidePropsContext } from "next";
import { useSession } from "next-auth/react";
import DashboardLayout from "../../components/layout/DashboardLayout";
import getServerCookieData from "../../lib/getServerCookieData";
import getCookieData from "../../lib/getCookieData";
import {
getCertificates,
createCertificate,
deleteCertificate,
downloadCertificate,
massMailCertificates,
uploadCsvCertificates,
uploadTemplate,
getEvents,
Certificate,
} from "../../repository/certificates";
import styles from "../../styles/pages/certificates.module.scss";

type Status = {
type: "success" | "error" | "info";
message: string;
} | null;

function Certificates() {
const { data: session } = useSession();
const { data: cookieData } = getCookieData(session);
const token = cookieData?.token;

const [events, setEvents] = useState<any[]>([]);
const [selectedEventId, setSelectedEventId] = useState<number | "">("");
const [certificates, setCertificates] = useState<Certificate[]>([]);
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState<Status>(null);

const [templateFile, setTemplateFile] = useState<File | null>(null);
const [csvFile, setCsvFile] = useState<File | null>(null);

const [singleName, setSingleName] = useState("");
const [singleEmail, setSingleEmail] = useState("");

const fetchEvents = useCallback(async () => {
if (!token) return;
try {
const data = await getEvents(token);
setEvents(Array.isArray(data) ? data : []);
} catch {
setStatus({ type: "error", message: "Failed to load events." });
}
}, [token]);

const fetchCertificates = useCallback(async () => {
if (!token || !selectedEventId) return;
setLoading(true);
try {
const data = await getCertificates(token, selectedEventId as number);
setCertificates(Array.isArray(data) ? data : []);
} catch {
setCertificates([]);
} finally {
setLoading(false);
}
}, [token, selectedEventId]);

useEffect(() => {
fetchEvents();
}, [fetchEvents]);

useEffect(() => {
if (selectedEventId) fetchCertificates();
}, [selectedEventId, fetchCertificates]);

const showStatus = (type: NonNullable<Status>["type"], message: string) => {
setStatus({ type, message });
setTimeout(() => setStatus(null), 5000);
};

const handleUploadTemplate = async () => {
if (!templateFile || !selectedEventId || !token) return;
try {
await uploadTemplate(selectedEventId as number, templateFile, token);
showStatus("success", "Template uploaded successfully.");
setTemplateFile(null);
} catch (e: any) {
showStatus("error", e?.message || "Template upload failed.");
}
};

const handleUploadCsv = async () => {
if (!csvFile || !selectedEventId || !token) return;
try {
const msg = await uploadCsvCertificates(
selectedEventId as number,
csvFile,
token
);
showStatus("success", msg as string);
setCsvFile(null);
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "CSV import failed.");
}
};

const handleGenerateSingle = async () => {
if (!singleName.trim() || !singleEmail.trim() || !selectedEventId || !token)
return;
try {
const cert = await createCertificate(
{
recipientName: singleName.trim(),
recipientEmail: singleEmail.trim(),
event: { id: selectedEventId as number },
issueDate: new Date().toISOString().split("T")[0],
},
token
);
showStatus("success", `Certificate created for ${cert.recipientName}.`);
setSingleName("");
setSingleEmail("");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to create certificate.");
}
};

const handleDelete = async (id: number) => {
if (!token) return;
try {
await deleteCertificate(id, token);
showStatus("success", "Certificate deleted.");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to delete certificate.");
}
};

const handleMassMail = async () => {
if (!selectedEventId || !token) return;
try {
const msg = await massMailCertificates(
selectedEventId as number,
token
);
showStatus("info", msg as string);
} catch (e: any) {
showStatus("error", e?.message || "Mass mail failed.");
}
};

const selectedEvent = events.find((e) => e.id === selectedEventId);

return (
<DashboardLayout
title="Certificates | ACM at PEC"
heading="Certificate Management"
>
<div className={styles.certificatesPage}>
{status && (
<div className={styles[status.type]}>{status.message}</div>
)}

<div className={styles.sectionCard}>
<h2>Select Event</h2>
<div className={styles.eventSelector}>
<select
value={selectedEventId}
onChange={(e) =>
setSelectedEventId(
e.target.value ? Number(e.target.value) : ""
)
}
>
<option value="">-- Choose an event --</option>
{events.map((event) => (
<option key={event.id} value={event.id}>
{event.title}
</option>
))}
</select>
</div>
</div>

{selectedEventId && (
<>
<div className={styles.sectionCard}>
<h2>
Upload PDF Template{" "}
<span className={styles.badgeTemplate}>
{selectedEvent?.template ? "Replace" : "Required"}
</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
Upload a Canva PDF with AcroForm fields:{" "}
<code>recipient_name</code>, <code>event_name</code>,{" "}
<code>issue_date</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".pdf"
onChange={(e) =>
setTemplateFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!templateFile}
onClick={handleUploadTemplate}
>
Upload
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>
Bulk Import from CSV{" "}
<span className={styles.badgeCsv}>CSV</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
CSV must have columns: <code>Name</code>, <code>Email</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".csv"
onChange={(e) =>
setCsvFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!csvFile}
onClick={handleUploadCsv}
>
Import
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>Generate Single Certificate</h2>
<div className={styles.singleForm}>
<input
placeholder="Recipient Name"
value={singleName}
onChange={(e) => setSingleName(e.target.value)}
/>
<input
placeholder="Recipient Email"
type="email"
value={singleEmail}
onChange={(e) => setSingleEmail(e.target.value)}
/>
<button
className={styles.generateBtn}
disabled={!singleName.trim() || !singleEmail.trim()}
onClick={handleGenerateSingle}
>
Create
</button>
</div>
</div>

<div className={styles.sectionCard}>
<div className={styles.actionRow}>
<h2 style={{ margin: 0, flex: 1 }}>
Certificates ({certificates.length})
</h2>
<button
className={styles.massMailBtn}
disabled={certificates.length === 0}
onClick={handleMassMail}
>
Mass Mail All
</button>
</div>

{loading ? (
<div className={styles.emptyState}>Loading...</div>
) : certificates.length === 0 ? (
<div className={styles.emptyState}>
No certificates yet. Import via CSV or create one manually.
</div>
) : (
<div className={styles.tableWrapper}>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Issue Date</th>
<th style={{ textAlign: "right" }}>Actions</th>
</tr>
</thead>
<tbody>
{certificates.map((cert) => (
<tr key={cert.id}>
<td>{cert.recipientName}</td>
<td>{cert.recipientEmail}</td>
<td>{cert.issueDate}</td>
<td style={{ textAlign: "right" }}>
<a
href={downloadCertificate(cert.id)}
className={styles.downloadBtn}
style={{
display: "inline-block",
textDecoration: "none",
marginRight: "0.5rem",
}}
>
Download
</a>
<button
className={styles.dangerBtn}
onClick={() => handleDelete(cert.id)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</>
)}
</div>
</DashboardLayout>
);
}

export default Certificates;

export async function getServerSideProps(context: GetServerSidePropsContext) {
const { data } = getServerCookieData(context);
const token = data?.token;

if (!token) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}

return { props: {} };
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
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
7 changes: 6 additions & 1 deletion components/dashboard/Sidebar.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import styles from "../../styles/components/Sidebar.module.scss";
import { SocialLinks } from "../common/SocialLinks/SocialLinks";
import { FaHome } from "react-icons/fa";
import { MdAccountCircle, MdLogout, MdExplore } from "react-icons/md";
import { BiCalendarEvent } from "react-icons/bi";
import { BiCalendarEvent, BiBadgeCheck } from "react-icons/bi";
import { AiFillTrophy, AiOutlineMenu } from "react-icons/ai";
import { SidebarItem } from "./SidebarItem";
import { useState } from "react";
Expand DownExpand Up@@ -32,6 +32,11 @@ const sidebarItems = [
icon: <BiCalendarEvent />,
path: "/dashboard/events",
},
{
title: "Certificates",
icon: <BiBadgeCheck />,
path: "/dashboard/certificates",
},
{
title: "Explore",
icon: <MdExplore />,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"engines": {
"node": "24.x"
"node": "24.x"
},
"scripts": {
"dev": "next dev",
Expand All@@ -30,7 +30,7 @@
"google-spreadsheet": "^4.0.2",
"moment": "^2.29.4",
"next": "13.2.2",
"next-auth": "^4.23.1",
"next-auth": "4.24.5",
"next-pwa": "^5.6.0",
"next-redux-wrapper": "^8.1.0",
"next-seo": "^6.1.0",
Expand Down
356 changes: 356 additions & 0 deletions pages/dashboard/certificates.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
import React, { useEffect, useState, useCallback } from "react";
import { GetServerSidePropsContext } from "next";
import { useSession } from "next-auth/react";
import DashboardLayout from "../../components/layout/DashboardLayout";
import getServerCookieData from "../../lib/getServerCookieData";
import getCookieData from "../../lib/getCookieData";
import {
getCertificates,
createCertificate,
deleteCertificate,
downloadCertificate,
massMailCertificates,
uploadCsvCertificates,
uploadTemplate,
getEvents,
Certificate,
} from "../../repository/certificates";
import styles from "../../styles/pages/certificates.module.scss";

type Status = {
type: "success" | "error" | "info";
message: string;
} | null;

function Certificates() {
const { data: session } = useSession();
const { data: cookieData } = getCookieData(session);
const token = cookieData?.token;

const [events, setEvents] = useState<any[]>([]);
const [selectedEventId, setSelectedEventId] = useState<number | "">("");
const [certificates, setCertificates] = useState<Certificate[]>([]);
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState<Status>(null);

const [templateFile, setTemplateFile] = useState<File | null>(null);
const [csvFile, setCsvFile] = useState<File | null>(null);

const [singleName, setSingleName] = useState("");
const [singleEmail, setSingleEmail] = useState("");

const fetchEvents = useCallback(async () => {
if (!token) return;
try {
const data = await getEvents(token);
setEvents(Array.isArray(data) ? data : []);
} catch {
setStatus({ type: "error", message: "Failed to load events." });
}
}, [token]);

const fetchCertificates = useCallback(async () => {
if (!token || !selectedEventId) return;
setLoading(true);
try {
const data = await getCertificates(token, selectedEventId as number);
setCertificates(Array.isArray(data) ? data : []);
} catch {
setCertificates([]);
} finally {
setLoading(false);
}
}, [token, selectedEventId]);

useEffect(() => {
fetchEvents();
}, [fetchEvents]);

useEffect(() => {
if (selectedEventId) fetchCertificates();
}, [selectedEventId, fetchCertificates]);

const showStatus = (type: NonNullable<Status>["type"], message: string) => {
setStatus({ type, message });
setTimeout(() => setStatus(null), 5000);
};

const handleUploadTemplate = async () => {
if (!templateFile || !selectedEventId || !token) return;
try {
await uploadTemplate(selectedEventId as number, templateFile, token);
showStatus("success", "Template uploaded successfully.");
setTemplateFile(null);
} catch (e: any) {
showStatus("error", e?.message || "Template upload failed.");
}
};

const handleUploadCsv = async () => {
if (!csvFile || !selectedEventId || !token) return;
try {
const msg = await uploadCsvCertificates(
selectedEventId as number,
csvFile,
token
);
showStatus("success", msg as string);
setCsvFile(null);
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "CSV import failed.");
}
};

const handleGenerateSingle = async () => {
if (!singleName.trim() || !singleEmail.trim() || !selectedEventId || !token)
return;
try {
const cert = await createCertificate(
{
recipientName: singleName.trim(),
recipientEmail: singleEmail.trim(),
event: { id: selectedEventId as number },
issueDate: new Date().toISOString().split("T")[0],
},
token
);
showStatus("success", `Certificate created for ${cert.recipientName}.`);
setSingleName("");
setSingleEmail("");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to create certificate.");
}
};

const handleDelete = async (id: number) => {
if (!token) return;
try {
await deleteCertificate(id, token);
showStatus("success", "Certificate deleted.");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to delete certificate.");
}
};

const handleMassMail = async () => {
if (!selectedEventId || !token) return;
try {
const msg = await massMailCertificates(
selectedEventId as number,
token
);
showStatus("info", msg as string);
} catch (e: any) {
showStatus("error", e?.message || "Mass mail failed.");
}
};

const selectedEvent = events.find((e) => e.id === selectedEventId);

return (
<DashboardLayout
title="Certificates | ACM at PEC"
heading="Certificate Management"
>
<div className={styles.certificatesPage}>
{status && (
<div className={styles[status.type]}>{status.message}</div>
)}

<div className={styles.sectionCard}>
<h2>Select Event</h2>
<div className={styles.eventSelector}>
<select
value={selectedEventId}
onChange={(e) =>
setSelectedEventId(
e.target.value ? Number(e.target.value) : ""
)
}
>
<option value="">-- Choose an event --</option>
{events.map((event) => (
<option key={event.id} value={event.id}>
{event.title}
</option>
))}
</select>
</div>
</div>

{selectedEventId && (
<>
<div className={styles.sectionCard}>
<h2>
Upload PDF Template{" "}
<span className={styles.badgeTemplate}>
{selectedEvent?.template ? "Replace" : "Required"}
</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
Upload a Canva PDF with AcroForm fields:{" "}
<code>recipient_name</code>, <code>event_name</code>,{" "}
<code>issue_date</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".pdf"
onChange={(e) =>
setTemplateFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!templateFile}
onClick={handleUploadTemplate}
>
Upload
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>
Bulk Import from CSV{" "}
<span className={styles.badgeCsv}>CSV</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
CSV must have columns: <code>Name</code>, <code>Email</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".csv"
onChange={(e) =>
setCsvFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!csvFile}
onClick={handleUploadCsv}
>
Import
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>Generate Single Certificate</h2>
<div className={styles.singleForm}>
<input
placeholder="Recipient Name"
value={singleName}
onChange={(e) => setSingleName(e.target.value)}
/>
<input
placeholder="Recipient Email"
type="email"
value={singleEmail}
onChange={(e) => setSingleEmail(e.target.value)}
/>
<button
className={styles.generateBtn}
disabled={!singleName.trim() || !singleEmail.trim()}
onClick={handleGenerateSingle}
>
Create
</button>
</div>
</div>

<div className={styles.sectionCard}>
<div className={styles.actionRow}>
<h2 style={{ margin: 0, flex: 1 }}>
Certificates ({certificates.length})
</h2>
<button
className={styles.massMailBtn}
disabled={certificates.length === 0}
onClick={handleMassMail}
>
Mass Mail All
</button>
</div>

{loading ? (
<div className={styles.emptyState}>Loading...</div>
) : certificates.length === 0 ? (
<div className={styles.emptyState}>
No certificates yet. Import via CSV or create one manually.
</div>
) : (
<div className={styles.tableWrapper}>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Issue Date</th>
<th style={{ textAlign: "right" }}>Actions</th>
</tr>
</thead>
<tbody>
{certificates.map((cert) => (
<tr key={cert.id}>
<td>{cert.recipientName}</td>
<td>{cert.recipientEmail}</td>
<td>{cert.issueDate}</td>
<td style={{ textAlign: "right" }}>
<a
href={downloadCertificate(cert.id)}
className={styles.downloadBtn}
style={{
display: "inline-block",
textDecoration: "none",
marginRight: "0.5rem",
}}
>
Download
</a>
<button
className={styles.dangerBtn}
onClick={() => handleDelete(cert.id)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</>
)}
</div>
</DashboardLayout>
);
}

export default Certificates;

export async function getServerSideProps(context: GetServerSidePropsContext) {
const { data } = getServerCookieData(context);
const token = data?.token;

if (!token) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}

return { props: {} };
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
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
7 changes: 6 additions & 1 deletion components/dashboard/Sidebar.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import styles from "../../styles/components/Sidebar.module.scss";
import { SocialLinks } from "../common/SocialLinks/SocialLinks";
import { FaHome } from "react-icons/fa";
import { MdAccountCircle, MdLogout, MdExplore } from "react-icons/md";
import { BiCalendarEvent } from "react-icons/bi";
import { BiCalendarEvent, BiBadgeCheck } from "react-icons/bi";
import { AiFillTrophy, AiOutlineMenu } from "react-icons/ai";
import { SidebarItem } from "./SidebarItem";
import { useState } from "react";
Expand DownExpand Up@@ -32,6 +32,11 @@ const sidebarItems = [
icon: <BiCalendarEvent />,
path: "/dashboard/events",
},
{
title: "Certificates",
icon: <BiBadgeCheck />,
path: "/dashboard/certificates",
},
{
title: "Explore",
icon: <MdExplore />,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"engines": {
"node": "24.x"
"node": "24.x"
},
"scripts": {
"dev": "next dev",
Expand All@@ -30,7 +30,7 @@
"google-spreadsheet": "^4.0.2",
"moment": "^2.29.4",
"next": "13.2.2",
"next-auth": "^4.23.1",
"next-auth": "4.24.5",
"next-pwa": "^5.6.0",
"next-redux-wrapper": "^8.1.0",
"next-seo": "^6.1.0",
Expand Down
356 changes: 356 additions & 0 deletions pages/dashboard/certificates.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
import React, { useEffect, useState, useCallback } from "react";
import { GetServerSidePropsContext } from "next";
import { useSession } from "next-auth/react";
import DashboardLayout from "../../components/layout/DashboardLayout";
import getServerCookieData from "../../lib/getServerCookieData";
import getCookieData from "../../lib/getCookieData";
import {
getCertificates,
createCertificate,
deleteCertificate,
downloadCertificate,
massMailCertificates,
uploadCsvCertificates,
uploadTemplate,
getEvents,
Certificate,
} from "../../repository/certificates";
import styles from "../../styles/pages/certificates.module.scss";

type Status = {
type: "success" | "error" | "info";
message: string;
} | null;

function Certificates() {
const { data: session } = useSession();
const { data: cookieData } = getCookieData(session);
const token = cookieData?.token;

const [events, setEvents] = useState<any[]>([]);
const [selectedEventId, setSelectedEventId] = useState<number | "">("");
const [certificates, setCertificates] = useState<Certificate[]>([]);
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState<Status>(null);

const [templateFile, setTemplateFile] = useState<File | null>(null);
const [csvFile, setCsvFile] = useState<File | null>(null);

const [singleName, setSingleName] = useState("");
const [singleEmail, setSingleEmail] = useState("");

const fetchEvents = useCallback(async () => {
if (!token) return;
try {
const data = await getEvents(token);
setEvents(Array.isArray(data) ? data : []);
} catch {
setStatus({ type: "error", message: "Failed to load events." });
}
}, [token]);

const fetchCertificates = useCallback(async () => {
if (!token || !selectedEventId) return;
setLoading(true);
try {
const data = await getCertificates(token, selectedEventId as number);
setCertificates(Array.isArray(data) ? data : []);
} catch {
setCertificates([]);
} finally {
setLoading(false);
}
}, [token, selectedEventId]);

useEffect(() => {
fetchEvents();
}, [fetchEvents]);

useEffect(() => {
if (selectedEventId) fetchCertificates();
}, [selectedEventId, fetchCertificates]);

const showStatus = (type: NonNullable<Status>["type"], message: string) => {
setStatus({ type, message });
setTimeout(() => setStatus(null), 5000);
};

const handleUploadTemplate = async () => {
if (!templateFile || !selectedEventId || !token) return;
try {
await uploadTemplate(selectedEventId as number, templateFile, token);
showStatus("success", "Template uploaded successfully.");
setTemplateFile(null);
} catch (e: any) {
showStatus("error", e?.message || "Template upload failed.");
}
};

const handleUploadCsv = async () => {
if (!csvFile || !selectedEventId || !token) return;
try {
const msg = await uploadCsvCertificates(
selectedEventId as number,
csvFile,
token
);
showStatus("success", msg as string);
setCsvFile(null);
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "CSV import failed.");
}
};

const handleGenerateSingle = async () => {
if (!singleName.trim() || !singleEmail.trim() || !selectedEventId || !token)
return;
try {
const cert = await createCertificate(
{
recipientName: singleName.trim(),
recipientEmail: singleEmail.trim(),
event: { id: selectedEventId as number },
issueDate: new Date().toISOString().split("T")[0],
},
token
);
showStatus("success", `Certificate created for ${cert.recipientName}.`);
setSingleName("");
setSingleEmail("");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to create certificate.");
}
};

const handleDelete = async (id: number) => {
if (!token) return;
try {
await deleteCertificate(id, token);
showStatus("success", "Certificate deleted.");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to delete certificate.");
}
};

const handleMassMail = async () => {
if (!selectedEventId || !token) return;
try {
const msg = await massMailCertificates(
selectedEventId as number,
token
);
showStatus("info", msg as string);
} catch (e: any) {
showStatus("error", e?.message || "Mass mail failed.");
}
};

const selectedEvent = events.find((e) => e.id === selectedEventId);

return (
<DashboardLayout
title="Certificates | ACM at PEC"
heading="Certificate Management"
>
<div className={styles.certificatesPage}>
{status && (
<div className={styles[status.type]}>{status.message}</div>
)}

<div className={styles.sectionCard}>
<h2>Select Event</h2>
<div className={styles.eventSelector}>
<select
value={selectedEventId}
onChange={(e) =>
setSelectedEventId(
e.target.value ? Number(e.target.value) : ""
)
}
>
<option value="">-- Choose an event --</option>
{events.map((event) => (
<option key={event.id} value={event.id}>
{event.title}
</option>
))}
</select>
</div>
</div>

{selectedEventId && (
<>
<div className={styles.sectionCard}>
<h2>
Upload PDF Template{" "}
<span className={styles.badgeTemplate}>
{selectedEvent?.template ? "Replace" : "Required"}
</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
Upload a Canva PDF with AcroForm fields:{" "}
<code>recipient_name</code>, <code>event_name</code>,{" "}
<code>issue_date</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".pdf"
onChange={(e) =>
setTemplateFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!templateFile}
onClick={handleUploadTemplate}
>
Upload
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>
Bulk Import from CSV{" "}
<span className={styles.badgeCsv}>CSV</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
CSV must have columns: <code>Name</code>, <code>Email</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".csv"
onChange={(e) =>
setCsvFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!csvFile}
onClick={handleUploadCsv}
>
Import
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>Generate Single Certificate</h2>
<div className={styles.singleForm}>
<input
placeholder="Recipient Name"
value={singleName}
onChange={(e) => setSingleName(e.target.value)}
/>
<input
placeholder="Recipient Email"
type="email"
value={singleEmail}
onChange={(e) => setSingleEmail(e.target.value)}
/>
<button
className={styles.generateBtn}
disabled={!singleName.trim() || !singleEmail.trim()}
onClick={handleGenerateSingle}
>
Create
</button>
</div>
</div>

<div className={styles.sectionCard}>
<div className={styles.actionRow}>
<h2 style={{ margin: 0, flex: 1 }}>
Certificates ({certificates.length})
</h2>
<button
className={styles.massMailBtn}
disabled={certificates.length === 0}
onClick={handleMassMail}
>
Mass Mail All
</button>
</div>

{loading ? (
<div className={styles.emptyState}>Loading...</div>
) : certificates.length === 0 ? (
<div className={styles.emptyState}>
No certificates yet. Import via CSV or create one manually.
</div>
) : (
<div className={styles.tableWrapper}>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Issue Date</th>
<th style={{ textAlign: "right" }}>Actions</th>
</tr>
</thead>
<tbody>
{certificates.map((cert) => (
<tr key={cert.id}>
<td>{cert.recipientName}</td>
<td>{cert.recipientEmail}</td>
<td>{cert.issueDate}</td>
<td style={{ textAlign: "right" }}>
<a
href={downloadCertificate(cert.id)}
className={styles.downloadBtn}
style={{
display: "inline-block",
textDecoration: "none",
marginRight: "0.5rem",
}}
>
Download
</a>
<button
className={styles.dangerBtn}
onClick={() => handleDelete(cert.id)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</>
)}
</div>
</DashboardLayout>
);
}

export default Certificates;

export async function getServerSideProps(context: GetServerSidePropsContext) {
const { data } = getServerCookieData(context);
const token = data?.token;

if (!token) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}

return { props: {} };
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Open
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
7 changes: 6 additions & 1 deletion components/dashboard/Sidebar.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import styles from "../../styles/components/Sidebar.module.scss";
import { SocialLinks } from "../common/SocialLinks/SocialLinks";
import { FaHome } from "react-icons/fa";
import { MdAccountCircle, MdLogout, MdExplore } from "react-icons/md";
import { BiCalendarEvent } from "react-icons/bi";
import { BiCalendarEvent, BiBadgeCheck } from "react-icons/bi";
import { AiFillTrophy, AiOutlineMenu } from "react-icons/ai";
import { SidebarItem } from "./SidebarItem";
import { useState } from "react";
Expand DownExpand Up@@ -32,6 +32,11 @@ const sidebarItems = [
icon: <BiCalendarEvent />,
path: "/dashboard/events",
},
{
title: "Certificates",
icon: <BiBadgeCheck />,
path: "/dashboard/certificates",
},
{
title: "Explore",
icon: <MdExplore />,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"engines": {
"node": "24.x"
"node": "24.x"
},
"scripts": {
"dev": "next dev",
Expand All@@ -30,7 +30,7 @@
"google-spreadsheet": "^4.0.2",
"moment": "^2.29.4",
"next": "13.2.2",
"next-auth": "^4.23.1",
"next-auth": "4.24.5",
"next-pwa": "^5.6.0",
"next-redux-wrapper": "^8.1.0",
"next-seo": "^6.1.0",
Expand Down
356 changes: 356 additions & 0 deletions pages/dashboard/certificates.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
import React, { useEffect, useState, useCallback } from "react";
import { GetServerSidePropsContext } from "next";
import { useSession } from "next-auth/react";
import DashboardLayout from "../../components/layout/DashboardLayout";
import getServerCookieData from "../../lib/getServerCookieData";
import getCookieData from "../../lib/getCookieData";
import {
getCertificates,
createCertificate,
deleteCertificate,
downloadCertificate,
massMailCertificates,
uploadCsvCertificates,
uploadTemplate,
getEvents,
Certificate,
} from "../../repository/certificates";
import styles from "../../styles/pages/certificates.module.scss";

type Status = {
type: "success" | "error" | "info";
message: string;
} | null;

function Certificates() {
const { data: session } = useSession();
const { data: cookieData } = getCookieData(session);
const token = cookieData?.token;

const [events, setEvents] = useState<any[]>([]);
const [selectedEventId, setSelectedEventId] = useState<number | "">("");
const [certificates, setCertificates] = useState<Certificate[]>([]);
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState<Status>(null);

const [templateFile, setTemplateFile] = useState<File | null>(null);
const [csvFile, setCsvFile] = useState<File | null>(null);

const [singleName, setSingleName] = useState("");
const [singleEmail, setSingleEmail] = useState("");

const fetchEvents = useCallback(async () => {
if (!token) return;
try {
const data = await getEvents(token);
setEvents(Array.isArray(data) ? data : []);
} catch {
setStatus({ type: "error", message: "Failed to load events." });
}
}, [token]);

const fetchCertificates = useCallback(async () => {
if (!token || !selectedEventId) return;
setLoading(true);
try {
const data = await getCertificates(token, selectedEventId as number);
setCertificates(Array.isArray(data) ? data : []);
} catch {
setCertificates([]);
} finally {
setLoading(false);
}
}, [token, selectedEventId]);

useEffect(() => {
fetchEvents();
}, [fetchEvents]);

useEffect(() => {
if (selectedEventId) fetchCertificates();
}, [selectedEventId, fetchCertificates]);

const showStatus = (type: NonNullable<Status>["type"], message: string) => {
setStatus({ type, message });
setTimeout(() => setStatus(null), 5000);
};

const handleUploadTemplate = async () => {
if (!templateFile || !selectedEventId || !token) return;
try {
await uploadTemplate(selectedEventId as number, templateFile, token);
showStatus("success", "Template uploaded successfully.");
setTemplateFile(null);
} catch (e: any) {
showStatus("error", e?.message || "Template upload failed.");
}
};

const handleUploadCsv = async () => {
if (!csvFile || !selectedEventId || !token) return;
try {
const msg = await uploadCsvCertificates(
selectedEventId as number,
csvFile,
token
);
showStatus("success", msg as string);
setCsvFile(null);
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "CSV import failed.");
}
};

const handleGenerateSingle = async () => {
if (!singleName.trim() || !singleEmail.trim() || !selectedEventId || !token)
return;
try {
const cert = await createCertificate(
{
recipientName: singleName.trim(),
recipientEmail: singleEmail.trim(),
event: { id: selectedEventId as number },
issueDate: new Date().toISOString().split("T")[0],
},
token
);
showStatus("success", `Certificate created for ${cert.recipientName}.`);
setSingleName("");
setSingleEmail("");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to create certificate.");
}
};

const handleDelete = async (id: number) => {
if (!token) return;
try {
await deleteCertificate(id, token);
showStatus("success", "Certificate deleted.");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to delete certificate.");
}
};

const handleMassMail = async () => {
if (!selectedEventId || !token) return;
try {
const msg = await massMailCertificates(
selectedEventId as number,
token
);
showStatus("info", msg as string);
} catch (e: any) {
showStatus("error", e?.message || "Mass mail failed.");
}
};

const selectedEvent = events.find((e) => e.id === selectedEventId);

return (
<DashboardLayout
title="Certificates | ACM at PEC"
heading="Certificate Management"
>
<div className={styles.certificatesPage}>
{status && (
<div className={styles[status.type]}>{status.message}</div>
)}

<div className={styles.sectionCard}>
<h2>Select Event</h2>
<div className={styles.eventSelector}>
<select
value={selectedEventId}
onChange={(e) =>
setSelectedEventId(
e.target.value ? Number(e.target.value) : ""
)
}
>
<option value="">-- Choose an event --</option>
{events.map((event) => (
<option key={event.id} value={event.id}>
{event.title}
</option>
))}
</select>
</div>
</div>

{selectedEventId && (
<>
<div className={styles.sectionCard}>
<h2>
Upload PDF Template{" "}
<span className={styles.badgeTemplate}>
{selectedEvent?.template ? "Replace" : "Required"}
</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
Upload a Canva PDF with AcroForm fields:{" "}
<code>recipient_name</code>, <code>event_name</code>,{" "}
<code>issue_date</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".pdf"
onChange={(e) =>
setTemplateFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!templateFile}
onClick={handleUploadTemplate}
>
Upload
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>
Bulk Import from CSV{" "}
<span className={styles.badgeCsv}>CSV</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
CSV must have columns: <code>Name</code>, <code>Email</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".csv"
onChange={(e) =>
setCsvFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!csvFile}
onClick={handleUploadCsv}
>
Import
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>Generate Single Certificate</h2>
<div className={styles.singleForm}>
<input
placeholder="Recipient Name"
value={singleName}
onChange={(e) => setSingleName(e.target.value)}
/>
<input
placeholder="Recipient Email"
type="email"
value={singleEmail}
onChange={(e) => setSingleEmail(e.target.value)}
/>
<button
className={styles.generateBtn}
disabled={!singleName.trim() || !singleEmail.trim()}
onClick={handleGenerateSingle}
>
Create
</button>
</div>
</div>

<div className={styles.sectionCard}>
<div className={styles.actionRow}>
<h2 style={{ margin: 0, flex: 1 }}>
Certificates ({certificates.length})
</h2>
<button
className={styles.massMailBtn}
disabled={certificates.length === 0}
onClick={handleMassMail}
>
Mass Mail All
</button>
</div>

{loading ? (
<div className={styles.emptyState}>Loading...</div>
) : certificates.length === 0 ? (
<div className={styles.emptyState}>
No certificates yet. Import via CSV or create one manually.
</div>
) : (
<div className={styles.tableWrapper}>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Issue Date</th>
<th style={{ textAlign: "right" }}>Actions</th>
</tr>
</thead>
<tbody>
{certificates.map((cert) => (
<tr key={cert.id}>
<td>{cert.recipientName}</td>
<td>{cert.recipientEmail}</td>
<td>{cert.issueDate}</td>
<td style={{ textAlign: "right" }}>
<a
href={downloadCertificate(cert.id)}
className={styles.downloadBtn}
style={{
display: "inline-block",
textDecoration: "none",
marginRight: "0.5rem",
}}
>
Download
</a>
<button
className={styles.dangerBtn}
onClick={() => handleDelete(cert.id)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</>
)}
</div>
</DashboardLayout>
);
}

export default Certificates;

export async function getServerSideProps(context: GetServerSidePropsContext) {
const { data } = getServerCookieData(context);
const token = data?.token;

if (!token) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}

return { props: {} };
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
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
7 changes: 6 additions & 1 deletion components/dashboard/Sidebar.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import styles from "../../styles/components/Sidebar.module.scss";
import { SocialLinks } from "../common/SocialLinks/SocialLinks";
import { FaHome } from "react-icons/fa";
import { MdAccountCircle, MdLogout, MdExplore } from "react-icons/md";
import { BiCalendarEvent } from "react-icons/bi";
import { BiCalendarEvent, BiBadgeCheck } from "react-icons/bi";
import { AiFillTrophy, AiOutlineMenu } from "react-icons/ai";
import { SidebarItem } from "./SidebarItem";
import { useState } from "react";
Expand DownExpand Up@@ -32,6 +32,11 @@ const sidebarItems = [
icon: <BiCalendarEvent />,
path: "/dashboard/events",
},
{
title: "Certificates",
icon: <BiBadgeCheck />,
path: "/dashboard/certificates",
},
{
title: "Explore",
icon: <MdExplore />,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"engines": {
"node": "24.x"
"node": "24.x"
},
"scripts": {
"dev": "next dev",
Expand All@@ -30,7 +30,7 @@
"google-spreadsheet": "^4.0.2",
"moment": "^2.29.4",
"next": "13.2.2",
"next-auth": "^4.23.1",
"next-auth": "4.24.5",
"next-pwa": "^5.6.0",
"next-redux-wrapper": "^8.1.0",
"next-seo": "^6.1.0",
Expand Down
356 changes: 356 additions & 0 deletions pages/dashboard/certificates.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
import React, { useEffect, useState, useCallback } from "react";
import { GetServerSidePropsContext } from "next";
import { useSession } from "next-auth/react";
import DashboardLayout from "../../components/layout/DashboardLayout";
import getServerCookieData from "../../lib/getServerCookieData";
import getCookieData from "../../lib/getCookieData";
import {
getCertificates,
createCertificate,
deleteCertificate,
downloadCertificate,
massMailCertificates,
uploadCsvCertificates,
uploadTemplate,
getEvents,
Certificate,
} from "../../repository/certificates";
import styles from "../../styles/pages/certificates.module.scss";

type Status = {
type: "success" | "error" | "info";
message: string;
} | null;

function Certificates() {
const { data: session } = useSession();
const { data: cookieData } = getCookieData(session);
const token = cookieData?.token;

const [events, setEvents] = useState<any[]>([]);
const [selectedEventId, setSelectedEventId] = useState<number | "">("");
const [certificates, setCertificates] = useState<Certificate[]>([]);
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState<Status>(null);

const [templateFile, setTemplateFile] = useState<File | null>(null);
const [csvFile, setCsvFile] = useState<File | null>(null);

const [singleName, setSingleName] = useState("");
const [singleEmail, setSingleEmail] = useState("");

const fetchEvents = useCallback(async () => {
if (!token) return;
try {
const data = await getEvents(token);
setEvents(Array.isArray(data) ? data : []);
} catch {
setStatus({ type: "error", message: "Failed to load events." });
}
}, [token]);

const fetchCertificates = useCallback(async () => {
if (!token || !selectedEventId) return;
setLoading(true);
try {
const data = await getCertificates(token, selectedEventId as number);
setCertificates(Array.isArray(data) ? data : []);
} catch {
setCertificates([]);
} finally {
setLoading(false);
}
}, [token, selectedEventId]);

useEffect(() => {
fetchEvents();
}, [fetchEvents]);

useEffect(() => {
if (selectedEventId) fetchCertificates();
}, [selectedEventId, fetchCertificates]);

const showStatus = (type: NonNullable<Status>["type"], message: string) => {
setStatus({ type, message });
setTimeout(() => setStatus(null), 5000);
};

const handleUploadTemplate = async () => {
if (!templateFile || !selectedEventId || !token) return;
try {
await uploadTemplate(selectedEventId as number, templateFile, token);
showStatus("success", "Template uploaded successfully.");
setTemplateFile(null);
} catch (e: any) {
showStatus("error", e?.message || "Template upload failed.");
}
};

const handleUploadCsv = async () => {
if (!csvFile || !selectedEventId || !token) return;
try {
const msg = await uploadCsvCertificates(
selectedEventId as number,
csvFile,
token
);
showStatus("success", msg as string);
setCsvFile(null);
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "CSV import failed.");
}
};

const handleGenerateSingle = async () => {
if (!singleName.trim() || !singleEmail.trim() || !selectedEventId || !token)
return;
try {
const cert = await createCertificate(
{
recipientName: singleName.trim(),
recipientEmail: singleEmail.trim(),
event: { id: selectedEventId as number },
issueDate: new Date().toISOString().split("T")[0],
},
token
);
showStatus("success", `Certificate created for ${cert.recipientName}.`);
setSingleName("");
setSingleEmail("");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to create certificate.");
}
};

const handleDelete = async (id: number) => {
if (!token) return;
try {
await deleteCertificate(id, token);
showStatus("success", "Certificate deleted.");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to delete certificate.");
}
};

const handleMassMail = async () => {
if (!selectedEventId || !token) return;
try {
const msg = await massMailCertificates(
selectedEventId as number,
token
);
showStatus("info", msg as string);
} catch (e: any) {
showStatus("error", e?.message || "Mass mail failed.");
}
};

const selectedEvent = events.find((e) => e.id === selectedEventId);

return (
<DashboardLayout
title="Certificates | ACM at PEC"
heading="Certificate Management"
>
<div className={styles.certificatesPage}>
{status && (
<div className={styles[status.type]}>{status.message}</div>
)}

<div className={styles.sectionCard}>
<h2>Select Event</h2>
<div className={styles.eventSelector}>
<select
value={selectedEventId}
onChange={(e) =>
setSelectedEventId(
e.target.value ? Number(e.target.value) : ""
)
}
>
<option value="">-- Choose an event --</option>
{events.map((event) => (
<option key={event.id} value={event.id}>
{event.title}
</option>
))}
</select>
</div>
</div>

{selectedEventId && (
<>
<div className={styles.sectionCard}>
<h2>
Upload PDF Template{" "}
<span className={styles.badgeTemplate}>
{selectedEvent?.template ? "Replace" : "Required"}
</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
Upload a Canva PDF with AcroForm fields:{" "}
<code>recipient_name</code>, <code>event_name</code>,{" "}
<code>issue_date</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".pdf"
onChange={(e) =>
setTemplateFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!templateFile}
onClick={handleUploadTemplate}
>
Upload
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>
Bulk Import from CSV{" "}
<span className={styles.badgeCsv}>CSV</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
CSV must have columns: <code>Name</code>, <code>Email</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".csv"
onChange={(e) =>
setCsvFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!csvFile}
onClick={handleUploadCsv}
>
Import
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>Generate Single Certificate</h2>
<div className={styles.singleForm}>
<input
placeholder="Recipient Name"
value={singleName}
onChange={(e) => setSingleName(e.target.value)}
/>
<input
placeholder="Recipient Email"
type="email"
value={singleEmail}
onChange={(e) => setSingleEmail(e.target.value)}
/>
<button
className={styles.generateBtn}
disabled={!singleName.trim() || !singleEmail.trim()}
onClick={handleGenerateSingle}
>
Create
</button>
</div>
</div>

<div className={styles.sectionCard}>
<div className={styles.actionRow}>
<h2 style={{ margin: 0, flex: 1 }}>
Certificates ({certificates.length})
</h2>
<button
className={styles.massMailBtn}
disabled={certificates.length === 0}
onClick={handleMassMail}
>
Mass Mail All
</button>
</div>

{loading ? (
<div className={styles.emptyState}>Loading...</div>
) : certificates.length === 0 ? (
<div className={styles.emptyState}>
No certificates yet. Import via CSV or create one manually.
</div>
) : (
<div className={styles.tableWrapper}>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Issue Date</th>
<th style={{ textAlign: "right" }}>Actions</th>
</tr>
</thead>
<tbody>
{certificates.map((cert) => (
<tr key={cert.id}>
<td>{cert.recipientName}</td>
<td>{cert.recipientEmail}</td>
<td>{cert.issueDate}</td>
<td style={{ textAlign: "right" }}>
<a
href={downloadCertificate(cert.id)}
className={styles.downloadBtn}
style={{
display: "inline-block",
textDecoration: "none",
marginRight: "0.5rem",
}}
>
Download
</a>
<button
className={styles.dangerBtn}
onClick={() => handleDelete(cert.id)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</>
)}
</div>
</DashboardLayout>
);
}

export default Certificates;

export async function getServerSideProps(context: GetServerSidePropsContext) {
const { data } = getServerCookieData(context);
const token = data?.token;

if (!token) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}

return { props: {} };
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
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
7 changes: 6 additions & 1 deletion components/dashboard/Sidebar.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import styles from "../../styles/components/Sidebar.module.scss";
import { SocialLinks } from "../common/SocialLinks/SocialLinks";
import { FaHome } from "react-icons/fa";
import { MdAccountCircle, MdLogout, MdExplore } from "react-icons/md";
import { BiCalendarEvent } from "react-icons/bi";
import { BiCalendarEvent, BiBadgeCheck } from "react-icons/bi";
import { AiFillTrophy, AiOutlineMenu } from "react-icons/ai";
import { SidebarItem } from "./SidebarItem";
import { useState } from "react";
Expand DownExpand Up@@ -32,6 +32,11 @@ const sidebarItems = [
icon: <BiCalendarEvent />,
path: "/dashboard/events",
},
{
title: "Certificates",
icon: <BiBadgeCheck />,
path: "/dashboard/certificates",
},
{
title: "Explore",
icon: <MdExplore />,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"engines": {
"node": "24.x"
"node": "24.x"
},
"scripts": {
"dev": "next dev",
Expand All@@ -30,7 +30,7 @@
"google-spreadsheet": "^4.0.2",
"moment": "^2.29.4",
"next": "13.2.2",
"next-auth": "^4.23.1",
"next-auth": "4.24.5",
"next-pwa": "^5.6.0",
"next-redux-wrapper": "^8.1.0",
"next-seo": "^6.1.0",
Expand Down
356 changes: 356 additions & 0 deletions pages/dashboard/certificates.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
import React, { useEffect, useState, useCallback } from "react";
import { GetServerSidePropsContext } from "next";
import { useSession } from "next-auth/react";
import DashboardLayout from "../../components/layout/DashboardLayout";
import getServerCookieData from "../../lib/getServerCookieData";
import getCookieData from "../../lib/getCookieData";
import {
getCertificates,
createCertificate,
deleteCertificate,
downloadCertificate,
massMailCertificates,
uploadCsvCertificates,
uploadTemplate,
getEvents,
Certificate,
} from "../../repository/certificates";
import styles from "../../styles/pages/certificates.module.scss";

type Status = {
type: "success" | "error" | "info";
message: string;
} | null;

function Certificates() {
const { data: session } = useSession();
const { data: cookieData } = getCookieData(session);
const token = cookieData?.token;

const [events, setEvents] = useState<any[]>([]);
const [selectedEventId, setSelectedEventId] = useState<number | "">("");
const [certificates, setCertificates] = useState<Certificate[]>([]);
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState<Status>(null);

const [templateFile, setTemplateFile] = useState<File | null>(null);
const [csvFile, setCsvFile] = useState<File | null>(null);

const [singleName, setSingleName] = useState("");
const [singleEmail, setSingleEmail] = useState("");

const fetchEvents = useCallback(async () => {
if (!token) return;
try {
const data = await getEvents(token);
setEvents(Array.isArray(data) ? data : []);
} catch {
setStatus({ type: "error", message: "Failed to load events." });
}
}, [token]);

const fetchCertificates = useCallback(async () => {
if (!token || !selectedEventId) return;
setLoading(true);
try {
const data = await getCertificates(token, selectedEventId as number);
setCertificates(Array.isArray(data) ? data : []);
} catch {
setCertificates([]);
} finally {
setLoading(false);
}
}, [token, selectedEventId]);

useEffect(() => {
fetchEvents();
}, [fetchEvents]);

useEffect(() => {
if (selectedEventId) fetchCertificates();
}, [selectedEventId, fetchCertificates]);

const showStatus = (type: NonNullable<Status>["type"], message: string) => {
setStatus({ type, message });
setTimeout(() => setStatus(null), 5000);
};

const handleUploadTemplate = async () => {
if (!templateFile || !selectedEventId || !token) return;
try {
await uploadTemplate(selectedEventId as number, templateFile, token);
showStatus("success", "Template uploaded successfully.");
setTemplateFile(null);
} catch (e: any) {
showStatus("error", e?.message || "Template upload failed.");
}
};

const handleUploadCsv = async () => {
if (!csvFile || !selectedEventId || !token) return;
try {
const msg = await uploadCsvCertificates(
selectedEventId as number,
csvFile,
token
);
showStatus("success", msg as string);
setCsvFile(null);
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "CSV import failed.");
}
};

const handleGenerateSingle = async () => {
if (!singleName.trim() || !singleEmail.trim() || !selectedEventId || !token)
return;
try {
const cert = await createCertificate(
{
recipientName: singleName.trim(),
recipientEmail: singleEmail.trim(),
event: { id: selectedEventId as number },
issueDate: new Date().toISOString().split("T")[0],
},
token
);
showStatus("success", `Certificate created for ${cert.recipientName}.`);
setSingleName("");
setSingleEmail("");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to create certificate.");
}
};

const handleDelete = async (id: number) => {
if (!token) return;
try {
await deleteCertificate(id, token);
showStatus("success", "Certificate deleted.");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to delete certificate.");
}
};

const handleMassMail = async () => {
if (!selectedEventId || !token) return;
try {
const msg = await massMailCertificates(
selectedEventId as number,
token
);
showStatus("info", msg as string);
} catch (e: any) {
showStatus("error", e?.message || "Mass mail failed.");
}
};

const selectedEvent = events.find((e) => e.id === selectedEventId);

return (
<DashboardLayout
title="Certificates | ACM at PEC"
heading="Certificate Management"
>
<div className={styles.certificatesPage}>
{status && (
<div className={styles[status.type]}>{status.message}</div>
)}

<div className={styles.sectionCard}>
<h2>Select Event</h2>
<div className={styles.eventSelector}>
<select
value={selectedEventId}
onChange={(e) =>
setSelectedEventId(
e.target.value ? Number(e.target.value) : ""
)
}
>
<option value="">-- Choose an event --</option>
{events.map((event) => (
<option key={event.id} value={event.id}>
{event.title}
</option>
))}
</select>
</div>
</div>

{selectedEventId && (
<>
<div className={styles.sectionCard}>
<h2>
Upload PDF Template{" "}
<span className={styles.badgeTemplate}>
{selectedEvent?.template ? "Replace" : "Required"}
</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
Upload a Canva PDF with AcroForm fields:{" "}
<code>recipient_name</code>, <code>event_name</code>,{" "}
<code>issue_date</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".pdf"
onChange={(e) =>
setTemplateFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!templateFile}
onClick={handleUploadTemplate}
>
Upload
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>
Bulk Import from CSV{" "}
<span className={styles.badgeCsv}>CSV</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
CSV must have columns: <code>Name</code>, <code>Email</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".csv"
onChange={(e) =>
setCsvFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!csvFile}
onClick={handleUploadCsv}
>
Import
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>Generate Single Certificate</h2>
<div className={styles.singleForm}>
<input
placeholder="Recipient Name"
value={singleName}
onChange={(e) => setSingleName(e.target.value)}
/>
<input
placeholder="Recipient Email"
type="email"
value={singleEmail}
onChange={(e) => setSingleEmail(e.target.value)}
/>
<button
className={styles.generateBtn}
disabled={!singleName.trim() || !singleEmail.trim()}
onClick={handleGenerateSingle}
>
Create
</button>
</div>
</div>

<div className={styles.sectionCard}>
<div className={styles.actionRow}>
<h2 style={{ margin: 0, flex: 1 }}>
Certificates ({certificates.length})
</h2>
<button
className={styles.massMailBtn}
disabled={certificates.length === 0}
onClick={handleMassMail}
>
Mass Mail All
</button>
</div>

{loading ? (
<div className={styles.emptyState}>Loading...</div>
) : certificates.length === 0 ? (
<div className={styles.emptyState}>
No certificates yet. Import via CSV or create one manually.
</div>
) : (
<div className={styles.tableWrapper}>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Issue Date</th>
<th style={{ textAlign: "right" }}>Actions</th>
</tr>
</thead>
<tbody>
{certificates.map((cert) => (
<tr key={cert.id}>
<td>{cert.recipientName}</td>
<td>{cert.recipientEmail}</td>
<td>{cert.issueDate}</td>
<td style={{ textAlign: "right" }}>
<a
href={downloadCertificate(cert.id)}
className={styles.downloadBtn}
style={{
display: "inline-block",
textDecoration: "none",
marginRight: "0.5rem",
}}
>
Download
</a>
<button
className={styles.dangerBtn}
onClick={() => handleDelete(cert.id)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</>
)}
</div>
</DashboardLayout>
);
}

export default Certificates;

export async function getServerSideProps(context: GetServerSidePropsContext) {
const { data } = getServerCookieData(context);
const token = data?.token;

if (!token) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}

return { props: {} };
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Open
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
7 changes: 6 additions & 1 deletion components/dashboard/Sidebar.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import styles from "../../styles/components/Sidebar.module.scss";
import { SocialLinks } from "../common/SocialLinks/SocialLinks";
import { FaHome } from "react-icons/fa";
import { MdAccountCircle, MdLogout, MdExplore } from "react-icons/md";
import { BiCalendarEvent } from "react-icons/bi";
import { BiCalendarEvent, BiBadgeCheck } from "react-icons/bi";
import { AiFillTrophy, AiOutlineMenu } from "react-icons/ai";
import { SidebarItem } from "./SidebarItem";
import { useState } from "react";
Expand DownExpand Up@@ -32,6 +32,11 @@ const sidebarItems = [
icon: <BiCalendarEvent />,
path: "/dashboard/events",
},
{
title: "Certificates",
icon: <BiBadgeCheck />,
path: "/dashboard/certificates",
},
{
title: "Explore",
icon: <MdExplore />,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"engines": {
"node": "24.x"
"node": "24.x"
},
"scripts": {
"dev": "next dev",
Expand All@@ -30,7 +30,7 @@
"google-spreadsheet": "^4.0.2",
"moment": "^2.29.4",
"next": "13.2.2",
"next-auth": "^4.23.1",
"next-auth": "4.24.5",
"next-pwa": "^5.6.0",
"next-redux-wrapper": "^8.1.0",
"next-seo": "^6.1.0",
Expand Down
356 changes: 356 additions & 0 deletions pages/dashboard/certificates.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
import React, { useEffect, useState, useCallback } from "react";
import { GetServerSidePropsContext } from "next";
import { useSession } from "next-auth/react";
import DashboardLayout from "../../components/layout/DashboardLayout";
import getServerCookieData from "../../lib/getServerCookieData";
import getCookieData from "../../lib/getCookieData";
import {
getCertificates,
createCertificate,
deleteCertificate,
downloadCertificate,
massMailCertificates,
uploadCsvCertificates,
uploadTemplate,
getEvents,
Certificate,
} from "../../repository/certificates";
import styles from "../../styles/pages/certificates.module.scss";

type Status = {
type: "success" | "error" | "info";
message: string;
} | null;

function Certificates() {
const { data: session } = useSession();
const { data: cookieData } = getCookieData(session);
const token = cookieData?.token;

const [events, setEvents] = useState<any[]>([]);
const [selectedEventId, setSelectedEventId] = useState<number | "">("");
const [certificates, setCertificates] = useState<Certificate[]>([]);
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState<Status>(null);

const [templateFile, setTemplateFile] = useState<File | null>(null);
const [csvFile, setCsvFile] = useState<File | null>(null);

const [singleName, setSingleName] = useState("");
const [singleEmail, setSingleEmail] = useState("");

const fetchEvents = useCallback(async () => {
if (!token) return;
try {
const data = await getEvents(token);
setEvents(Array.isArray(data) ? data : []);
} catch {
setStatus({ type: "error", message: "Failed to load events." });
}
}, [token]);

const fetchCertificates = useCallback(async () => {
if (!token || !selectedEventId) return;
setLoading(true);
try {
const data = await getCertificates(token, selectedEventId as number);
setCertificates(Array.isArray(data) ? data : []);
} catch {
setCertificates([]);
} finally {
setLoading(false);
}
}, [token, selectedEventId]);

useEffect(() => {
fetchEvents();
}, [fetchEvents]);

useEffect(() => {
if (selectedEventId) fetchCertificates();
}, [selectedEventId, fetchCertificates]);

const showStatus = (type: NonNullable<Status>["type"], message: string) => {
setStatus({ type, message });
setTimeout(() => setStatus(null), 5000);
};

const handleUploadTemplate = async () => {
if (!templateFile || !selectedEventId || !token) return;
try {
await uploadTemplate(selectedEventId as number, templateFile, token);
showStatus("success", "Template uploaded successfully.");
setTemplateFile(null);
} catch (e: any) {
showStatus("error", e?.message || "Template upload failed.");
}
};

const handleUploadCsv = async () => {
if (!csvFile || !selectedEventId || !token) return;
try {
const msg = await uploadCsvCertificates(
selectedEventId as number,
csvFile,
token
);
showStatus("success", msg as string);
setCsvFile(null);
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "CSV import failed.");
}
};

const handleGenerateSingle = async () => {
if (!singleName.trim() || !singleEmail.trim() || !selectedEventId || !token)
return;
try {
const cert = await createCertificate(
{
recipientName: singleName.trim(),
recipientEmail: singleEmail.trim(),
event: { id: selectedEventId as number },
issueDate: new Date().toISOString().split("T")[0],
},
token
);
showStatus("success", `Certificate created for ${cert.recipientName}.`);
setSingleName("");
setSingleEmail("");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to create certificate.");
}
};

const handleDelete = async (id: number) => {
if (!token) return;
try {
await deleteCertificate(id, token);
showStatus("success", "Certificate deleted.");
fetchCertificates();
} catch (e: any) {
showStatus("error", e?.message || "Failed to delete certificate.");
}
};

const handleMassMail = async () => {
if (!selectedEventId || !token) return;
try {
const msg = await massMailCertificates(
selectedEventId as number,
token
);
showStatus("info", msg as string);
} catch (e: any) {
showStatus("error", e?.message || "Mass mail failed.");
}
};

const selectedEvent = events.find((e) => e.id === selectedEventId);

return (
<DashboardLayout
title="Certificates | ACM at PEC"
heading="Certificate Management"
>
<div className={styles.certificatesPage}>
{status && (
<div className={styles[status.type]}>{status.message}</div>
)}

<div className={styles.sectionCard}>
<h2>Select Event</h2>
<div className={styles.eventSelector}>
<select
value={selectedEventId}
onChange={(e) =>
setSelectedEventId(
e.target.value ? Number(e.target.value) : ""
)
}
>
<option value="">-- Choose an event --</option>
{events.map((event) => (
<option key={event.id} value={event.id}>
{event.title}
</option>
))}
</select>
</div>
</div>

{selectedEventId && (
<>
<div className={styles.sectionCard}>
<h2>
Upload PDF Template{" "}
<span className={styles.badgeTemplate}>
{selectedEvent?.template ? "Replace" : "Required"}
</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
Upload a Canva PDF with AcroForm fields:{" "}
<code>recipient_name</code>, <code>event_name</code>,{" "}
<code>issue_date</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".pdf"
onChange={(e) =>
setTemplateFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!templateFile}
onClick={handleUploadTemplate}
>
Upload
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>
Bulk Import from CSV{" "}
<span className={styles.badgeCsv}>CSV</span>
</h2>
<p style={{ marginBottom: "0.75rem", color: "#595959" }}>
CSV must have columns: <code>Name</code>, <code>Email</code>
</p>
<div className={styles.sectionRow}>
<div className={styles.fileInput}>
<input
type="file"
accept=".csv"
onChange={(e) =>
setCsvFile(e.target.files?.[0] ?? null)
}
/>
</div>
<button
className={styles.uploadBtn}
disabled={!csvFile}
onClick={handleUploadCsv}
>
Import
</button>
</div>
</div>

<div className={styles.sectionCard}>
<h2>Generate Single Certificate</h2>
<div className={styles.singleForm}>
<input
placeholder="Recipient Name"
value={singleName}
onChange={(e) => setSingleName(e.target.value)}
/>
<input
placeholder="Recipient Email"
type="email"
value={singleEmail}
onChange={(e) => setSingleEmail(e.target.value)}
/>
<button
className={styles.generateBtn}
disabled={!singleName.trim() || !singleEmail.trim()}
onClick={handleGenerateSingle}
>
Create
</button>
</div>
</div>

<div className={styles.sectionCard}>
<div className={styles.actionRow}>
<h2 style={{ margin: 0, flex: 1 }}>
Certificates ({certificates.length})
</h2>
<button
className={styles.massMailBtn}
disabled={certificates.length === 0}
onClick={handleMassMail}
>
Mass Mail All
</button>
</div>

{loading ? (
<div className={styles.emptyState}>Loading...</div>
) : certificates.length === 0 ? (
<div className={styles.emptyState}>
No certificates yet. Import via CSV or create one manually.
</div>
) : (
<div className={styles.tableWrapper}>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Issue Date</th>
<th style={{ textAlign: "right" }}>Actions</th>
</tr>
</thead>
<tbody>
{certificates.map((cert) => (
<tr key={cert.id}>
<td>{cert.recipientName}</td>
<td>{cert.recipientEmail}</td>
<td>{cert.issueDate}</td>
<td style={{ textAlign: "right" }}>
<a
href={downloadCertificate(cert.id)}
className={styles.downloadBtn}
style={{
display: "inline-block",
textDecoration: "none",
marginRight: "0.5rem",
}}
>
Download
</a>
<button
className={styles.dangerBtn}
onClick={() => handleDelete(cert.id)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</>
)}
</div>
</DashboardLayout>
);
}

export default Certificates;

export async function getServerSideProps(context: GetServerSidePropsContext) {
const { data } = getServerCookieData(context);
const token = data?.token;

if (!token) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}

return { props: {} };
}
Loading