diff --git a/app/(api)/_actions/emails/emailTemplates/2026JudgeHubInviteTemplate.ts b/app/(api)/_actions/emails/emailTemplates/2026JudgeHubInviteTemplate.ts new file mode 100644 index 000000000..db6eda9e9 --- /dev/null +++ b/app/(api)/_actions/emails/emailTemplates/2026JudgeHubInviteTemplate.ts @@ -0,0 +1,79 @@ +export default function judgeHubInviteTemplate( + fname: string, + inviteLink: string +) { + const EMAIL_SUBJECT = '[ACTION REQUIRED] HackDavis 2026 Judging App Invite'; + const HEADER_IMAGE_URL = `${process.env.BASE_URL}/email/2025_email_header.png`; + const FOOTER_IMAGE_URL = `${process.env.BASE_URL}/email/2025_email_footer.png`; + const MEETING_RECORDING_URL = + 'https://drive.google.com/file/d/1Lit5fvhev2q8mkv2QyDgTgeh3cfLeX9l/view?usp=sharing'; + const JUDGING_GUIDE_URL = + 'https://www.notion.so/hackdavis/HackDavis-2025-Judging-Guide-1c32d37fcae880b1ba3aeb0a9a7841b7?pvs=4'; + const INVITATION_TO_REGISTER_GUIDE_URL = + 'https://www.notion.so/hackdavis/HackDavis-2025-Judging-Guide-1c32d37fcae880b1ba3aeb0a9a7841b7?pvs=4#1cb2d37fcae880b6a5f4e3d793349bf6'; + const DISCORD_SERVER_URL = 'https://discord.gg/wc6QQEc'; + + return ` + + + + + ${EMAIL_SUBJECT} + + + +
+ HackDavis 2026 header +

Welcome to HackDavis 2026! 🎉

+
+

Hi ${fname},

+
+

Thank you again for joining us as a judge, we’re thrilled to have you on board! Here are some key resources from our virtual orientation:

+

🔹 Meeting Recording: ${MEETING_RECORDING_URL}

+

🔹 Judging Guide: ${JUDGING_GUIDE_URL}

+

You are requested to carefully review the judging guide and familiarize yourself with its content before the event for a smooth judging experience. Kindly do not share the Judging Guide with anyone outside the judging team.

+
+

IMPORTANT NEXT STEP: Create an account on our Judging Application

+

⚠️ The Judging Application is a key prerequisite for the day of the event! Please carefully review the Invitation to Register section of the Judging Guide before proceeding to create your account.

+

Please use the following unique invite link below to create your judge account. Do NOT share it with anyone else.

+

👉 Invite Link: ${inviteLink}

+
+

OPTIONAL: Join our Discord

+

We’ll be using Discord server as our main space for announcements and support during the event. Joining is totally optional for judges, but it’s a great way to:

+

🔹 Get quick answers from the team

+

🔹 Stay in the loop on event updates

+

🔹 Connect with other judges & participants

+

👉 Discord Server: ${DISCORD_SERVER_URL}

+
+

Lastly, we are grateful for your thoughtful feedback during the orientation. As suggested, we will be sharing more details soon about the prize tracks and their eligibility criteria and rubrics to help you get a sense of the tracks ahead of time.

+

Please feel free to reach out if you have any questions or concerns. Looking forward to seeing you at the event!

+
+

Thank you,

+

The HackDavis Team

+
+
+ HackDavis 2026 footer +
+ +`; +} diff --git a/app/(api)/_actions/emails/parseInviteCSV.ts b/app/(api)/_actions/emails/parseInviteCSV.ts new file mode 100644 index 000000000..57ba39fd4 --- /dev/null +++ b/app/(api)/_actions/emails/parseInviteCSV.ts @@ -0,0 +1,88 @@ +import { parse } from 'csv-parse/sync'; +import { z } from 'zod'; +import { JudgeInviteData } from '@typeDefs/emails'; + +const emailSchema = z.string().email(); + +interface ParseResult { + ok: true; + body: JudgeInviteData[]; +} + +interface ParseError { + ok: false; + error: string; +} + +export default function parseInviteCSV( + csvText: string +): ParseResult | ParseError { + try { + if (!csvText.trim()) { + return { ok: false, error: 'CSV file is empty.' }; + } + + const rows: string[][] = parse(csvText, { + trim: true, + skip_empty_lines: true, + }); + + if (rows.length === 0) { + return { ok: false, error: 'CSV file has no rows.' }; + } + + // Detect and skip header row + const firstRow = rows[0].map((cell) => cell.toLowerCase()); + const hasHeader = + firstRow.some((cell) => cell.includes('first')) || + firstRow.some((cell) => cell.includes('email')); + const dataRows = hasHeader ? rows.slice(1) : rows; + + if (dataRows.length === 0) { + return { ok: false, error: 'CSV has a header but no data rows.' }; + } + + const results: JudgeInviteData[] = []; + const errors: string[] = []; + + for (let i = 0; i < dataRows.length; i++) { + const row = dataRows[i]; + const rowNum = hasHeader ? i + 2 : i + 1; + + if (row.length < 3) { + errors.push( + `Row ${rowNum}: expected 3 columns (First Name, Last Name, Email), got ${row.length}.` + ); + continue; + } + + const [firstName, lastName, email] = row; + + if (!firstName) { + errors.push(`Row ${rowNum}: First Name is empty.`); + continue; + } + if (!lastName) { + errors.push(`Row ${rowNum}: Last Name is empty.`); + continue; + } + + const emailResult = emailSchema.safeParse(email); + if (!emailResult.success) { + errors.push(`Row ${rowNum}: "${email}" is not a valid email address.`); + continue; + } + + results.push({ firstName, lastName, email }); + } + + if (errors.length > 0) { + return { ok: false, error: errors.join('\n') }; + } + + return { ok: true, body: results }; + } catch (e) { + const error = e as Error; + return { ok: false, error: `Failed to parse CSV: ${error.message}` }; + } +} diff --git a/app/(api)/_actions/emails/sendBulkJudgeHubInvites.ts b/app/(api)/_actions/emails/sendBulkJudgeHubInvites.ts new file mode 100644 index 000000000..ac8949ba7 --- /dev/null +++ b/app/(api)/_actions/emails/sendBulkJudgeHubInvites.ts @@ -0,0 +1,96 @@ +'use server'; + +import { GetManyUsers } from '@datalib/users/getUser'; +import parseInviteCSV from './parseInviteCSV'; +import sendSingleJudgeHubInvite from './sendSingleJudgeHubInvite'; +import { + BulkJudgeInviteResponse, + JudgeInviteData, + JudgeInviteResult, +} from '@typeDefs/emails'; + +const CONCURRENCY = 10; + +export default async function sendBulkJudgeHubInvites( + csvText: string +): Promise { + // Parse and validate CSV + const parsed = parseInviteCSV(csvText); + if (!parsed.ok) { + return { + ok: false, + results: [], + successCount: 0, + failureCount: 0, + error: parsed.error, + }; + } + + const allJudges = parsed.body; + const results: JudgeInviteResult[] = []; + let successCount = 0; + let failureCount = 0; + + // Single upfront duplicate check for all emails at once + const allEmails = allJudges.map((j) => j.email); + const existingUsers = await GetManyUsers({ email: { $in: allEmails } }); + const existingEmailSet = new Set( + existingUsers.ok + ? existingUsers.body.map((u: { email: string }) => u.email) + : [] + ); + + // Partition judges into duplicates (immediate failure) and new (to send) + const judges: JudgeInviteData[] = []; + for (const judge of allJudges) { + if (existingEmailSet.has(judge.email)) { + results.push({ + email: judge.email, + success: false, + error: 'User already exists.', + }); + failureCount++; + } else { + judges.push(judge); + } + } + + for (let i = 0; i < judges.length; i += CONCURRENCY) { + const batch: JudgeInviteData[] = judges.slice(i, i + CONCURRENCY); + + const batchResults = await Promise.allSettled( + batch.map((judge) => sendSingleJudgeHubInvite(judge, true)) + ); + + for (let j = 0; j < batchResults.length; j++) { + const result = batchResults[j]; + const email = batch[j].email; + + if (result.status === 'fulfilled' && result.value.ok) { + results.push({ + email, + success: true, + inviteUrl: result.value.inviteUrl, + }); + successCount++; + } else { + const errorMsg = + result.status === 'rejected' + ? result.reason?.message ?? 'Unknown error' + : result.value.error ?? 'Unknown error'; + console.error(`[Bulk Judge Invites] ✗ Failed: ${email}`, errorMsg); + results.push({ email, success: false, error: errorMsg }); + failureCount++; + } + } + } + + return { + ok: failureCount === 0, + results, + successCount, + failureCount, + error: + failureCount > 0 ? `${failureCount} invite(s) failed to send.` : null, + }; +} diff --git a/app/(api)/_actions/emails/sendSingleJudgeHubInvite.ts b/app/(api)/_actions/emails/sendSingleJudgeHubInvite.ts new file mode 100644 index 000000000..31104b7cb --- /dev/null +++ b/app/(api)/_actions/emails/sendSingleJudgeHubInvite.ts @@ -0,0 +1,66 @@ +'use server'; + +import GenerateInvite from '@datalib/invite/generateInvite'; +import { GetManyUsers } from '@datalib/users/getUser'; +import { DuplicateError, HttpError } from '@utils/response/Errors'; +import judgeHubInviteTemplate from './emailTemplates/2026JudgeHubInviteTemplate'; +import { DEFAULT_SENDER, transporter } from './transporter'; +import { JudgeInviteData, SingleJudgeInviteResponse } from '@typeDefs/emails'; + +const EMAIL_SUBJECT = '[ACTION REQUIRED] HackDavis 2025 Judging App Invite'; + +export default async function sendSingleJudgeHubInvite( + options: JudgeInviteData, + skipDuplicateCheck = false +): Promise { + const totalStart = Date.now(); + const { firstName, lastName, email } = options; + + try { + // Step 1: duplicate check (skipped in bulk flow — checked upfront there) + if (!skipDuplicateCheck) { + const users = await GetManyUsers({ email }); + if (users.ok && users.body.length > 0) { + throw new DuplicateError(`User with email ${email} already exists.`); + } + } + + // Step 2: generate HMAC-signed invite link + const invite = await GenerateInvite( + { email, name: `${firstName} ${lastName}`, role: 'judge' }, + 'invite' + ); + if (!invite.ok || !invite.body) { + throw new HttpError(invite.error ?? 'Failed to generate invite link.'); + } + + if (!DEFAULT_SENDER) { + throw new Error('Email configuration missing: SENDER_EMAIL is not set.'); + } + + const htmlContent = judgeHubInviteTemplate(firstName, invite.body); + + // Step 3: send email + await transporter.sendMail({ + from: DEFAULT_SENDER, + to: email, + subject: EMAIL_SUBJECT, + html: htmlContent, + }); + return { ok: true, inviteUrl: invite.body, error: null }; + } catch (e) { + const errorMessage = + e instanceof Error + ? e.message + : typeof e === 'string' + ? e + : 'Unknown error'; + console.error( + `[Judge Hub Invite] ✗ Failed (${email}) after ${ + Date.now() - totalStart + }ms:`, + errorMessage + ); + return { ok: false, error: errorMessage }; + } +} diff --git a/app/(api)/_actions/emails/transporter.ts b/app/(api)/_actions/emails/transporter.ts new file mode 100644 index 000000000..ada44c0a3 --- /dev/null +++ b/app/(api)/_actions/emails/transporter.ts @@ -0,0 +1,28 @@ +import nodemailer from 'nodemailer'; + +const SENDER_EMAIL = process.env.SENDER_EMAIL; +const SENDER_PWD = process.env.SENDER_PWD; + +const missingVars: string[] = []; +if (!SENDER_EMAIL) missingVars.push('SENDER_EMAIL'); +if (!SENDER_PWD) missingVars.push('SENDER_PWD'); +if (missingVars.length > 0) { + throw new Error( + `Email transporter: missing environment variable(s): ${missingVars.join( + ', ' + )}` + ); +} + +export const transporter = nodemailer.createTransport({ + service: 'gmail', + pool: true, + maxConnections: 10, + maxMessages: Infinity, // don't recycle connections mid-batch + auth: { + user: SENDER_EMAIL, + pass: SENDER_PWD, + }, +}); + +export const DEFAULT_SENDER = SENDER_EMAIL; diff --git a/app/(pages)/admin/_components/InviteLinkForm/InviteLinkForm.tsx b/app/(pages)/admin/_components/InviteLinkForm/InviteLinkForm.tsx index 81259b06c..7fa5376a7 100644 --- a/app/(pages)/admin/_components/InviteLinkForm/InviteLinkForm.tsx +++ b/app/(pages)/admin/_components/InviteLinkForm/InviteLinkForm.tsx @@ -47,7 +47,7 @@ export default function InviteLinkForm() { return ( <>
-

Invite a User

+

Invite a User [to be deprecated & replaced]

{error}

diff --git a/app/(pages)/admin/_components/JudgeInvites/JudgeBulkInviteForm.tsx b/app/(pages)/admin/_components/JudgeInvites/JudgeBulkInviteForm.tsx new file mode 100644 index 000000000..6d78a0a62 --- /dev/null +++ b/app/(pages)/admin/_components/JudgeInvites/JudgeBulkInviteForm.tsx @@ -0,0 +1,232 @@ +'use client'; + +import { ChangeEvent, useState } from 'react'; +import sendBulkJudgeHubInvites from '@actions/emails/sendBulkJudgeHubInvites'; +import { BulkJudgeInviteResponse, JudgeInviteData } from '@typeDefs/emails'; + +/** + * Browser-safe CSV preview parser (no Node.js deps). Full validation runs server-side. + * Note: uses simple comma-split, so quoted fields containing commas are not supported. + * This is acceptable since judge names/emails rarely contain commas. + */ +function previewCSV( + text: string +): { ok: true; rows: JudgeInviteData[] } | { ok: false; error: string } { + const lines = text + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean); + if (lines.length === 0) return { ok: false, error: 'CSV is empty.' }; + + const firstCells = lines[0].toLowerCase(); + const hasHeader = + firstCells.includes('first') || firstCells.includes('email'); + const dataLines = hasHeader ? lines.slice(1) : lines; + if (dataLines.length === 0) + return { ok: false, error: 'No data rows found.' }; + + const rows: JudgeInviteData[] = []; + for (let i = 0; i < dataLines.length; i++) { + const cols = dataLines[i].split(',').map((c) => c.trim()); + if (cols.length < 3) { + return { + ok: false, + error: `Row ${hasHeader ? i + 2 : i + 1}: expected 3 columns, got ${ + cols.length + }.`, + }; + } + rows.push({ firstName: cols[0], lastName: cols[1], email: cols[2] }); + } + return { ok: true, rows }; +} + +type Status = 'idle' | 'previewing' | 'sending' | 'done'; + +export default function JudgeBulkInviteForm() { + const [status, setStatus] = useState('idle'); + const [csvText, setCsvText] = useState(''); + const [preview, setPreview] = useState([]); + const [parseError, setParseError] = useState(''); + const [result, setResult] = useState(null); + + const handleFileChange = (e: ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + + const reader = new FileReader(); + reader.onload = (ev) => { + const text = ev.target?.result as string; + setCsvText(text); + + const parsed = previewCSV(text); + if (parsed.ok) { + setPreview(parsed.rows); + setParseError(''); + setStatus('previewing'); + } else { + setParseError(parsed.error); + setPreview([]); + setStatus('idle'); + } + }; + reader.readAsText(file); + }; + + const handleSend = async () => { + setStatus('sending'); + setResult(null); + + const response = await sendBulkJudgeHubInvites(csvText); + setResult(response); + setStatus('done'); + }; + + const handleReset = () => { + setStatus('idle'); + setCsvText(''); + setPreview([]); + setParseError(''); + setResult(null); + }; + + return ( +
+ {/* File input */} +
+ + +
+ + {/* Parse error */} + {parseError && ( +
+

CSV errors:

+
+            {parseError}
+          
+
+ )} + + {/* Preview table */} + {status === 'previewing' && preview.length > 0 && ( +
+

+ {preview.length} judge + {preview.length !== 1 ? 's' : ''} found. Review before sending: +

+
+
+ + + + + + + + + + {preview.map((judge, i) => ( + + + + + + ))} + +
+ First Name + + Last Name + + Email +
+ {judge.firstName} + + {judge.lastName} + {judge.email}
+
+
+ +
+ )} + + {/* Sending spinner */} + {status === 'sending' && ( +
+
+ Sending invites… +
+ )} + + {/* Results */} + {status === 'done' && result && ( +
+
+
+

+ {result.successCount} +

+

Sent

+
+
+

+ {result.failureCount} +

+

Failed

+
+
+ + {result.failureCount > 0 && ( +
+

+ Failed invites +

+
+ {result.results + .filter((r) => !r.success) + .map((r, i) => ( +
+ + {r.email} + + {r.error} +
+ ))} +
+
+ )} + + +
+ )} +
+ ); +} diff --git a/app/(pages)/admin/_components/JudgeInvites/JudgeSingleInviteForm.tsx b/app/(pages)/admin/_components/JudgeInvites/JudgeSingleInviteForm.tsx new file mode 100644 index 000000000..8b5e00d2b --- /dev/null +++ b/app/(pages)/admin/_components/JudgeInvites/JudgeSingleInviteForm.tsx @@ -0,0 +1,96 @@ +'use client'; + +import { FormEvent, useState } from 'react'; +import sendSingleJudgeHubInvite from '@actions/emails/sendSingleJudgeHubInvite'; + +export default function JudgeSingleInviteForm() { + const [loading, setLoading] = useState(false); + const [inviteUrl, setInviteUrl] = useState(''); + const [error, setError] = useState(''); + + const handleSubmit = async (e: FormEvent) => { + e.preventDefault(); + setLoading(true); + setInviteUrl(''); + setError(''); + + const formData = new FormData(e.currentTarget); + const firstName = formData.get('firstName') as string; + const lastName = formData.get('lastName') as string; + const email = formData.get('email') as string; + + const result = await sendSingleJudgeHubInvite({ + firstName, + lastName, + email, + }); + + setLoading(false); + + if (result.ok) { + setInviteUrl(result.inviteUrl ?? ''); + (e.target as HTMLFormElement).reset(); + } else { + setError(result.error ?? 'An unexpected error occurred.'); + } + }; + + return ( + +
+
+ + +
+
+ + +
+
+ +
+ + +
+ + + + {error && ( +

+ {error} +

+ )} + {inviteUrl && ( +
+

+ Invite sent! +

+

{inviteUrl}

+
+ )} + + ); +} diff --git a/app/(pages)/admin/invite-link/page.tsx b/app/(pages)/admin/invite-hackers/page.tsx similarity index 52% rename from app/(pages)/admin/invite-link/page.tsx rename to app/(pages)/admin/invite-hackers/page.tsx index 1e03eb424..e042ca6cd 100644 --- a/app/(pages)/admin/invite-link/page.tsx +++ b/app/(pages)/admin/invite-hackers/page.tsx @@ -1,11 +1,10 @@ 'use client'; import InviteLinkForm from '../_components/InviteLinkForm/InviteLinkForm'; -import styles from './invite.module.scss'; -export default function AdminInviteLinkPage() { +export default function InviteJudgesPage() { return ( -
+
); diff --git a/app/(pages)/admin/invite-judges/page.tsx b/app/(pages)/admin/invite-judges/page.tsx new file mode 100644 index 000000000..c892ef0ba --- /dev/null +++ b/app/(pages)/admin/invite-judges/page.tsx @@ -0,0 +1,35 @@ +'use client'; + +import JudgeSingleInviteForm from '../_components/JudgeInvites/JudgeSingleInviteForm'; +import JudgeBulkInviteForm from '../_components/JudgeInvites/JudgeBulkInviteForm'; + +export default function InviteJudgesPage() { + return ( +
+

Invite Judges

+ +
+

Invite a Judge

+

+ Send a HackDavis Hub invite to a single judge by entering their + details below. +

+ +
+ +
+ +
+

Bulk Invite Judges

+

+ Upload a CSV with columns{' '} + + First Name, Last Name, Email + {' '} + to send Hub invites to multiple judges at once. +

+ +
+
+ ); +} diff --git a/app/(pages)/admin/invite-link/invite.module.scss b/app/(pages)/admin/invite-link/invite.module.scss deleted file mode 100644 index 847ca7f68..000000000 --- a/app/(pages)/admin/invite-link/invite.module.scss +++ /dev/null @@ -1,5 +0,0 @@ -.container { - min-height: 100vh; - background-color: var(--background-tertiary); - padding: 24px; -} \ No newline at end of file diff --git a/app/(pages)/admin/page.tsx b/app/(pages)/admin/page.tsx index c7a1f1b5d..cd139d2f1 100644 --- a/app/(pages)/admin/page.tsx +++ b/app/(pages)/admin/page.tsx @@ -22,9 +22,13 @@ const action_links = [ body: 'Create Panels', }, { - href: '/admin/invite-link', + href: '/admin/invite-judges', body: 'Invite Judges', }, + { + href: '/admin/invite-hackers', + body: 'Invite Hackers', + }, { href: '/admin/randomize-projects', body: 'Randomize Projects', diff --git a/app/_types/emails.ts b/app/_types/emails.ts new file mode 100644 index 000000000..9d2c29912 --- /dev/null +++ b/app/_types/emails.ts @@ -0,0 +1,27 @@ +// Judge Hub invite types +export interface JudgeInviteData { + firstName: string; + lastName: string; + email: string; +} + +export interface JudgeInviteResult { + email: string; + success: boolean; + inviteUrl?: string; + error?: string; +} + +export interface BulkJudgeInviteResponse { + ok: boolean; + results: JudgeInviteResult[]; + successCount: number; + failureCount: number; + error: string | null; +} + +export interface SingleJudgeInviteResponse { + ok: boolean; + inviteUrl?: string; + error: string | null; +} diff --git a/public/email/2025_email_footer.png b/public/email/2025_email_footer.png new file mode 100644 index 000000000..0c829d693 Binary files /dev/null and b/public/email/2025_email_footer.png differ diff --git a/public/email/2025_email_header.png b/public/email/2025_email_header.png new file mode 100644 index 000000000..07f7bc97e Binary files /dev/null and b/public/email/2025_email_header.png differ