From 5b3075eef7a9c16c57a36675f629567ca6694432 Mon Sep 17 00:00:00 2001 From: naijwu Date: Sat, 7 Nov 2026 13:34:16 -0700 Subject: [PATCH 1/2] fix: raffle pool --- .../features/raffle/raffle-draw-panel.tsx | 8 ++ .../features/raffle/raffle-winner-dialog.tsx | 9 +- .../features/raffle/raffle-winners-log.tsx | 17 ++- src/lib/firebase/types.ts | 4 + src/lib/raffle.test.ts | 105 +++++++++++++++++- src/lib/raffle.ts | 101 ++++++++++++++++- src/lib/stamps.test.ts | 51 ++++++++- src/lib/stamps.ts | 52 ++++++--- src/lib/utils.test.ts | 17 +++ src/lib/utils.ts | 8 ++ src/routes/_auth/stampbook/raffle.tsx | 47 +++++--- src/services/raffle.ts | 30 +++-- src/services/stamps.ts | 19 +++- 13 files changed, 418 insertions(+), 50 deletions(-) create mode 100644 src/lib/utils.test.ts diff --git a/src/components/features/raffle/raffle-draw-panel.tsx b/src/components/features/raffle/raffle-draw-panel.tsx index 0db94f1..8ddd110 100644 --- a/src/components/features/raffle/raffle-draw-panel.tsx +++ b/src/components/features/raffle/raffle-draw-panel.tsx @@ -23,6 +23,8 @@ interface RaffleDrawPanelProps { prizes: RafflePrize[]; winners: RaffleWinner[]; entrants: RaffleEntrant[]; + /** organizer accounts that had points and were left out of `entrants` */ + excludedOrganizers: number; poolLoading: boolean; /** the last pool load failed, so `entrants` is empty and drawing is blocked */ poolError: boolean; @@ -36,6 +38,7 @@ export function RaffleDrawPanel({ prizes, winners, entrants, + excludedOrganizers, poolLoading, poolError, poolFetchedAt, @@ -133,6 +136,11 @@ export function RaffleDrawPanel({ per point )} + {excludedOrganizers > 0 && !poolLoading && !poolError && ( + + · {excludedOrganizers} organizer account{excludedOrganizers === 1 ? "" : "s"} excluded + + )} {poolFetchedAt && !poolLoading && ( · as of {poolFetchedAt.toLocaleTimeString()} )} diff --git a/src/components/features/raffle/raffle-winner-dialog.tsx b/src/components/features/raffle/raffle-winner-dialog.tsx index 53b095e..57e181f 100644 --- a/src/components/features/raffle/raffle-winner-dialog.tsx +++ b/src/components/features/raffle/raffle-winner-dialog.tsx @@ -1,7 +1,7 @@ import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogFooter, DialogTitle } from "@/components/ui/dialog"; import type { RaffleEntrant, RafflePrize, RaffleWinner } from "@/lib/firebase/types"; -import { nextPrizeSlot, pickWeightedWinner, remainingForPrize } from "@/lib/raffle"; +import { nextPrizeSlot, pickWeightedWinner, remainingForPrize, totalEntries } from "@/lib/raffle"; import { RaffleSlotTakenError, addRaffleWinner } from "@/services/raffle"; import { Check, Loader2, X } from "lucide-react"; import { useEffect, useRef, useState } from "react"; @@ -34,6 +34,10 @@ export function RaffleWinnerDialog({ const [phase, setPhase] = useState("drawing"); const [shown, setShown] = useState(null); const [winner, setWinner] = useState(null); + // the pool the winner was drawn from, logged with them so the odds can be checked later + const [drawnFrom, setDrawnFrom] = useState<{ poolSize: number; poolEntries: number } | null>( + null, + ); const [confirming, setConfirming] = useState(false); const timerRef = useRef | null>(null); @@ -55,6 +59,7 @@ export function RaffleWinnerDialog({ setWinner(null); setShown(null); + setDrawnFrom({ poolSize: pool.length, poolEntries: totalEntries(pool) }); setPhase("drawing"); const reducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false; @@ -116,6 +121,8 @@ export function RaffleWinnerDialog({ lastName: winner.lastName, email: winner.email, entryCount: winner.entries, + poolSize: drawnFrom?.poolSize, + poolEntries: drawnFrom?.poolEntries, }, nextPrizeSlot(winners, prize._id), ); diff --git a/src/components/features/raffle/raffle-winners-log.tsx b/src/components/features/raffle/raffle-winners-log.tsx index e6a894d..64549c1 100644 --- a/src/components/features/raffle/raffle-winners-log.tsx +++ b/src/components/features/raffle/raffle-winners-log.tsx @@ -87,6 +87,9 @@ export function RaffleWinnersLog({ Email )} + + Odds + @@ -94,7 +97,7 @@ export function RaffleWinnersLog({ {winners.length === 0 ? ( No winners drawn yet. They'll show up here as you confirm each draw. @@ -117,6 +120,18 @@ export function RaffleWinnersLog({ {winner.email} )} + + {winner.poolEntries + ? `${winner.entryCount} of ${winner.poolEntries}` + : `${winner.entryCount} entries`} + { ]); }); }); + +describe("splitOrganizers", () => { + it("recognizes organizer emails by domain, whatever the casing", () => { + expect(isOrganizerEmail("someone@nwplus.io")).toBe(true); + expect(isOrganizerEmail(" Someone@NWPLUS.IO ")).toBe(true); + expect(isOrganizerEmail("someone@gmail.com")).toBe(false); + expect(isOrganizerEmail("nwplus.io")).toBe(false); + }); + + it("takes organizers out of the pool and keeps everyone else in order", () => { + const alice = { email: "alice@example.com", preferredName: "Al", lastName: "", entries: 2 }; + const org = { email: "org@nwplus.io", preferredName: "Org", lastName: "", entries: 9 }; + const bob = { email: "bob@example.com", preferredName: "Bo", lastName: "", entries: 1 }; + + expect(splitOrganizers([alice, org, bob])).toEqual({ + hackers: [alice, bob], + organizers: [org], + }); + }); +}); + +describe("pickWeightedWinner", () => { + const pool = [ + { email: "a@example.com", preferredName: "A", lastName: "", entries: 1 }, + { email: "b@example.com", preferredName: "B", lastName: "", entries: 3 }, + ]; + + it("lands on each entrant in proportion to their entries", () => { + expect(pickWeightedWinner(pool, () => 0)?.email).toBe("a@example.com"); + expect(pickWeightedWinner(pool, () => 0.249)?.email).toBe("a@example.com"); + expect(pickWeightedWinner(pool, () => 0.25)?.email).toBe("b@example.com"); + expect(pickWeightedWinner(pool, () => 0.999)?.email).toBe("b@example.com"); + }); + + it("draws nobody from an empty pool", () => { + expect(pickWeightedWinner([])).toBeNull(); + }); +}); + +describe("defaultRaffleHackathon", () => { + const ids = ["HackCamp2026", "nwHacks2026", "nwHacks2027", "cmd-f2026", "blacklist", "www"]; + + it("picks the event whose season is nearest, not the highest year", () => { + expect(defaultRaffleHackathon(ids, new Date(2026, 10, 7))).toBe("HackCamp2026"); + expect(defaultRaffleHackathon(ids, new Date(2027, 0, 20))).toBe("nwHacks2027"); + expect(defaultRaffleHackathon(ids, new Date(2026, 2, 1))).toBe("cmd-f2026"); + }); + + it("prefers the upcoming event when two are equally near", () => { + expect(defaultRaffleHackathon(ids, new Date(2026, 11, 15))).toBe("nwHacks2027"); + }); + + it("never picks a non-event document, and falls back to the newest unknown-season event", () => { + expect(defaultRaffleHackathon(["blacklist", "www"])).toBe(""); + expect(defaultRaffleHackathon(["LHD2021", "HealthX2020", "www"])).toBe("LHD2021"); + }); +}); + +describe("generateWinnersCSV", () => { + it("escapes fields and leaves pool columns blank for winners logged before they existed", () => { + const csv = generateWinnersCSV([ + { + prizeId: "p", + prizeName: 'Air "Fryer"', + preferredName: "Al", + lastName: "A", + email: "al@example.com", + entryCount: 4, + poolEntries: 222, + poolSize: 49, + drawnAt: { toDate: () => new Date(2026, 10, 7, 12, 0) } as unknown as Timestamp, + }, + { + prizeId: "p", + prizeName: "Mug", + preferredName: "Bo", + lastName: "", + email: "bo@example.com", + entryCount: 1, + }, + ]); + + const [header, first, second] = csv.split("\n"); + expect(header).toBe( + '"Prize","Preferred Name","Last Name","Email","Entries","Pool Entries","Pool Size","Drawn At"', + ); + expect(first.startsWith('"Air ""Fryer""","Al","A","al@example.com","4","222","49","')).toBe( + true, + ); + expect(second).toBe('"Mug","Bo","","bo@example.com","1","","",""'); + }); +}); diff --git a/src/lib/raffle.ts b/src/lib/raffle.ts index 246bdb5..7e3033b 100644 --- a/src/lib/raffle.ts +++ b/src/lib/raffle.ts @@ -8,6 +8,7 @@ import type { } from "@/lib/firebase/types"; import { stampPointValue } from "@/lib/points"; import { SOCIALS_NAME_FALLBACK } from "@/lib/stamps"; +import { getHackathonType, isHackathonEvent, splitHackathon } from "@/lib/utils"; export type StampEntry = Pick; @@ -104,22 +105,105 @@ export const sumCtfPointsByEmail = ( return points; }; +/** Email domains that belong to organizers rather than hackers */ +export const ORGANIZER_EMAIL_DOMAINS = ["nwplus.io"]; + +/** + * Whether an email belongs to an organizer account, which must never win a hacker prize + * @param email - any casing, with or without surrounding whitespace + */ +export const isOrganizerEmail = (email: string): boolean => { + const domain = email.trim().toLowerCase().split("@")[1]; + return domain !== undefined && ORGANIZER_EMAIL_DOMAINS.includes(domain); +}; + +/** + * Separates organizer accounts out of the raffle pool so the draw can skip them and the page + * can say how many were skipped + * @param entrants - the raffle pool, organizers included + * @returns the hackers to draw from and the organizers removed + */ +export const splitOrganizers = ( + entrants: RaffleEntrant[], +): { hackers: RaffleEntrant[]; organizers: RaffleEntrant[] } => { + const hackers: RaffleEntrant[] = []; + const organizers: RaffleEntrant[] = []; + for (const entrant of entrants) { + (isOrganizerEmail(entrant.email) ? organizers : hackers).push(entrant); + } + return { hackers, organizers }; +}; + +/** The month each hackathon usually runs in, 1-12, for guessing which event is current */ +const SEASON_MONTH: Record = { hackcamp: 11, nwhacks: 1, "cmd-f": 3 }; + +/** + * Picks the hackathon an organizer most likely wants the raffle open on: the event whose usual + * month is closest to now, so HackCamp wins in November even once next year's nwHacks exists. + * Events whose season is unknown only win when nothing else is there, newest first + * @param hackathonIds - every hackathon document ID, events or not + * @param now - the current date, injectable for tests + * @returns the chosen hackathon ID, or "" when there are no events + */ +export const defaultRaffleHackathon = (hackathonIds: string[], now: Date = new Date()): string => { + const nowMonths = now.getFullYear() * 12 + now.getMonth() + 1; + + const ranked = hackathonIds + .filter(isHackathonEvent) + .map((id) => { + const year = Number(splitHackathon(id)[1]); + const month = SEASON_MONTH[getHackathonType(id)]; + const eventMonths = month === undefined ? undefined : year * 12 + month; + return { + id, + year, + distance: + eventMonths === undefined ? Number.POSITIVE_INFINITY : Math.abs(eventMonths - nowMonths), + // on a tie between a just-finished and an upcoming event, prefer the upcoming one + eventMonths: eventMonths ?? 0, + }; + }) + .sort( + (a, b) => + a.distance - b.distance || + b.eventMonths - a.eventMonths || + b.year - a.year || + a.id.localeCompare(b.id), + ); + + return ranked[0]?.id ?? ""; +}; + /** * Sums every entrant's entries across the pool */ export const totalEntries = (entrants: RaffleEntrant[]): number => entrants.reduce((sum, entrant) => sum + entrant.entries, 0); +/** + * A uniform random number in [0, 1) from the platform's cryptographic generator, so a draw can't + * be predicted or steered the way a seeded `Math.random` could; falls back to `Math.random` + * only where `crypto` is unavailable + */ +export const secureRandom = (): number => { + if (typeof crypto === "undefined" || !crypto.getRandomValues) return Math.random(); + return crypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32; +}; + /** * Draws one winner, weighted so that a hacker with N points is N times as likely to win * @param entrants - the raffle pool + * @param random - a source of uniform numbers in [0, 1), injectable for tests * @returns the drawn entrant, or null when the pool has no entries */ -export const pickWeightedWinner = (entrants: RaffleEntrant[]): RaffleEntrant | null => { +export const pickWeightedWinner = ( + entrants: RaffleEntrant[], + random: () => number = secureRandom, +): RaffleEntrant | null => { const total = totalEntries(entrants); if (total <= 0) return null; - let threshold = Math.random() * total; + let threshold = random() * total; for (const entrant of entrants) { threshold -= entrant.entries; if (threshold < 0) return entrant; @@ -188,7 +272,16 @@ const csvField = (value: string | number): string => `"${String(value).replace(/ * @returns CSV content ready for `downloadCSV` */ export const generateWinnersCSV = (winners: RaffleWinner[]): string => { - const header = ["Prize", "Preferred Name", "Last Name", "Email", "Entries", "Drawn At"]; + const header = [ + "Prize", + "Preferred Name", + "Last Name", + "Email", + "Entries", + "Pool Entries", + "Pool Size", + "Drawn At", + ]; const rows = winners.map((winner) => [ winner.prizeName, @@ -196,6 +289,8 @@ export const generateWinnersCSV = (winners: RaffleWinner[]): string => { winner.lastName, winner.email, winner.entryCount, + winner.poolEntries ?? "", + winner.poolSize ?? "", winner.drawnAt?.toDate().toLocaleString() ?? "", ] .map(csvField) diff --git a/src/lib/stamps.test.ts b/src/lib/stamps.test.ts index 15d129a..13df009 100644 --- a/src/lib/stamps.test.ts +++ b/src/lib/stamps.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { needsStampQrRegeneration } from "./stamps"; +import { needsStampQrRegeneration, readUnlockedStamps, stampBelongsToHackathon } from "./stamps"; describe("needsStampQrRegeneration", () => { it("generates a QR when enabling QR unlocking for the first time", () => { @@ -53,3 +53,52 @@ describe("needsStampQrRegeneration", () => { ).toBe(false); }); }); + +describe("stampBelongsToHackathon", () => { + it("matches the stamp's hackathon ignoring case, and counts hackathon-less stamps everywhere", () => { + expect(stampBelongsToHackathon({ hackathon: "HackCamp2026" }, "HackCamp2026")).toBe(true); + expect(stampBelongsToHackathon({ hackathon: "hackcamp2026" }, "HackCamp2026")).toBe(true); + expect(stampBelongsToHackathon({ hackathon: "cmd-f2026" }, "HackCamp2026")).toBe(false); + expect(stampBelongsToHackathon({}, "HackCamp2026")).toBe(true); + }); +}); + +describe("readUnlockedStamps", () => { + const stamps = new Map([ + ["hc", { hackathon: "HackCamp2026" }], + ["cf", { hackathon: "cmd-f2026" }], + ["global", {}], + ]); + + it("reads the map entry for the exact hackathon ID, as an array or a truthy map", () => { + expect(readUnlockedStamps({ HackCamp2026: ["hc", "global"] }, "HackCamp2026", stamps)).toEqual([ + "hc", + "global", + ]); + expect( + readUnlockedStamps({ HackCamp2026: { hc: true, global: false } }, "HackCamp2026", stamps), + ).toEqual(["hc"]); + }); + + it("no longer falls back to the hackathon slug, so one year's stamps stay out of the next", () => { + expect(readUnlockedStamps({ nwhacks: ["hc"] }, "nwHacks2026", stamps)).toEqual([]); + expect(readUnlockedStamps({ HackCamp2025: ["hc"] }, "HackCamp2026", stamps)).toEqual([]); + }); + + it("scopes a flat array by each stamp's own hackathon instead of counting it everywhere", () => { + const flat = ["hc", "cf", "global", "deleted"]; + expect(readUnlockedStamps(flat, "HackCamp2026", stamps)).toEqual(["hc", "global"]); + expect(readUnlockedStamps(flat, "cmd-f2026", stamps)).toEqual(["cf", "global"]); + expect(readUnlockedStamps(flat, "nwHacks2026", stamps)).toEqual(["global"]); + }); + + it("drops a stamp filed under one hackathon that has since moved to another", () => { + expect(readUnlockedStamps({ HackCamp2026: ["cf"] }, "HackCamp2026", stamps)).toEqual([]); + }); + + it("reads nothing from a missing or malformed field", () => { + expect(readUnlockedStamps(undefined, "HackCamp2026", stamps)).toEqual([]); + expect(readUnlockedStamps("hc", "HackCamp2026", stamps)).toEqual([]); + expect(readUnlockedStamps({ HackCamp2026: 3 }, "HackCamp2026", stamps)).toEqual([]); + }); +}); diff --git a/src/lib/stamps.ts b/src/lib/stamps.ts index 9c8b812..f8c98ae 100644 --- a/src/lib/stamps.ts +++ b/src/lib/stamps.ts @@ -35,28 +35,50 @@ export const needsStampQrRegeneration = ( return getHackathonType(activeStamp.hackathon ?? "") !== getHackathonType(values.hackathon ?? ""); }; +/** + * Whether a stamp counts toward a hackathon, matching the portal's stampbook: a stamp without a + * hackathon is global and counts everywhere, otherwise the hackathon IDs must match ignoring case + * @param stamp - the stamp, or just its `hackathon` + * @param hackathonId - hackathon ID + */ +export const stampBelongsToHackathon = ( + stamp: Pick, + hackathonId: string, +): boolean => !stamp.hackathon || stamp.hackathon.toLowerCase() === hackathonId.toLowerCase(); + /** * Reads the stamp IDs one Socials document has unlocked for a hackathon * - * The portal has written this field three different ways over the years, so all are read: - * a flat array, a map keyed by hackathon document ID, and a map keyed by hackathon slug + * The portal writes `unlockedStamps` as a map keyed by hackathon document ID, but a few older + * documents hold a flat array with no hackathon at all. Every stamp ID is therefore checked + * against the stamp's own `hackathon`, so a flat array only counts toward the event its stamps + * belong to instead of every event, and a stamp moved to another hackathon stops counting here * @param unlockedStamps - the raw `unlockedStamps` field off a Socials document * @param hackathonId - hackathon ID + * @param stampsById - every stamp by document ID; an ID missing from it (deleted) is left out * @returns the stamp IDs this hacker has collected for the hackathon */ -export const readUnlockedStamps = (unlockedStamps: unknown, hackathonId: string): string[] => { - if (Array.isArray(unlockedStamps)) return unlockedStamps.map(String); - if (!unlockedStamps || typeof unlockedStamps !== "object") return []; - - const byHackathon = unlockedStamps as Record; - const collected = byHackathon[hackathonId] ?? byHackathon[getHackathonType(hackathonId)]; +export const readUnlockedStamps = ( + unlockedStamps: unknown, + hackathonId: string, + stampsById: Map>, +): string[] => { + const collected = Array.isArray(unlockedStamps) + ? unlockedStamps + : unlockedStamps && typeof unlockedStamps === "object" + ? (unlockedStamps as Record)[hackathonId] + : undefined; - if (Array.isArray(collected)) return collected.map(String); - if (collected && typeof collected === "object") { - return Object.entries(collected) - .filter(([, unlocked]) => Boolean(unlocked)) - .map(([stampId]) => stampId); - } + const ids = Array.isArray(collected) + ? collected.map(String) + : collected && typeof collected === "object" + ? Object.entries(collected) + .filter(([, unlocked]) => Boolean(unlocked)) + .map(([stampId]) => stampId) + : []; - return []; + return ids.filter((stampId) => { + const stamp = stampsById.get(stampId); + return stamp !== undefined && stampBelongsToHackathon(stamp, hackathonId); + }); }; diff --git a/src/lib/utils.test.ts b/src/lib/utils.test.ts new file mode 100644 index 0000000..27d7407 --- /dev/null +++ b/src/lib/utils.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; +import { isHackathonEvent } from "./utils"; + +describe("isHackathonEvent", () => { + it("accepts a hackathon name followed by its four-digit year", () => { + expect(isHackathonEvent("HackCamp2026")).toBe(true); + expect(isHackathonEvent("cmd-f2026")).toBe(true); + expect(isHackathonEvent("LHD2021")).toBe(true); + }); + + it("rejects the documents that live beside the events", () => { + expect(isHackathonEvent("blacklist")).toBe(false); + expect(isHackathonEvent("www")).toBe(false); + expect(isHackathonEvent("WrappedTestHackathon")).toBe(false); + expect(isHackathonEvent("2026")).toBe(false); + }); +}); diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 2daa61f..0b3b656 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -30,6 +30,14 @@ export const splitHackathon = (hackathonId: string): [string, string | undefined return [hackathonId, undefined]; }; +/** + * Whether a Hackathons document is an actual event, as opposed to `blacklist`, `www` or a test + * document: every event ID is a name followed by its four-digit year + * @param hackathonId - hackathon document ID + */ +export const isHackathonEvent = (hackathonId: string): boolean => + splitHackathon(hackathonId)[1] !== undefined; + /** * Formats a Firebase timestamp object for display */ diff --git a/src/routes/_auth/stampbook/raffle.tsx b/src/routes/_auth/stampbook/raffle.tsx index 6de36fe..7cf4d1c 100644 --- a/src/routes/_auth/stampbook/raffle.tsx +++ b/src/routes/_auth/stampbook/raffle.tsx @@ -12,7 +12,8 @@ import { } from "@/components/ui/select"; import { subscribeToHackathons } from "@/lib/firebase/firestore"; import type { Hackathon, RaffleEntrant, RafflePrize, RaffleWinner } from "@/lib/firebase/types"; -import { splitHackathon } from "@/lib/utils"; +import { defaultRaffleHackathon } from "@/lib/raffle"; +import { isHackathonEvent } from "@/lib/utils"; import { fetchRaffleEntrants, subscribeToRafflePrizes, @@ -23,35 +24,43 @@ import { ArrowLeft } from "lucide-react"; import { useCallback, useEffect, useRef, useState } from "react"; import { toast } from "sonner"; +interface RaffleSearch { + /** the hackathon the raffle is open on, kept in the URL so organizers can share one link */ + hackathon?: string; +} + export const Route = createFileRoute("/_auth/stampbook/raffle")({ component: RafflePage, + validateSearch: (search: Record): RaffleSearch => ({ + hackathon: + typeof search.hackathon === "string" && search.hackathon ? search.hackathon : undefined, + }), }); -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 ?? ""; - function RafflePage() { + const { hackathon: searchHackathon } = Route.useSearch(); + const navigate = Route.useNavigate(); const [hackathons, setHackathons] = useState([]); - const [selectedHackathon, setSelectedHackathon] = useState(""); const [prizes, setPrizes] = useState([]); const [winners, setWinners] = useState([]); const [entrants, setEntrants] = useState([]); + const [excludedOrganizers, setExcludedOrganizers] = useState(0); const [poolLoading, setPoolLoading] = useState(false); const [poolError, setPoolError] = useState(false); const [poolFetchedAt, setPoolFetchedAt] = useState(null); const [showEmails, setShowEmails] = useState(false); const requestRef = useRef(0); - useEffect(() => { - const unsubHackathons = subscribeToHackathons((docs) => { - setHackathons(docs); - setSelectedHackathon((current) => current || newestHackathonId(docs)); - }); + // only real events are offered, so `blacklist`, `www` and test documents can't be drawn from + const events = hackathons.filter((hackathon) => isHackathonEvent(hackathon._id)); + const selectedHackathon = + searchHackathon && events.some((hackathon) => hackathon._id === searchHackathon) + ? searchHackathon + : defaultRaffleHackathon(events.map((hackathon) => hackathon._id)); - return unsubHackathons; - }, []); + const selectHackathon = (hackathon: string) => navigate({ search: { hackathon }, replace: true }); + + useEffect(() => subscribeToHackathons(setHackathons), []); useEffect(() => { if (!selectedHackathon) return; @@ -74,6 +83,7 @@ function RafflePage() { const loadPool = useCallback(async (hackathon: string, refresh = false) => { if (!hackathon) { setEntrants([]); + setExcludedOrganizers(0); setPoolError(false); setPoolFetchedAt(null); return; @@ -87,13 +97,15 @@ function RafflePage() { try { const pool = await fetchRaffleEntrants(hackathon, refresh); if (requestId !== requestRef.current) return; - setEntrants(pool); + setEntrants(pool.entrants); + setExcludedOrganizers(pool.excludedOrganizers); 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([]); + setExcludedOrganizers(0); setPoolFetchedAt(null); setPoolError(true); toast.error("Failed to load raffle entries"); @@ -112,12 +124,12 @@ function RafflePage() {
Raffle
- - {hackathons.map((hackathon) => ( + {events.map((hackathon) => ( {hackathon._id} @@ -150,6 +162,7 @@ function RafflePage() { prizes={prizes} winners={winners} entrants={entrants} + excludedOrganizers={excludedOrganizers} poolLoading={poolLoading} poolError={poolError} poolFetchedAt={poolFetchedAt} diff --git a/src/services/raffle.ts b/src/services/raffle.ts index a87cad7..e57095e 100644 --- a/src/services/raffle.ts +++ b/src/services/raffle.ts @@ -9,6 +9,7 @@ import type { import { type ApplicantName, buildRaffleEntrants, + splitOrganizers, stampPointsById, sumCtfPointsByEmail, } from "@/lib/raffle"; @@ -173,6 +174,8 @@ export const addRaffleWinner = async ( lastName: winner.lastName, email: winner.email, entryCount: winner.entryCount, + ...(winner.poolSize !== undefined && { poolSize: winner.poolSize }), + ...(winner.poolEntries !== undefined && { poolEntries: winner.poolEntries }), slot, drawnAt: Timestamp.now(), drawnBy: auth.currentUser?.email ?? "", @@ -245,23 +248,36 @@ export const fetchCtfPointsByEmail = async (hackathon: string): Promise solveDoc.data() as CtfSolve)); }; +/** + * The raffle pool for a hackathon, with organizer accounts already taken out of it + */ +export interface RafflePool { + /** one entrant per hacker with at least one point, organizers excluded */ + entrants: RaffleEntrant[]; + /** how many organizer accounts had points and were left out */ + excludedOrganizers: number; +} + /** * Builds the raffle pool for a hackathon, where each point is one entry: the point value of - * every stamp a hacker collected plus their CTF points + * every stamp a hacker collected plus their CTF points. Organizer accounts are removed * @param hackathon - hackathon ID * @param refreshNames - re-reads applicant names as well as stamps, for an explicit refresh - * @returns the raffle pool, one entrant per hacker with at least one point + * @returns the raffle pool and how many organizers were excluded from it */ export const fetchRaffleEntrants = async ( hackathon: string, refreshNames = false, -): Promise => { - const [stampEntries, stamps, applicantNames, ctfPoints] = await Promise.all([ - fetchHackersWithStamps(hackathon), - fetchStamps(), +): Promise => { + const stamps = await fetchStamps(); + const [stampEntries, applicantNames, ctfPoints] = await Promise.all([ + fetchHackersWithStamps(hackathon, stamps), fetchApplicantNames(hackathon, refreshNames), fetchCtfPointsByEmail(hackathon), ]); - return buildRaffleEntrants(stampEntries, stampPointsById(stamps), applicantNames, ctfPoints); + const { hackers, organizers } = splitOrganizers( + buildRaffleEntrants(stampEntries, stampPointsById(stamps), applicantNames, ctfPoints), + ); + return { entrants: hackers, excludedOrganizers: organizers.length }; }; diff --git a/src/services/stamps.ts b/src/services/stamps.ts index 09c11eb..b5b91da 100644 --- a/src/services/stamps.ts +++ b/src/services/stamps.ts @@ -145,18 +145,29 @@ export const deleteStampQR = async (stampId: string) => { * 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 + * @param stamps - every stamp, when the caller has already loaded them; fetched otherwise * @returns Array of entries where each entry represents one stamp collected by a hacker */ -export const fetchHackersWithStamps = async (hackathonId: string): Promise => { - const socialsSnapshot = await getDocs(collection(db, "Socials")); - const entries: HackerStampEntry[] = []; +export const fetchHackersWithStamps = async ( + hackathonId: string, + stamps?: Stamp[], +): Promise => { + const [socialsSnapshot, everyStamp] = await Promise.all([ + getDocs(collection(db, "Socials")), + stamps ?? fetchStamps(), + ]); + const stampsById = new Map(); + for (const stamp of everyStamp) { + if (stamp._id) stampsById.set(stamp._id, stamp); + } + const entries: HackerStampEntry[] = []; for (const socialDoc of socialsSnapshot.docs) { const socialData = socialDoc.data(); const displayName = socialData.preferredName || SOCIALS_NAME_FALLBACK; const email = socialData.email || ""; - for (const stampId of readUnlockedStamps(socialData.unlockedStamps, hackathonId)) { + for (const stampId of readUnlockedStamps(socialData.unlockedStamps, hackathonId, stampsById)) { entries.push({ displayName, email, stampId }); } } From fb42593924fa1e2a0d75624f78e46ce9583d3b3c Mon Sep 17 00:00:00 2001 From: naijwu Date: Sat, 7 Nov 2026 13:42:24 -0700 Subject: [PATCH 2/2] fix(raffle): hardening --- .../features/auth/sign-in-button.tsx | 4 +- src/lib/raffle.test.ts | 32 ++++++++++--- src/lib/raffle.ts | 45 +++++++++++-------- src/lib/stamps.test.ts | 8 +++- src/lib/stamps.ts | 21 +++++---- src/lib/utils.ts | 3 ++ src/routes/_auth/stampbook/raffle.tsx | 38 ++++++++++++++-- src/services/raffle.ts | 8 ++-- src/services/stamps.ts | 5 ++- 9 files changed, 121 insertions(+), 43 deletions(-) diff --git a/src/components/features/auth/sign-in-button.tsx b/src/components/features/auth/sign-in-button.tsx index 564aecd..6cba4bb 100644 --- a/src/components/features/auth/sign-in-button.tsx +++ b/src/components/features/auth/sign-in-button.tsx @@ -1,5 +1,5 @@ import { auth } from "@/lib/firebase/client"; -import { cn } from "@/lib/utils"; +import { ORGANIZER_EMAIL_DOMAIN, cn } from "@/lib/utils"; import { useRouter } from "@tanstack/react-router"; import { GoogleAuthProvider, signInWithPopup } from "firebase/auth"; import { useState } from "react"; @@ -21,7 +21,7 @@ export function SignInButton({ try { const provider = new GoogleAuthProvider(); provider.setCustomParameters({ - hd: "nwplus.io", + hd: ORGANIZER_EMAIL_DOMAIN, }); await signInWithPopup(auth, provider); } catch (error) { diff --git a/src/lib/raffle.test.ts b/src/lib/raffle.test.ts index a1e2329..dd0f00c 100644 --- a/src/lib/raffle.test.ts +++ b/src/lib/raffle.test.ts @@ -148,7 +148,10 @@ describe("splitOrganizers", () => { it("recognizes organizer emails by domain, whatever the casing", () => { expect(isOrganizerEmail("someone@nwplus.io")).toBe(true); expect(isOrganizerEmail(" Someone@NWPLUS.IO ")).toBe(true); + expect(isOrganizerEmail("someone@sub.nwplus.io")).toBe(true); + expect(isOrganizerEmail("a@b@nwplus.io")).toBe(true); expect(isOrganizerEmail("someone@gmail.com")).toBe(false); + expect(isOrganizerEmail("someone@notnwplus.io")).toBe(false); expect(isOrganizerEmail("nwplus.io")).toBe(false); }); @@ -185,14 +188,33 @@ describe("pickWeightedWinner", () => { describe("defaultRaffleHackathon", () => { const ids = ["HackCamp2026", "nwHacks2026", "nwHacks2027", "cmd-f2026", "blacklist", "www"]; - it("picks the event whose season is nearest, not the highest year", () => { - expect(defaultRaffleHackathon(ids, new Date(2026, 10, 7))).toBe("HackCamp2026"); - expect(defaultRaffleHackathon(ids, new Date(2027, 0, 20))).toBe("nwHacks2027"); - expect(defaultRaffleHackathon(ids, new Date(2026, 2, 1))).toBe("cmd-f2026"); + it("uses the CMS's active hackathon when it is a listed event", () => { + expect(defaultRaffleHackathon(ids, "cmd-f2026", new Date(2026, 10, 7))).toBe("cmd-f2026"); + expect(defaultRaffleHackathon(ids, "www", new Date(2026, 10, 7))).toBe("HackCamp2026"); + expect(defaultRaffleHackathon(ids, "nwHacks2028", new Date(2026, 10, 7))).toBe("HackCamp2026"); + }); + + it("otherwise picks the event whose season is nearest, not the highest year", () => { + expect(defaultRaffleHackathon(ids, undefined, new Date(2026, 10, 7))).toBe("HackCamp2026"); + expect(defaultRaffleHackathon(ids, "", new Date(2027, 0, 20))).toBe("nwHacks2027"); + expect(defaultRaffleHackathon(ids, undefined, new Date(2026, 2, 1))).toBe("cmd-f2026"); }); it("prefers the upcoming event when two are equally near", () => { - expect(defaultRaffleHackathon(ids, new Date(2026, 11, 15))).toBe("nwHacks2027"); + expect(defaultRaffleHackathon(ids, undefined, new Date(2026, 11, 15))).toBe("nwHacks2027"); + }); + + it("ranks events with an unknown season below every known one", () => { + expect( + defaultRaffleHackathon( + ["LHD2027", "nwHacks2027", "HackCamp2026"], + undefined, + new Date(2026, 11, 15), + ), + ).toBe("nwHacks2027"); + expect( + defaultRaffleHackathon(["LHD2026", "HackCamp2021"], undefined, new Date(2026, 10, 7)), + ).toBe("HackCamp2021"); }); it("never picks a non-event document, and falls back to the newest unknown-season event", () => { diff --git a/src/lib/raffle.ts b/src/lib/raffle.ts index 7e3033b..a1b106d 100644 --- a/src/lib/raffle.ts +++ b/src/lib/raffle.ts @@ -8,7 +8,7 @@ import type { } from "@/lib/firebase/types"; import { stampPointValue } from "@/lib/points"; import { SOCIALS_NAME_FALLBACK } from "@/lib/stamps"; -import { getHackathonType, isHackathonEvent, splitHackathon } from "@/lib/utils"; +import { ORGANIZER_EMAIL_DOMAIN, isHackathonEvent, splitHackathon } from "@/lib/utils"; export type StampEntry = Pick; @@ -105,16 +105,18 @@ export const sumCtfPointsByEmail = ( return points; }; -/** Email domains that belong to organizers rather than hackers */ -export const ORGANIZER_EMAIL_DOMAINS = ["nwplus.io"]; - /** * Whether an email belongs to an organizer account, which must never win a hacker prize * @param email - any casing, with or without surrounding whitespace + * @returns true for the organizer domain or any subdomain of it */ export const isOrganizerEmail = (email: string): boolean => { - const domain = email.trim().toLowerCase().split("@")[1]; - return domain !== undefined && ORGANIZER_EMAIL_DOMAINS.includes(domain); + const trimmed = email.trim().toLowerCase(); + const at = trimmed.lastIndexOf("@"); + if (at < 0) return false; + + const domain = trimmed.slice(at + 1); + return domain === ORGANIZER_EMAIL_DOMAIN || domain.endsWith(`.${ORGANIZER_EMAIL_DOMAIN}`); }; /** @@ -134,29 +136,36 @@ export const splitOrganizers = ( return { hackers, organizers }; }; -/** The month each hackathon usually runs in, 1-12, for guessing which event is current */ +/** The month each hackathon usually runs in, 1-12, by lowercased name, for guessing the current event */ const SEASON_MONTH: Record = { hackcamp: 11, nwhacks: 1, "cmd-f": 3 }; /** - * Picks the hackathon an organizer most likely wants the raffle open on: the event whose usual - * month is closest to now, so HackCamp wins in November even once next year's nwHacks exists. - * Events whose season is unknown only win when nothing else is there, newest first + * Picks the hackathon the raffle should open on: the CMS's `activeHackathon` when it is one of + * the listed events, otherwise the event whose usual month is closest to now, so HackCamp wins + * in November even once next year's nwHacks exists. Events whose season is unknown only win + * when nothing else is there, newest first * @param hackathonIds - every hackathon document ID, events or not + * @param activeHackathon - the CMS's `activeHackathon` flag, if it could be read * @param now - the current date, injectable for tests * @returns the chosen hackathon ID, or "" when there are no events */ -export const defaultRaffleHackathon = (hackathonIds: string[], now: Date = new Date()): string => { - const nowMonths = now.getFullYear() * 12 + now.getMonth() + 1; +export const defaultRaffleHackathon = ( + hackathonIds: string[], + activeHackathon?: string, + now: Date = new Date(), +): string => { + const events = hackathonIds.filter(isHackathonEvent); + if (activeHackathon && events.includes(activeHackathon)) return activeHackathon; - const ranked = hackathonIds - .filter(isHackathonEvent) + const nowMonths = now.getFullYear() * 12 + now.getMonth() + 1; + const ranked = events .map((id) => { - const year = Number(splitHackathon(id)[1]); - const month = SEASON_MONTH[getHackathonType(id)]; - const eventMonths = month === undefined ? undefined : year * 12 + month; + const [name, year] = splitHackathon(id); + const month = SEASON_MONTH[name.toLowerCase()]; + const eventMonths = month === undefined ? undefined : Number(year) * 12 + month; return { id, - year, + year: Number(year), distance: eventMonths === undefined ? Number.POSITIVE_INFINITY : Math.abs(eventMonths - nowMonths), // on a tie between a just-finished and an upcoming event, prefer the upcoming one diff --git a/src/lib/stamps.test.ts b/src/lib/stamps.test.ts index 13df009..ceda8b7 100644 --- a/src/lib/stamps.test.ts +++ b/src/lib/stamps.test.ts @@ -80,8 +80,14 @@ describe("readUnlockedStamps", () => { ).toEqual(["hc"]); }); - it("no longer falls back to the hackathon slug, so one year's stamps stay out of the next", () => { + it("reads a slug-keyed bucket but only keeps the stamps belonging to this hackathon", () => { + const slugKeyed = { hackcamp: ["hc", "cf", "global"] }; + expect(readUnlockedStamps(slugKeyed, "HackCamp2026", stamps)).toEqual(["hc", "global"]); + expect(readUnlockedStamps(slugKeyed, "HackCamp2025", stamps)).toEqual(["global"]); expect(readUnlockedStamps({ nwhacks: ["hc"] }, "nwHacks2026", stamps)).toEqual([]); + }); + + it("does not read another year's bucket", () => { expect(readUnlockedStamps({ HackCamp2025: ["hc"] }, "HackCamp2026", stamps)).toEqual([]); }); diff --git a/src/lib/stamps.ts b/src/lib/stamps.ts index f8c98ae..7e0fb6d 100644 --- a/src/lib/stamps.ts +++ b/src/lib/stamps.ts @@ -49,10 +49,11 @@ export const stampBelongsToHackathon = ( /** * Reads the stamp IDs one Socials document has unlocked for a hackathon * - * The portal writes `unlockedStamps` as a map keyed by hackathon document ID, but a few older - * documents hold a flat array with no hackathon at all. Every stamp ID is therefore checked - * against the stamp's own `hackathon`, so a flat array only counts toward the event its stamps - * belong to instead of every event, and a stamp moved to another hackathon stops counting here + * The portal has written `unlockedStamps` three ways over the years: a map keyed by hackathon + * document ID, a map keyed by hackathon slug, and a flat array with no hackathon at all. All + * three are read, and every stamp ID is then checked against the stamp's own `hackathon`, so + * a flat array or slug bucket only counts toward the event its stamps belong to instead of + * every event sharing that slug, and a stamp moved to another hackathon stops counting here * @param unlockedStamps - the raw `unlockedStamps` field off a Socials document * @param hackathonId - hackathon ID * @param stampsById - every stamp by document ID; an ID missing from it (deleted) is left out @@ -63,11 +64,13 @@ export const readUnlockedStamps = ( hackathonId: string, stampsById: Map>, ): string[] => { - const collected = Array.isArray(unlockedStamps) - ? unlockedStamps - : unlockedStamps && typeof unlockedStamps === "object" - ? (unlockedStamps as Record)[hackathonId] - : undefined; + let collected: unknown; + if (Array.isArray(unlockedStamps)) { + collected = unlockedStamps; + } else if (unlockedStamps && typeof unlockedStamps === "object") { + const byHackathon = unlockedStamps as Record; + collected = byHackathon[hackathonId] ?? byHackathon[getHackathonType(hackathonId)]; + } const ids = Array.isArray(collected) ? collected.map(String) diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 0b3b656..38c156d 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -2,6 +2,9 @@ import { type ClassValue, clsx } from "clsx"; import { twMerge } from "tailwind-merge"; import type { Applicant, HackathonType } from "./firebase/types"; +/** The Google Workspace domain organizers sign in with; hackers never have one of these */ +export const ORGANIZER_EMAIL_DOMAIN = "nwplus.io"; + export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } diff --git a/src/routes/_auth/stampbook/raffle.tsx b/src/routes/_auth/stampbook/raffle.tsx index 7cf4d1c..5a754d7 100644 --- a/src/routes/_auth/stampbook/raffle.tsx +++ b/src/routes/_auth/stampbook/raffle.tsx @@ -14,6 +14,7 @@ import { subscribeToHackathons } from "@/lib/firebase/firestore"; import type { Hackathon, RaffleEntrant, RafflePrize, RaffleWinner } from "@/lib/firebase/types"; import { defaultRaffleHackathon } from "@/lib/raffle"; import { isHackathonEvent } from "@/lib/utils"; +import { getAdminFlags } from "@/services/evaluator"; import { fetchRaffleEntrants, subscribeToRafflePrizes, @@ -21,7 +22,7 @@ import { } from "@/services/raffle"; import { Link, createFileRoute } from "@tanstack/react-router"; import { ArrowLeft } from "lucide-react"; -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { toast } from "sonner"; interface RaffleSearch { @@ -41,6 +42,8 @@ function RafflePage() { const { hackathon: searchHackathon } = Route.useSearch(); const navigate = Route.useNavigate(); const [hackathons, setHackathons] = useState([]); + // null until the CMS has been read, so the default isn't chosen without it + const [activeHackathon, setActiveHackathon] = useState(null); const [prizes, setPrizes] = useState([]); const [winners, setWinners] = useState([]); const [entrants, setEntrants] = useState([]); @@ -52,16 +55,45 @@ function RafflePage() { const requestRef = useRef(0); // only real events are offered, so `blacklist`, `www` and test documents can't be drawn from - const events = hackathons.filter((hackathon) => isHackathonEvent(hackathon._id)); + const events = useMemo( + () => + hackathons.filter( + (hackathon) => isHackathonEvent(hackathon._id) && !hackathon.featureFlags?.test, + ), + [hackathons], + ); + + // the URL is the only source of the selection, so a Hackathons snapshot arriving mid-draw + // can't switch the page to another event the way a re-derived default would const selectedHackathon = searchHackathon && events.some((hackathon) => hackathon._id === searchHackathon) ? searchHackathon - : defaultRaffleHackathon(events.map((hackathon) => hackathon._id)); + : ""; const selectHackathon = (hackathon: string) => navigate({ search: { hackathon }, replace: true }); useEffect(() => subscribeToHackathons(setHackathons), []); + useEffect(() => { + let cancelled = false; + getAdminFlags().then((flags) => { + if (!cancelled) setActiveHackathon(flags?.activeHackathon ?? ""); + }); + return () => { + cancelled = true; + }; + }, []); + + // without a usable hackathon in the URL, pick one once and write it there + useEffect(() => { + if (selectedHackathon || activeHackathon === null || events.length === 0) return; + const fallback = defaultRaffleHackathon( + events.map((hackathon) => hackathon._id), + activeHackathon, + ); + if (fallback) navigate({ search: { hackathon: fallback }, replace: true }); + }, [selectedHackathon, activeHackathon, events, navigate]); + useEffect(() => { if (!selectedHackathon) return; diff --git a/src/services/raffle.ts b/src/services/raffle.ts index e57095e..438af96 100644 --- a/src/services/raffle.ts +++ b/src/services/raffle.ts @@ -269,9 +269,11 @@ export const fetchRaffleEntrants = async ( hackathon: string, refreshNames = false, ): Promise => { - const stamps = await fetchStamps(); - const [stampEntries, applicantNames, ctfPoints] = await Promise.all([ - fetchHackersWithStamps(hackathon, stamps), + // the stamps fetch is shared with fetchHackersWithStamps without waiting on it first + const pendingStamps = fetchStamps(); + const [stampEntries, stamps, applicantNames, ctfPoints] = await Promise.all([ + fetchHackersWithStamps(hackathon, pendingStamps), + pendingStamps, fetchApplicantNames(hackathon, refreshNames), fetchCtfPointsByEmail(hackathon), ]); diff --git a/src/services/stamps.ts b/src/services/stamps.ts index b5b91da..b5dc7a3 100644 --- a/src/services/stamps.ts +++ b/src/services/stamps.ts @@ -145,12 +145,13 @@ export const deleteStampQR = async (stampId: string) => { * 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 - * @param stamps - every stamp, when the caller has already loaded them; fetched otherwise + * @param stamps - every stamp, or a pending fetch of them, when the caller is loading them + * anyway; fetched here otherwise * @returns Array of entries where each entry represents one stamp collected by a hacker */ export const fetchHackersWithStamps = async ( hackathonId: string, - stamps?: Stamp[], + stamps?: Stamp[] | Promise, ): Promise => { const [socialsSnapshot, everyStamp] = await Promise.all([ getDocs(collection(db, "Socials")),