From cf2caa8f0c61f5e8f85b4032bc82ab66c390667d Mon Sep 17 00:00:00 2001 From: Eric Zuo Date: Sun, 25 Oct 2026 15:48:08 -0700 Subject: [PATCH 1/7] feat(raffle): count CTF points as raffle entries --- src/lib/firebase/types.ts | 17 +++++++++ src/lib/raffle.test.ts | 75 +++++++++++++++++++++++++++++++++++++++ src/lib/raffle.ts | 44 ++++++++++++++++++----- 3 files changed, 127 insertions(+), 9 deletions(-) create mode 100644 src/lib/raffle.test.ts diff --git a/src/lib/firebase/types.ts b/src/lib/firebase/types.ts index 2f4597d..1150e92 100644 --- a/src/lib/firebase/types.ts +++ b/src/lib/firebase/types.ts @@ -772,10 +772,27 @@ export interface RaffleWinner { */ export interface RaffleSettings { eligibleStampIds: string[]; + /** when true, each CTF point a hacker earned is one more raffle entry */ + includeCtfPoints?: boolean; lastModified?: Timestamp; lastModifiedBy?: string; } +/** + * Sub-collection: /Hackathons/[hackathon]/CtfSolves, doc ID `{uid}_{challengeId}` + * + * One hacker's solve of one CTF challenge, written only by the portal's submitCtfFlag function + */ +export interface CtfSolve { + uid: string; + email: string; + challengeId: string; + rank: number; + points: number; + flagHash: string; + solvedAt?: Timestamp; +} + /** * Derived, never stored: one hacker in the raffle pool, built by `buildRaffleEntrants` */ diff --git a/src/lib/raffle.test.ts b/src/lib/raffle.test.ts new file mode 100644 index 0000000..4dc64bb --- /dev/null +++ b/src/lib/raffle.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vitest"; +import { buildRaffleEntrants, sumCtfPointsByEmail, totalEntries } from "./raffle"; + +const names = new Map([ + ["alice@example.com", { preferredName: "Alice", lastName: "Applicant" }], + ["carol@example.com", { preferredName: "Carol", lastName: "Coder" }], +]); + +describe("buildRaffleEntrants", () => { + it("counts one entry per stamp, merged by lowercased email", () => { + const entrants = buildRaffleEntrants( + [ + { email: "Alice@Example.com", displayName: "Al" }, + { email: "alice@example.com", displayName: "Al" }, + { email: "bob@example.com", displayName: "User" }, + ], + names, + ); + + expect(entrants).toEqual([ + { email: "alice@example.com", preferredName: "Al", lastName: "Applicant", entries: 2 }, + { email: "bob@example.com", preferredName: "User", lastName: "", entries: 1 }, + ]); + }); + + it("adds CTF points to stamp entries for the same hacker", () => { + const entrants = buildRaffleEntrants( + [{ email: "alice@example.com", displayName: "Al" }], + names, + new Map([["ALICE@example.com", 10]]), + ); + + expect(entrants).toEqual([ + { email: "alice@example.com", preferredName: "Al", lastName: "Applicant", entries: 11 }, + ]); + }); + + it("adds hackers who only have CTF points, named from their application", () => { + const entrants = buildRaffleEntrants([], names, new Map([["carol@example.com", 7]])); + + expect(entrants).toEqual([ + { email: "carol@example.com", preferredName: "Carol", lastName: "Coder", entries: 7 }, + ]); + }); + + it("ignores zero points and blank emails", () => { + const entrants = buildRaffleEntrants( + [{ email: " ", displayName: "Nobody" }], + names, + new Map([ + ["carol@example.com", 0], + ["", 5], + ]), + ); + + expect(entrants).toEqual([]); + expect(totalEntries(entrants)).toBe(0); + }); +}); + +describe("sumCtfPointsByEmail", () => { + it("sums each hacker's solves by lowercased, trimmed email", () => { + const points = sumCtfPointsByEmail([ + { email: "Alice@example.com ", points: 10 }, + { email: "alice@example.com", points: 1 }, + { email: "bob@example.com", points: 2 }, + { email: "", points: 5 }, + ]); + + expect([...points.entries()]).toEqual([ + ["alice@example.com", 11], + ["bob@example.com", 2], + ]); + }); +}); diff --git a/src/lib/raffle.ts b/src/lib/raffle.ts index 801a30a..39385f0 100644 --- a/src/lib/raffle.ts +++ b/src/lib/raffle.ts @@ -1,4 +1,5 @@ import type { + CtfSolve, HackerStampEntry, RaffleEntrant, RafflePrize, @@ -14,29 +15,32 @@ export interface ApplicantName { } /** - * Aggregates collected stamps into one entrant per hacker, where each stamp is one raffle entry + * Aggregates collected stamps and CTF points into one entrant per hacker, where each stamp and + * each CTF point is one raffle entry * @param stampEntries - one element per stamp collected, as returned by `fetchHackersWithStamps` * @param applicantNames - lowercased email to applicant name fields, used to recover last names + * @param ctfPoints - email to CTF points, from `sumCtfPointsByEmail`; empty when CTF points don't count * @returns the raffle pool, one entrant per hacker */ export const buildRaffleEntrants = ( stampEntries: StampEntry[], applicantNames: Map, + ctfPoints: Map = new Map(), ): RaffleEntrant[] => { const entrants = new Map(); - for (const entry of stampEntries) { - const email = entry.email.trim().toLowerCase(); - if (!email) continue; + const addEntries = (rawEmail: string, displayName: string | undefined, count: number) => { + const email = rawEmail.trim().toLowerCase(); + if (!email || count <= 0) return; const existing = entrants.get(email); if (existing) { - existing.entries += 1; - continue; + existing.entries += count; + return; } const applicant = applicantNames.get(email); - const socialsName = entry.displayName?.trim(); + const socialsName = displayName?.trim(); const preferredName = socialsName && socialsName !== SOCIALS_NAME_FALLBACK ? socialsName @@ -46,13 +50,35 @@ export const buildRaffleEntrants = ( email, preferredName, lastName: applicant?.lastName ?? "", - entries: 1, + entries: count, }); - } + }; + + for (const entry of stampEntries) addEntries(entry.email, entry.displayName, 1); + for (const [email, points] of ctfPoints) addEntries(email, undefined, points); return [...entrants.values()]; }; +/** + * Totals each hacker's CTF points across their solves, keyed the same way as raffle entrants + * @param solves - every CtfSolves doc for the hackathon + * @returns lowercased email to total CTF points + */ +export const sumCtfPointsByEmail = ( + solves: Pick[], +): Map => { + const points = new Map(); + + for (const solve of solves) { + const email = solve.email?.trim().toLowerCase(); + if (!email) continue; + points.set(email, (points.get(email) ?? 0) + solve.points); + } + + return points; +}; + /** * Sums every entrant's entries across the pool */ From 8a1305656e54fb9b217c108c144170b7ea77e16e Mon Sep 17 00:00:00 2001 From: Eric Zuo Date: Sun, 25 Oct 2026 15:51:03 -0700 Subject: [PATCH 2/7] feat(raffle): add Include CTF points setting to the raffle draw --- .../features/raffle/raffle-stamps-dialog.tsx | 25 ++++++- src/routes/_auth/stampbook/raffle.tsx | 67 +++++++++++-------- src/services/raffle.ts | 42 ++++++++++-- 3 files changed, 96 insertions(+), 38 deletions(-) diff --git a/src/components/features/raffle/raffle-stamps-dialog.tsx b/src/components/features/raffle/raffle-stamps-dialog.tsx index 855c563..0860452 100644 --- a/src/components/features/raffle/raffle-stamps-dialog.tsx +++ b/src/components/features/raffle/raffle-stamps-dialog.tsx @@ -7,6 +7,8 @@ import { DialogHeader, DialogTitle, } from "@/components/ui/dialog"; +import { Label } from "@/components/ui/label"; +import { Switch } from "@/components/ui/switch"; import type { Stamp } from "@/lib/firebase/types"; import { saveRaffleSettings } from "@/services/raffle"; import { Loader2 } from "lucide-react"; @@ -19,6 +21,7 @@ interface RaffleStampsDialogProps { hackathon: string; stamps: Stamp[]; eligibleStampIds: string[]; + includeCtfPoints: boolean; } export function RaffleStampsDialog({ @@ -27,14 +30,18 @@ export function RaffleStampsDialog({ hackathon, stamps, eligibleStampIds, + includeCtfPoints, }: RaffleStampsDialogProps) { const [draftStampIds, setDraftStampIds] = useState(null); + const [draftIncludeCtf, setDraftIncludeCtf] = useState(null); const [loading, setLoading] = useState(false); const selectedStampIds = draftStampIds ?? eligibleStampIds; + const selectedIncludeCtf = draftIncludeCtf ?? includeCtfPoints; const handleClose = () => { setDraftStampIds(null); + setDraftIncludeCtf(null); onClose(); }; @@ -42,9 +49,9 @@ export function RaffleStampsDialog({ if (loading) return; setLoading(true); try { - await saveRaffleSettings(hackathon, selectedStampIds); + await saveRaffleSettings(hackathon, selectedStampIds, selectedIncludeCtf); toast.success( - `${selectedStampIds.length} stamp${selectedStampIds.length === 1 ? "" : "s"} count as entries`, + `${selectedStampIds.length} stamp${selectedStampIds.length === 1 ? "" : "s"} count as entries${selectedIncludeCtf ? ", plus CTF points" : ""}`, ); handleClose(); } catch (error) { @@ -76,6 +83,20 @@ export function RaffleStampsDialog({ label={`Stamps for ${hackathon}`} /> +
+
+ +

+ Each CTF point a hacker earned counts as one more entry. +

+
+ +
+ - - - - ); -} diff --git a/src/components/features/stampbook/export-raffle-dialog.tsx b/src/components/features/stampbook/export-raffle-dialog.tsx index e78806c..8deb221 100644 --- a/src/components/features/stampbook/export-raffle-dialog.tsx +++ b/src/components/features/stampbook/export-raffle-dialog.tsx @@ -72,12 +72,12 @@ export function ExportRaffleDialog({ open, onClose, stamps }: ExportRaffleDialog } const csvContent = generateRaffleCSV(raffleEntries); - const filename = `raffle-${selectedHackathon}-${new Date().toISOString().split("T")[0]}.csv`; + const filename = `stamp-holders-${selectedHackathon}-${new Date().toISOString().split("T")[0]}.csv`; downloadCSV(csvContent, filename); - toast.success(`Exported ${raffleEntries.length} raffle entries`); + toast.success(`Exported ${raffleEntries.length} stamp holder rows`); } catch (error) { - console.error("Error exporting raffle:", error); - toast.error("Failed to export raffle data"); + console.error("Error exporting stamp holders:", error); + toast.error("Failed to export stamp holders"); } finally { setLoading(false); } @@ -96,10 +96,11 @@ export function ExportRaffleDialog({ open, onClose, stamps }: ExportRaffleDialog aria-describedby="raffle-export-description" > - Export Raffle + Export stamp holders - Export a CSV of obfuscated emails for raffles. Outputs a list of name + emails, where - duplicate entries correlate to number of stamps collected by a hacker. + Export a CSV of obfuscated emails with one row per collected stamp, so a hacker appears + once for each selected stamp they hold. This is not the raffle pool, which is based on + points. @@ -140,7 +141,7 @@ export function ExportRaffleDialog({ open, onClose, stamps }: ExportRaffleDialog ) : ( )} - Export Raffle CSV + Export stamp holders CSV diff --git a/src/routes/_auth/stampbook/index.tsx b/src/routes/_auth/stampbook/index.tsx index 8e432e6..d724c1d 100644 --- a/src/routes/_auth/stampbook/index.tsx +++ b/src/routes/_auth/stampbook/index.tsx @@ -34,7 +34,7 @@ function StampbookPage() {
-
{disabledReason &&

{disabledReason}

} diff --git a/src/lib/firebase/types.ts b/src/lib/firebase/types.ts index 0e96412..70c1e88 100644 --- a/src/lib/firebase/types.ts +++ b/src/lib/firebase/types.ts @@ -767,19 +767,6 @@ export interface RaffleWinner { drawnBy?: string; } -/** - * Document: /Hackathons/[hackathon]/Raffle/settings - * - * Which stamps count as raffle entries for this hackathon - */ -export interface RaffleSettings { - eligibleStampIds: string[]; - /** when true, each CTF point a hacker earned is one more raffle entry */ - includeCtfPoints?: boolean; - lastModified?: Timestamp; - lastModifiedBy?: string; -} - /** * Sub-collection: /Hackathons/[hackathon]/CtfSolves, doc ID `{uid}_{challengeId}` * diff --git a/src/lib/raffle.test.ts b/src/lib/raffle.test.ts index 4dc64bb..ec91891 100644 --- a/src/lib/raffle.test.ts +++ b/src/lib/raffle.test.ts @@ -1,54 +1,110 @@ import { describe, expect, it } from "vitest"; -import { buildRaffleEntrants, sumCtfPointsByEmail, totalEntries } from "./raffle"; +import { buildRaffleEntrants, stampPointsById, sumCtfPointsByEmail, totalEntries } from "./raffle"; const names = new Map([ ["alice@example.com", { preferredName: "Alice", lastName: "Applicant" }], ["carol@example.com", { preferredName: "Carol", lastName: "Coder" }], ]); +const stamps = [ + { _id: "s1", points: 3 }, + { _id: "s2" }, + { _id: "zero", points: 0 }, + { _id: "s5", points: 5 }, +]; +const values = stampPointsById(stamps); + +describe("stampPointsById", () => { + it("maps stamp IDs to their point values, defaulting to 1", () => { + expect([...values.entries()]).toEqual([ + ["s1", 3], + ["s2", 1], + ["zero", 0], + ["s5", 5], + ]); + }); + + it("leaves out stamps without an ID", () => { + expect(stampPointsById([{ points: 4 }]).size).toBe(0); + }); +}); + describe("buildRaffleEntrants", () => { - it("counts one entry per stamp, merged by lowercased email", () => { + it("counts each stamp for its point value, merged by lowercased email", () => { + const entrants = buildRaffleEntrants( + [ + { email: "Alice@Example.com", displayName: "Al", stampId: "s1" }, + { email: "alice@example.com", displayName: "Al", stampId: "s2" }, + { email: "bob@example.com", displayName: "User", stampId: "s5" }, + ], + values, + names, + ); + + expect(entrants).toEqual([ + { email: "alice@example.com", preferredName: "Al", lastName: "Applicant", entries: 4 }, + { email: "bob@example.com", preferredName: "User", lastName: "", entries: 5 }, + ]); + }); + + it("counts a repeated stamp once", () => { + const entrants = buildRaffleEntrants( + [ + { email: "bob@example.com", displayName: "Bo", stampId: "s5" }, + { email: "bob@example.com", displayName: "Bo", stampId: "s5" }, + ], + values, + names, + ); + + expect(entrants.map((entrant) => entrant.entries)).toEqual([5]); + }); + + it("leaves out 0-point stamps, deleted stamps and hackers left with 0 points", () => { const entrants = buildRaffleEntrants( [ - { email: "Alice@Example.com", displayName: "Al" }, - { email: "alice@example.com", displayName: "Al" }, - { email: "bob@example.com", displayName: "User" }, + { email: "bob@example.com", displayName: "Bo", stampId: "zero" }, + { email: "bob@example.com", displayName: "Bo", stampId: "deleted" }, + { email: "alice@example.com", displayName: "Al", stampId: "s2" }, ], + values, names, ); expect(entrants).toEqual([ - { email: "alice@example.com", preferredName: "Al", lastName: "Applicant", entries: 2 }, - { email: "bob@example.com", preferredName: "User", lastName: "", entries: 1 }, + { email: "alice@example.com", preferredName: "Al", lastName: "Applicant", entries: 1 }, ]); }); - it("adds CTF points to stamp entries for the same hacker", () => { + it("adds CTF points to stamp points for the same hacker", () => { const entrants = buildRaffleEntrants( - [{ email: "alice@example.com", displayName: "Al" }], + [{ email: "alice@example.com", displayName: "Al", stampId: "s1" }], + values, names, new Map([["ALICE@example.com", 10]]), ); expect(entrants).toEqual([ - { email: "alice@example.com", preferredName: "Al", lastName: "Applicant", entries: 11 }, + { email: "alice@example.com", preferredName: "Al", lastName: "Applicant", entries: 13 }, ]); }); it("adds hackers who only have CTF points, named from their application", () => { - const entrants = buildRaffleEntrants([], names, new Map([["carol@example.com", 7]])); + const entrants = buildRaffleEntrants([], values, names, new Map([["carol@example.com", 7]])); expect(entrants).toEqual([ { email: "carol@example.com", preferredName: "Carol", lastName: "Coder", entries: 7 }, ]); }); - it("ignores zero points and blank emails", () => { + it("ignores zero or non-finite CTF points and blank emails", () => { const entrants = buildRaffleEntrants( - [{ email: " ", displayName: "Nobody" }], + [{ email: " ", displayName: "Nobody", stampId: "s1" }], + values, names, new Map([ ["carol@example.com", 0], + ["dave@example.com", Number.NaN], ["", 5], ]), ); @@ -65,6 +121,9 @@ describe("sumCtfPointsByEmail", () => { { email: "alice@example.com", points: 1 }, { email: "bob@example.com", points: 2 }, { email: "", points: 5 }, + { email: "bob@example.com", points: Number.NaN }, + { email: "bob@example.com", points: "7" as unknown as number }, + { email: "carol@example.com", points: Number.POSITIVE_INFINITY }, ]); expect([...points.entries()]).toEqual([ diff --git a/src/lib/raffle.ts b/src/lib/raffle.ts index 39385f0..246bdb5 100644 --- a/src/lib/raffle.ts +++ b/src/lib/raffle.ts @@ -4,10 +4,12 @@ import type { RaffleEntrant, RafflePrize, RaffleWinner, + Stamp, } from "@/lib/firebase/types"; +import { stampPointValue } from "@/lib/points"; import { SOCIALS_NAME_FALLBACK } from "@/lib/stamps"; -export type StampEntry = Pick; +export type StampEntry = Pick; export interface ApplicantName { preferredName?: string; @@ -15,15 +17,30 @@ export interface ApplicantName { } /** - * Aggregates collected stamps and CTF points into one entrant per hacker, where each stamp and - * each CTF point is one raffle entry + * Looks up each stamp's point value by ID, whatever hackathon the stamp belongs to + * @param stamps - every stamp, unfiltered + * @returns stamp ID to point value; a stamp ID missing from the map (deleted) is worth 0 + */ +export const stampPointsById = (stamps: Pick[]): Map => { + const values = new Map(); + for (const stamp of stamps) { + if (stamp._id) values.set(stamp._id, stampPointValue(stamp)); + } + return values; +}; + +/** + * Aggregates collected stamps and CTF points into one entrant per hacker, where each point is + * one raffle entry * @param stampEntries - one element per stamp collected, as returned by `fetchHackersWithStamps` + * @param stampPoints - stamp ID to point value, from `stampPointsById`; unknown stamps count 0 * @param applicantNames - lowercased email to applicant name fields, used to recover last names - * @param ctfPoints - email to CTF points, from `sumCtfPointsByEmail`; empty when CTF points don't count - * @returns the raffle pool, one entrant per hacker + * @param ctfPoints - email to CTF points, from `sumCtfPointsByEmail` + * @returns the raffle pool, one entrant per hacker with at least one point */ export const buildRaffleEntrants = ( stampEntries: StampEntry[], + stampPoints: Map, applicantNames: Map, ctfPoints: Map = new Map(), ): RaffleEntrant[] => { @@ -31,7 +48,7 @@ export const buildRaffleEntrants = ( const addEntries = (rawEmail: string, displayName: string | undefined, count: number) => { const email = rawEmail.trim().toLowerCase(); - if (!email || count <= 0) return; + if (!email || !Number.isFinite(count) || count <= 0) return; const existing = entrants.get(email); if (existing) { @@ -54,7 +71,14 @@ export const buildRaffleEntrants = ( }); }; - for (const entry of stampEntries) addEntries(entry.email, entry.displayName, 1); + // a stamp counts once per hacker, however many times it appears + const counted = new Set(); + for (const entry of stampEntries) { + const key = `${entry.email.trim().toLowerCase()}\u0000${entry.stampId}`; + if (counted.has(key)) continue; + counted.add(key); + addEntries(entry.email, entry.displayName, stampPoints.get(entry.stampId) ?? 0); + } for (const [email, points] of ctfPoints) addEntries(email, undefined, points); return [...entrants.values()]; @@ -73,6 +97,7 @@ export const sumCtfPointsByEmail = ( for (const solve of solves) { const email = solve.email?.trim().toLowerCase(); if (!email) continue; + if (typeof solve.points !== "number" || !Number.isFinite(solve.points)) continue; points.set(email, (points.get(email) ?? 0) + solve.points); } @@ -86,7 +111,7 @@ export const totalEntries = (entrants: RaffleEntrant[]): number => entrants.reduce((sum, entrant) => sum + entrant.entries, 0); /** - * Draws one winner, weighted so that a hacker with N stamps is N times as likely to win + * Draws one winner, weighted so that a hacker with N points is N times as likely to win * @param entrants - the raffle pool * @returns the drawn entrant, or null when the pool has no entries */ diff --git a/src/routes/_auth/stampbook/raffle.tsx b/src/routes/_auth/stampbook/raffle.tsx index d059a74..6de36fe 100644 --- a/src/routes/_auth/stampbook/raffle.tsx +++ b/src/routes/_auth/stampbook/raffle.tsx @@ -1,6 +1,5 @@ import { RaffleDrawPanel } from "@/components/features/raffle/raffle-draw-panel"; import { RafflePrizesCard } from "@/components/features/raffle/raffle-prizes-card"; -import { RaffleStampsDialog } from "@/components/features/raffle/raffle-stamps-dialog"; import { RaffleWinnersLog } from "@/components/features/raffle/raffle-winners-log"; import { PageHeader } from "@/components/graphy/typo"; import { Button } from "@/components/ui/button"; @@ -12,21 +11,13 @@ import { SelectValue, } from "@/components/ui/select"; import { subscribeToHackathons } from "@/lib/firebase/firestore"; -import type { - Hackathon, - RaffleEntrant, - RafflePrize, - RaffleWinner, - Stamp, -} from "@/lib/firebase/types"; +import type { Hackathon, RaffleEntrant, RafflePrize, RaffleWinner } from "@/lib/firebase/types"; import { splitHackathon } from "@/lib/utils"; import { fetchRaffleEntrants, subscribeToRafflePrizes, - subscribeToRaffleSettings, subscribeToRaffleWinners, } from "@/services/raffle"; -import { subscribeToStamps } from "@/services/stamps"; import { Link, createFileRoute } from "@tanstack/react-router"; import { ArrowLeft } from "lucide-react"; import { useCallback, useEffect, useRef, useState } from "react"; @@ -41,22 +32,16 @@ const hackathonYear = (id: string) => Number(splitHackathon(id)[1] ?? 0); const newestHackathonId = (hackathons: Hackathon[]) => [...hackathons].sort((a, b) => hackathonYear(b._id) - hackathonYear(a._id))[0]?._id ?? ""; -const sameStampIds = (current: string[], next: string[]) => - current.length === next.length && current.every((id, index) => id === next[index]); - function RafflePage() { const [hackathons, setHackathons] = useState([]); const [selectedHackathon, setSelectedHackathon] = useState(""); - const [stamps, setStamps] = useState([]); const [prizes, setPrizes] = useState([]); const [winners, setWinners] = useState([]); - const [eligibleStampIds, setEligibleStampIds] = useState([]); - const [includeCtfPoints, setIncludeCtfPoints] = useState(false); const [entrants, setEntrants] = useState([]); const [poolLoading, setPoolLoading] = useState(false); + const [poolError, setPoolError] = useState(false); const [poolFetchedAt, setPoolFetchedAt] = useState(null); const [showEmails, setShowEmails] = useState(false); - const [stampsOpen, setStampsOpen] = useState(false); const requestRef = useRef(0); useEffect(() => { @@ -64,18 +49,14 @@ function RafflePage() { setHackathons(docs); setSelectedHackathon((current) => current || newestHackathonId(docs)); }); - const unsubStamps = subscribeToStamps(setStamps); - return () => { - unsubHackathons(); - unsubStamps(); - }; + return unsubHackathons; }, []); useEffect(() => { if (!selectedHackathon) return; - // share one toast id so three failing subscriptions don't stack three toasts + // share one toast id so two failing subscriptions don't stack two toasts const onError = () => toast.error("Couldn't load the raffle, you may not have access to this hackathon", { id: "raffle-subscription-error", @@ -83,55 +64,47 @@ function RafflePage() { const unsubPrizes = subscribeToRafflePrizes(selectedHackathon, setPrizes, onError); const unsubWinners = subscribeToRaffleWinners(selectedHackathon, setWinners, onError); - const unsubSettings = subscribeToRaffleSettings( - selectedHackathon, - (settings) => { - setEligibleStampIds((current) => - sameStampIds(current, settings.eligibleStampIds) ? current : settings.eligibleStampIds, - ); - setIncludeCtfPoints(settings.includeCtfPoints ?? false); - }, - onError, - ); return () => { unsubPrizes(); unsubWinners(); - unsubSettings(); }; }, [selectedHackathon]); - const loadPool = useCallback( - async (hackathon: string, stampIds: string[], includeCtf: boolean, refresh = false) => { - if (!hackathon) { - setEntrants([]); - setPoolFetchedAt(null); - return; - } - - const requestId = requestRef.current + 1; - requestRef.current = requestId; - setPoolLoading(true); - - try { - const pool = await fetchRaffleEntrants(hackathon, stampIds, includeCtf, refresh); - if (requestId !== requestRef.current) return; - setEntrants(pool); - setPoolFetchedAt(new Date()); - } catch (error) { - if (requestId !== requestRef.current) return; - console.error("Error loading the raffle pool:", error); - toast.error("Failed to load raffle entries"); - } finally { - if (requestId === requestRef.current) setPoolLoading(false); - } - }, - [], - ); + const loadPool = useCallback(async (hackathon: string, refresh = false) => { + if (!hackathon) { + setEntrants([]); + setPoolError(false); + setPoolFetchedAt(null); + return; + } + + const requestId = requestRef.current + 1; + requestRef.current = requestId; + setPoolLoading(true); + setPoolError(false); + + try { + const pool = await fetchRaffleEntrants(hackathon, refresh); + if (requestId !== requestRef.current) return; + setEntrants(pool); + setPoolFetchedAt(new Date()); + } catch (error) { + if (requestId !== requestRef.current) return; + console.error("Error loading the raffle pool:", error); + // a stale pool must never be drawn from after a failed load + setEntrants([]); + setPoolFetchedAt(null); + setPoolError(true); + toast.error("Failed to load raffle entries"); + } finally { + if (requestId === requestRef.current) setPoolLoading(false); + } + }, []); useEffect(() => { - loadPool(selectedHackathon, eligibleStampIds, includeCtfPoints); - }, [loadPool, selectedHackathon, eligibleStampIds, includeCtfPoints]); + loadPool(selectedHackathon); + }, [loadPool, selectedHackathon]); return ( <> @@ -177,13 +150,10 @@ function RafflePage() { prizes={prizes} winners={winners} entrants={entrants} - eligibleStampCount={eligibleStampIds.length} poolLoading={poolLoading} + poolError={poolError} poolFetchedAt={poolFetchedAt} - onRefreshPool={() => - loadPool(selectedHackathon, eligibleStampIds, includeCtfPoints, true) - } - onManageStamps={() => setStampsOpen(true)} + onRefreshPool={() => loadPool(selectedHackathon, true)} className="lg:w-[482px]" /> @@ -195,17 +165,6 @@ function RafflePage() { onToggleEmails={setShowEmails} /> - - {selectedHackathon && ( - setStampsOpen(false)} - hackathon={selectedHackathon} - stamps={stamps} - eligibleStampIds={eligibleStampIds} - includeCtfPoints={includeCtfPoints} - /> - )} ); } diff --git a/src/services/raffle.ts b/src/services/raffle.ts index 1c26eb7..a87cad7 100644 --- a/src/services/raffle.ts +++ b/src/services/raffle.ts @@ -4,11 +4,15 @@ import type { CtfSolve, RaffleEntrant, RafflePrize, - RaffleSettings, RaffleWinner, } from "@/lib/firebase/types"; -import { type ApplicantName, buildRaffleEntrants, sumCtfPointsByEmail } from "@/lib/raffle"; -import { fetchHackersWithStamps } from "@/services/stamps"; +import { + type ApplicantName, + buildRaffleEntrants, + stampPointsById, + sumCtfPointsByEmail, +} from "@/lib/raffle"; +import { fetchHackersWithStamps, fetchStamps } from "@/services/stamps"; import { type DocumentReference, type FirestoreError, @@ -197,64 +201,6 @@ export const deleteRaffleWinner = async (hackathon: string, id: string) => { } }; -/** - * Utility function that returns a hackathon's raffle settings as realtime data - * @param hackathon - hackathon ID - * @param callback - the function used to ingest the data - * @param onError - called when the subscription fails, so an unreadable settings document is - * not mistaken for a raffle with no eligible stamps chosen - * @returns a function to be called on dismount - */ -export const subscribeToRaffleSettings = ( - hackathon: string, - callback: (settings: RaffleSettings) => void, - onError?: (error: FirestoreError) => void, -) => - onSnapshot( - doc(db, "Hackathons", hackathon, "Raffle", "settings"), - (docSnapshot) => { - const data = docSnapshot.data() as unknown as RaffleSettings | undefined; - callback({ - ...data, - eligibleStampIds: data?.eligibleStampIds ?? [], - includeCtfPoints: data?.includeCtfPoints ?? false, - }); - }, - (error) => { - console.error("Error fetching raffle settings:", error); - callback({ eligibleStampIds: [], includeCtfPoints: false }); - onError?.(error); - }, - ); - -/** - * Saves which stamps count as raffle entries for a hackathon, and whether CTF points do too - * @param hackathon - hackathon ID - * @param eligibleStampIds - the IDs of the stamps that count as entries - * @param includeCtfPoints - whether each CTF point counts as one more entry - */ -export const saveRaffleSettings = async ( - hackathon: string, - eligibleStampIds: string[], - includeCtfPoints: boolean, -) => { - try { - await setDoc( - doc(db, "Hackathons", hackathon, "Raffle", "settings"), - { - eligibleStampIds, - includeCtfPoints, - lastModified: Timestamp.now(), - lastModifiedBy: auth.currentUser?.email ?? "", - }, - { merge: true }, - ); - } catch (error) { - console.error("Error saving raffle settings:", error); - throw error; - } -}; - // applicant names rarely change mid-event, so they are cached for the page lifetime const applicantNameCache = new Map>(); @@ -300,34 +246,22 @@ export const fetchCtfPointsByEmail = async (hackathon: string): Promise => { - if (eligibleStampIds.length === 0) return []; - - const [stampEntries, applicantNames, ctfPoints] = await Promise.all([ + const [stampEntries, stamps, applicantNames, ctfPoints] = await Promise.all([ fetchHackersWithStamps(hackathon), + fetchStamps(), fetchApplicantNames(hackathon, refreshNames), - includeCtfPoints - ? fetchCtfPointsByEmail(hackathon) - : Promise.resolve(new Map()), + fetchCtfPointsByEmail(hackathon), ]); - const eligible = new Set(eligibleStampIds); - return buildRaffleEntrants( - stampEntries.filter((entry) => eligible.has(entry.stampId)), - applicantNames, - ctfPoints, - ); + return buildRaffleEntrants(stampEntries, stampPointsById(stamps), applicantNames, ctfPoints); }; diff --git a/src/services/stamps.ts b/src/services/stamps.ts index c629e09..09c11eb 100644 --- a/src/services/stamps.ts +++ b/src/services/stamps.ts @@ -40,6 +40,15 @@ export const subscribeToStamps = (callback: (docs: Stamp[]) => void) => callback(stamps); }); +/** + * Reads every stamp once, unfiltered, for point values + * @returns every stamp with its document ID + */ +export const fetchStamps = async (): Promise => { + const snapshot = await getDocs(collection(db, "Stamps")); + return snapshot.docs.map((stampDoc) => ({ ...(stampDoc.data() as Stamp), _id: stampDoc.id })); +}; + /** * Utility function that updates or adds a stamp document, depending on if an id argument is passed * @param stamp - the stamp to upsert @@ -133,7 +142,7 @@ export const deleteStampQR = async (stampId: string) => { /** * Fetches all hackers with unlocked stamps from the Socials collection - * Each stamp a user has unlocked creates one entry + * Each stamp a user has unlocked creates one entry, which the raffle weights by point value * * @param hackathonId - hackathon ID whose stamps should be counted * @returns Array of entries where each entry represents one stamp collected by a hacker From e53f382e52760dc037a19e5fe7dc5ed81f13613c Mon Sep 17 00:00:00 2001 From: Daksh Shahani Date: Fri, 30 Oct 2026 14:30:12 -0700 Subject: [PATCH 6/7] fix(stampbook): regenerate stamp qr when hackathon changes --- .../features/stampbook/stamp-dialog.tsx | 6 +- src/lib/stamps.test.ts | 55 +++++++++++++++++++ src/lib/stamps.ts | 22 ++++++++ 3 files changed, 81 insertions(+), 2 deletions(-) create mode 100644 src/lib/stamps.test.ts diff --git a/src/components/features/stampbook/stamp-dialog.tsx b/src/components/features/stampbook/stamp-dialog.tsx index 0b66486..66575c2 100644 --- a/src/components/features/stampbook/stamp-dialog.tsx +++ b/src/components/features/stampbook/stamp-dialog.tsx @@ -23,6 +23,7 @@ import { Switch } from "@/components/ui/switch"; import { Textarea } from "@/components/ui/textarea"; import { subscribeToHackathons } from "@/lib/firebase/firestore"; import type { FilterRowsSelection, Hackathon, Stamp } from "@/lib/firebase/types"; +import { needsStampQrRegeneration } from "@/lib/stamps"; import { getHackathonType } from "@/lib/utils"; import { deleteStampQR, deleteStampWithImage, upsertStampWithImage } from "@/services/stamps"; import { zodResolver } from "@hookform/resolvers/zod"; @@ -232,11 +233,12 @@ export function StampDialog({ open, activeStamp, onClose }: StampDialogProps) { stampData.criteria = criteria; } - // Generate QR blob if isQRUnlockable is being enabled for the first time + // Generate QR blob if isQRUnlockable is being enabled for the first time, + // the stamp is moving to a hackathon with a different portal slug, // else delete QR if isQRUnlockable is being disabled and a QR exists let qrBlob: Blob | null = null; const stampId = activeStamp?._id; - const needsNewQR = values.isQRUnlockable && (!activeStamp || !activeStamp.isQRUnlockable); + const needsNewQR = needsStampQrRegeneration(activeStamp, values); const needsQRDeletion = !values.isQRUnlockable && activeStamp?.isQRUnlockable && activeStamp?.qrURL; diff --git a/src/lib/stamps.test.ts b/src/lib/stamps.test.ts new file mode 100644 index 0000000..15d129a --- /dev/null +++ b/src/lib/stamps.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from "vitest"; +import { needsStampQrRegeneration } from "./stamps"; + +describe("needsStampQrRegeneration", () => { + it("generates a QR when enabling QR unlocking for the first time", () => { + expect( + needsStampQrRegeneration(null, { hackathon: "HackCamp2026", isQRUnlockable: true }), + ).toBe(true); + expect( + needsStampQrRegeneration( + { hackathon: "HackCamp2026", isQRUnlockable: false }, + { hackathon: "HackCamp2026", isQRUnlockable: true }, + ), + ).toBe(true); + }); + + it("does not regenerate a QR when nothing relevant changed", () => { + expect( + needsStampQrRegeneration( + { hackathon: "HackCamp2026", isQRUnlockable: true }, + { hackathon: "HackCamp2026", isQRUnlockable: true }, + ), + ).toBe(false); + expect( + needsStampQrRegeneration( + { hackathon: "HackCamp2025", isQRUnlockable: true }, + { hackathon: "HackCamp2026", isQRUnlockable: true }, + ), + ).toBe(false); + }); + + it("regenerates a QR when the stamp moves to a hackathon with a different slug", () => { + expect( + needsStampQrRegeneration( + { hackathon: "nwHacks2026", isQRUnlockable: true }, + { hackathon: "HackCamp2026", isQRUnlockable: true }, + ), + ).toBe(true); + expect( + needsStampQrRegeneration( + { hackathon: undefined, isQRUnlockable: true }, + { hackathon: "HackCamp2026", isQRUnlockable: true }, + ), + ).toBe(true); + }); + + it("does not generate a QR when QR unlocking is off", () => { + expect( + needsStampQrRegeneration( + { hackathon: "nwHacks2026", isQRUnlockable: true }, + { hackathon: "HackCamp2026", isQRUnlockable: false }, + ), + ).toBe(false); + }); +}); diff --git a/src/lib/stamps.ts b/src/lib/stamps.ts index 1f452b0..a083af9 100644 --- a/src/lib/stamps.ts +++ b/src/lib/stamps.ts @@ -1,7 +1,29 @@ +import type { Stamp } from "@/lib/firebase/types"; import { getHackathonType } from "@/lib/utils"; export const SOCIALS_NAME_FALLBACK = "User"; +/** + * Whether a stamp's QR image has to be regenerated + * + * The QR encodes `.../{hackathonSlug}/stampbook?unlockStamp={stampId}`, so moving a + * stamp to a hackathon with a different portal slug (for example reusing an nwHacks + * stamp for HackCamp) invalidates the QR already in storage. + * + * @param activeStamp - the stamp being edited, if any + * @param values - the submitted form values + * @returns true when a new QR image should be generated + */ +export const needsStampQrRegeneration = ( + activeStamp: Pick | null | undefined, + values: Pick, +): boolean => { + if (!values.isQRUnlockable) return false; + if (!activeStamp?.isQRUnlockable) return true; + + return getHackathonType(activeStamp.hackathon ?? "") !== getHackathonType(values.hackathon ?? ""); +}; + /** * Reads the stamp IDs one Socials document has unlocked for a hackathon * From 82909fa8a38f3463c1df881ae4b08f0c933776e0 Mon Sep 17 00:00:00 2001 From: Eric Zuo Date: Fri, 30 Oct 2026 17:32:33 -0700 Subject: [PATCH 7/7] feat(settings): add a CTF Open toggle to hackathon settings --- .../settings/hackathon-settings-form.test.tsx | 64 +++++++++++++++++++ .../settings/hackathon-settings-form.tsx | 18 +++++- src/lib/firebase/types.ts | 1 + 3 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 src/components/features/settings/hackathon-settings-form.test.tsx diff --git a/src/components/features/settings/hackathon-settings-form.test.tsx b/src/components/features/settings/hackathon-settings-form.test.tsx new file mode 100644 index 0000000..ceec41d --- /dev/null +++ b/src/components/features/settings/hackathon-settings-form.test.tsx @@ -0,0 +1,64 @@ +import type { HackathonConfig } from "@/lib/firebase/types"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { HackathonSettingsForm } from "./hackathon-settings-form"; + +const settings = vi.hoisted(() => ({ + config: null as unknown as HackathonConfig, + updateHackathonConfig: vi.fn(), +})); + +vi.mock("@/services/hackathon-settings", () => ({ + subscribeToHackathonConfig: (callback: (data: HackathonConfig) => void) => { + callback(settings.config); + return () => {}; + }, + updateHackathonConfig: settings.updateHackathonConfig, +})); + +vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } })); + +const timeline = { + hackathonStart: { hackcamp: "2026-11-07T17:00:00.000Z" }, + hackathonEnd: { hackcamp: "2026-11-08T23:00:00.000Z" }, + hackingStart: { hackcamp: "2026-11-07T19:00:00.000Z" }, + hackingEnd: { hackcamp: "2026-11-08T19:00:00.000Z" }, +}; + +const toggleCtfAndSave = async () => { + render(); + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + fireEvent.click(screen.getByRole("switch", { name: "CTF Open" })); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(settings.updateHackathonConfig).toHaveBeenCalledOnce()); + return settings.updateHackathonConfig.mock.calls[0][0] as HackathonConfig; +}; + +describe("HackathonSettingsForm CTF Open", () => { + beforeEach(() => { + settings.updateHackathonConfig.mockReset(); + }); + + it("creates the ctfOpen map when the doc doesn't have one yet", async () => { + settings.config = { + ...timeline, + portalLive: { hackcamp: false }, + } as unknown as HackathonConfig; + + const saved = await toggleCtfAndSave(); + + expect(saved.ctfOpen).toEqual({ hackcamp: true }); + expect(saved.portalLive).toEqual({ hackcamp: false }); + }); + + it("only changes this hackathon's flag", async () => { + settings.config = { + ...timeline, + ctfOpen: { hackcamp: false, nwhacks: true }, + } as unknown as HackathonConfig; + + const saved = await toggleCtfAndSave(); + + expect(saved.ctfOpen).toEqual({ hackcamp: true, nwhacks: true }); + }); +}); diff --git a/src/components/features/settings/hackathon-settings-form.tsx b/src/components/features/settings/hackathon-settings-form.tsx index f04ee2a..a2303b2 100644 --- a/src/components/features/settings/hackathon-settings-form.tsx +++ b/src/components/features/settings/hackathon-settings-form.tsx @@ -133,8 +133,10 @@ export function HackathonSettingsForm({ hackathonId }: { hackathonId: string }) } const currentValue = editedConfig[field]; + // toggles are per-hackathon maps; one missing from older docs (like ctfOpen) starts as a new map const isMapField = - typeof currentValue === "object" && currentValue !== null && !Array.isArray(currentValue); + (typeof currentValue === "object" && currentValue !== null && !Array.isArray(currentValue)) || + (currentValue === undefined && typeof value === "boolean"); if (nestedField) { const hackathonValue = @@ -275,6 +277,20 @@ export function HackathonSettingsForm({ hackathonId }: { hackathonId: string }) disabled={!isEditing} /> +
+
+ +

+ Shows the CTF page to RSVP'd hackers, even before the portal is live +

+
+ handleFieldChange("ctfOpen", checked)} + disabled={!isEditing} + /> +
diff --git a/src/lib/firebase/types.ts b/src/lib/firebase/types.ts index 70c1e88..7b27756 100644 --- a/src/lib/firebase/types.ts +++ b/src/lib/firebase/types.ts @@ -680,6 +680,7 @@ export interface HackathonConfig { _id?: string; applicationDeadline: HackathonConfigMap; applicationsOpen: HackathonBooleanMap; + ctfOpen?: HackathonBooleanMap; hackathonEnd: HackathonConfigMap; hackathonStart: HackathonConfigMap; hackathonWeekend: HackathonConfigMap;