generated from include-davis/Next.js-App-Router-Starter
-
Notifications
You must be signed in to change notification settings - Fork 3
Judge email invites #406
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Judge email invites #406
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
c3df639
Judge invites!
ReehalS 302ee39
Linty lint
ReehalS f4d2371
Fix image URL and error handling for sending emails
ReehalS 2ee04c4
Document browser preview csv parser
ReehalS 47aef86
Throw error for missing email ENV vars
ReehalS 069aece
cleaned code and updated email
michelleyeoh b41745b
fixed email template
michelleyeoh 0fee260
Merge branch 'main' into 397-judge-email-invites
michelleyeoh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
79 changes: 79 additions & 0 deletions
79
app/(api)/_actions/emails/emailTemplates/2026JudgeHubInviteTemplate.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 `<!DOCTYPE html> | ||
| <html lang="en"> | ||
| <head> | ||
| <meta charset="UTF-8"> | ||
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | ||
| <title>${EMAIL_SUBJECT}</title> | ||
| <style> | ||
| body { margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background-color: #ffffff; } | ||
| .container { max-width: 600px; margin: 0 auto; background-color: #ffffff; } | ||
| .header-image { width: 100%; height: auto; display: block; } | ||
| .title { text-align: center; font-size: 32px; font-weight: bold; margin: 30px 0; color: #000000; } | ||
| .content-box { background-color: #EDEDED; padding: 40px; margin: 20px 0; } | ||
| .content-box p { font-size: 16px; line-height: 1.5; color: #222222; margin: 0 0 16px 0; } | ||
| .content-box a { color: #0061FE; text-decoration: none; } | ||
| .content-box a:hover { text-decoration: underline; } | ||
| .content-box ul { margin: 16px 0; padding-left: 20px; } | ||
| .content-box li { font-size: 16px; line-height: 1.6; color: #222222; margin-bottom: 12px; } | ||
| .content-box ul ul { margin-top: 8px; } | ||
| .bold { font-weight: bold; } | ||
| .button { display: inline-block; background-color: #FFC53D; color: #173a52; font-weight: 600; font-size: 16px; padding: 14px 32px; border-radius: 6px; text-decoration: none; margin: 8px 0 16px; } | ||
| .divider { height: 2px; background-color: #000000; margin: 40px 0; } | ||
| .footer-image { width: 100%; height: auto; display: block; margin-top: 20px; } | ||
| @media only screen and (max-width: 600px) { | ||
| .content-box { padding: 24px; margin: 10px; } | ||
| .title { font-size: 24px; margin: 20px 0; } | ||
| } | ||
| </style> | ||
| </head> | ||
| <body> | ||
| <div class="container"> | ||
| <img src="${HEADER_IMAGE_URL}" alt="HackDavis 2026 header" class="header-image"> | ||
| <h1 class="title">Welcome to HackDavis 2026! 🎉</h1> | ||
| <div class="content-box"> | ||
| <p>Hi ${fname},</p> | ||
| <br/> | ||
| <p>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:</p> | ||
| <p>🔹 Meeting Recording: <a href="${MEETING_RECORDING_URL}">${MEETING_RECORDING_URL}</a></p> | ||
| <p>🔹 Judging Guide: <a href="${JUDGING_GUIDE_URL}">${JUDGING_GUIDE_URL}</a></p> | ||
| <p>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.</p> | ||
| <br/> | ||
| <p class="bold">IMPORTANT NEXT STEP: Create an account on our Judging Application</p> | ||
| <p>⚠️ The Judging Application is a key prerequisite for the day of the event! Please carefully review the <a href="${INVITATION_TO_REGISTER_GUIDE_URL}">Invitation to Register</a> section of the Judging Guide before proceeding to create your account.</p> | ||
| <p>Please use the following unique invite link below to create your judge account. Do NOT share it with anyone else.</p> | ||
| <p>👉 Invite Link: <a href="${inviteLink}">${inviteLink}</a></p> | ||
| <br/> | ||
| <p class="bold">OPTIONAL: Join our Discord</p> | ||
| <p>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:</p> | ||
| <p>🔹 Get quick answers from the team</p> | ||
| <p>🔹 Stay in the loop on event updates</p> | ||
| <p>🔹 Connect with other judges & participants</p> | ||
| <p>👉 Discord Server: <a href="${DISCORD_SERVER_URL}">${DISCORD_SERVER_URL}</a></p> | ||
| <br/> | ||
| <p>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.</p> | ||
| <p>Please feel free to reach out if you have any questions or concerns. Looking forward to seeing you at the event!</p> | ||
| <br/> | ||
| <p>Thank you,</p> | ||
| <p style="margin-bottom: 0;">The HackDavis Team</p> | ||
| </div> | ||
| <div class="divider"></div> | ||
| <img src="${FOOTER_IMAGE_URL}" alt="HackDavis 2026 footer" class="footer-image"> | ||
| </div> | ||
| </body> | ||
| </html>`; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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}` }; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<BulkJudgeInviteResponse> { | ||
| // 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<string>( | ||
| existingUsers.ok | ||
| ? existingUsers.body.map((u: { email: string }) => u.email) | ||
| : [] | ||
michelleyeoh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ); | ||
|
|
||
| // 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, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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'; | ||
michelleyeoh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| export default async function sendSingleJudgeHubInvite( | ||
| options: JudgeInviteData, | ||
| skipDuplicateCheck = false | ||
| ): Promise<SingleJudgeInviteResponse> { | ||
| 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) { | ||
michelleyeoh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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 }; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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, | ||
| }, | ||
| }); | ||
ReehalS marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| export const DEFAULT_SENDER = SENDER_EMAIL; | ||
michelleyeoh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.