diff --git a/src/components/features/raffle/raffle-draw-panel.tsx b/src/components/features/raffle/raffle-draw-panel.tsx index e96cdea..0db94f1 100644 --- a/src/components/features/raffle/raffle-draw-panel.tsx +++ b/src/components/features/raffle/raffle-draw-panel.tsx @@ -15,7 +15,7 @@ import { totalEntries, } from "@/lib/raffle"; import { cn } from "@/lib/utils"; -import { Gift, Loader2, RefreshCw, Stamp } from "lucide-react"; +import { Gift, Loader2, RefreshCw } from "lucide-react"; import { useState } from "react"; interface RaffleDrawPanelProps { @@ -23,11 +23,11 @@ interface RaffleDrawPanelProps { prizes: RafflePrize[]; winners: RaffleWinner[]; entrants: RaffleEntrant[]; - eligibleStampCount: number; poolLoading: boolean; + /** the last pool load failed, so `entrants` is empty and drawing is blocked */ + poolError: boolean; poolFetchedAt: Date | null; onRefreshPool: () => void; - onManageStamps: () => void; className?: string; } @@ -36,11 +36,10 @@ export function RaffleDrawPanel({ prizes, winners, entrants, - eligibleStampCount, poolLoading, + poolError, poolFetchedAt, onRefreshPool, - onManageStamps, className, }: RaffleDrawPanelProps) { const [selectedPrizeId, setSelectedPrizeId] = useState(""); @@ -60,12 +59,12 @@ export function RaffleDrawPanel({ const disabledReason = prizes.length === 0 ? "Add prizes before drawing" - : eligibleStampCount === 0 - ? "Choose which stamps count as entries" - : poolLoading - ? "Loading the entry pool..." + : poolLoading + ? "Loading the entry pool..." + : poolError + ? "Couldn't load the entry pool, refresh to try again" : poolEntries === 0 - ? "No entries yet, nobody has collected an eligible stamp" + ? "No entries yet, nobody has earned any points" : !selectedPrize ? "Every prize has been fully drawn" : remaining <= 0 @@ -125,11 +124,13 @@ export function RaffleDrawPanel({ Loading entries... + ) : poolError ? ( + Couldn't load entries ) : ( {poolEntries} entries from{" "} - {entrants.length} hackers across{" "} - {eligibleStampCount} eligible stamp{eligibleStampCount === 1 ? "" : "s"} + {entrants.length} hackers, 1 entry + per point )} {poolFetchedAt && !poolLoading && ( @@ -145,15 +146,6 @@ export function RaffleDrawPanel({ Refresh - {disabledReason &&

{disabledReason}

} diff --git a/src/components/features/raffle/raffle-stamps-dialog.tsx b/src/components/features/raffle/raffle-stamps-dialog.tsx deleted file mode 100644 index 855c563..0000000 --- a/src/components/features/raffle/raffle-stamps-dialog.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import { StampPicker } from "@/components/features/stampbook/stamp-picker"; -import { Button } from "@/components/ui/button"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog"; -import type { Stamp } from "@/lib/firebase/types"; -import { saveRaffleSettings } from "@/services/raffle"; -import { Loader2 } from "lucide-react"; -import { useState } from "react"; -import { toast } from "sonner"; - -interface RaffleStampsDialogProps { - open: boolean; - onClose: () => void; - hackathon: string; - stamps: Stamp[]; - eligibleStampIds: string[]; -} - -export function RaffleStampsDialog({ - open, - onClose, - hackathon, - stamps, - eligibleStampIds, -}: RaffleStampsDialogProps) { - const [draftStampIds, setDraftStampIds] = useState(null); - const [loading, setLoading] = useState(false); - - const selectedStampIds = draftStampIds ?? eligibleStampIds; - - const handleClose = () => { - setDraftStampIds(null); - onClose(); - }; - - const handleSave = async () => { - if (loading) return; - setLoading(true); - try { - await saveRaffleSettings(hackathon, selectedStampIds); - toast.success( - `${selectedStampIds.length} stamp${selectedStampIds.length === 1 ? "" : "s"} count as entries`, - ); - handleClose(); - } catch (error) { - console.error("Error saving raffle settings:", error); - toast.error("Failed to save eligible stamps"); - } finally { - setLoading(false); - } - }; - - return ( - !state && handleClose()}> - - - Eligible stamps - - Every one of these stamps a hacker collected counts as one raffle entry, so collecting - more stamps means better odds. - - - -
- - - -
-
-
- ); -} 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..0a867e4 --- /dev/null +++ b/src/components/features/settings/hackathon-settings-form.test.tsx @@ -0,0 +1,68 @@ +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("@/components/features/settings/wallet-email-control", () => ({ + WalletEmailControl: () => null, +})); + +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 1c47361..c419bb3 100644 --- a/src/components/features/settings/hackathon-settings-form.tsx +++ b/src/components/features/settings/hackathon-settings-form.tsx @@ -134,8 +134,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 = @@ -283,6 +285,20 @@ export function HackathonSettingsForm({ hackathonId }: { hackathonId: string }) disabled={isEditing || isSaving} /> +
+
+ +

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

+
+ handleFieldChange("ctfOpen", checked)} + disabled={!isEditing} + /> +
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/components/features/stampbook/stamp-dialog.tsx b/src/components/features/stampbook/stamp-dialog.tsx index e5bc26d..9899732 100644 --- a/src/components/features/stampbook/stamp-dialog.tsx +++ b/src/components/features/stampbook/stamp-dialog.tsx @@ -23,7 +23,8 @@ 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 { STAMP_CATEGORIES } from "@/lib/stamps"; +import { stampPointValue } from "@/lib/points"; +import { STAMP_CATEGORIES, needsStampQrRegeneration } from "@/lib/stamps"; import { getHackathonType } from "@/lib/utils"; import { deleteStampQR, deleteStampWithImage, upsertStampWithImage } from "@/services/stamps"; import { zodResolver } from "@hookform/resolvers/zod"; @@ -43,6 +44,7 @@ const EMPTY_FORM: z.infer = { description: "", hackathon: "", category: "other", + points: 1, isHidden: false, isTitle: false, isQRUnlockable: false, @@ -54,6 +56,11 @@ const formSchema = z.object({ description: z.string().min(2, "Description must be at least 2 characters").max(500), hackathon: z.string().min(1, "Please select a hackathon"), category: z.enum(["preHackathonWorkshop", "dayOfWorkshop", "dayOfActivity", "other"]), + points: z + .number({ invalid_type_error: "Enter a whole number of points" }) + .int("Points must be a whole number") + .min(0, "Points can't be negative") + .max(1000, "Points can't be more than 1000"), isHidden: z.boolean(), isTitle: z.boolean(), isQRUnlockable: z.boolean(), @@ -139,6 +146,7 @@ export function StampDialog({ open, activeStamp, onClose }: StampDialogProps) { description: activeStamp?.description ?? "", hackathon: activeStamp?.hackathon ?? "", category: activeStamp?.category ?? "other", + points: activeStamp ? stampPointValue(activeStamp) : 1, isHidden: activeStamp?.isHidden ?? false, isTitle: activeStamp?.isTitle ?? false, isQRUnlockable: activeStamp?.isQRUnlockable ?? false, @@ -224,6 +232,7 @@ export function StampDialog({ open, activeStamp, onClose }: StampDialogProps) { const stampData: Stamp = { name: values.name, description: values.description, + points: values.points, isHidden: values.isHidden, isTitle: values.isTitle, isQRUnlockable: values.isQRUnlockable, @@ -237,11 +246,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; @@ -418,6 +428,34 @@ export function StampDialog({ open, activeStamp, onClose }: StampDialogProps) { )} /> + ( + + Points + + field.onChange(e.target.valueAsNumber)} + /> + + + Each point is one raffle entry for hackers who unlock this stamp. 0 gives no + entries. + + + + )} + /> + stampPointValue(stamp), { + id: "points", + header: "Points", + size: 50, + }), columnHelper.accessor("isHidden", { header: "Visibility", cell: (info) => { diff --git a/src/lib/firebase/types.ts b/src/lib/firebase/types.ts index 0d0b79a..386a462 100644 --- a/src/lib/firebase/types.ts +++ b/src/lib/firebase/types.ts @@ -716,6 +716,7 @@ export interface HackathonConfig { _id?: string; applicationDeadline: HackathonConfigMap; applicationsOpen: HackathonBooleanMap; + ctfOpen?: HackathonBooleanMap; hackathonEnd: HackathonConfigMap; hackathonStart: HackathonConfigMap; hackathonWeekend: HackathonConfigMap; @@ -753,6 +754,8 @@ export interface Stamp { imgName?: string; lockedImgURL?: string; hackathon?: string; // for stamps unlockable in specific hackathons + /** raffle entries this stamp is worth; a stamp without it is worth 1 */ + points?: number; criteria?: FilterRowsSelection[]; isHidden: boolean; isTitle?: boolean; @@ -805,14 +808,18 @@ export interface RaffleWinner { } /** - * Document: /Hackathons/[hackathon]/Raffle/settings + * Sub-collection: /Hackathons/[hackathon]/CtfSolves, doc ID `{uid}_{challengeId}` * - * Which stamps count as raffle entries for this hackathon + * One hacker's solve of one CTF challenge, written only by the portal's submitCtfFlag function */ -export interface RaffleSettings { - eligibleStampIds: string[]; - lastModified?: Timestamp; - lastModifiedBy?: string; +export interface CtfSolve { + uid: string; + email: string; + challengeId: string; + rank: number; + points: number; + flagHash: string; + solvedAt?: Timestamp; } /** diff --git a/src/lib/points.test.ts b/src/lib/points.test.ts new file mode 100644 index 0000000..0b22842 --- /dev/null +++ b/src/lib/points.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; +import { stampPointValue } from "./points"; + +describe("stampPointValue", () => { + it("uses the stamp's points, rounded down", () => { + expect(stampPointValue({ points: 5 })).toBe(5); + expect(stampPointValue({ points: 2.9 })).toBe(2); + }); + + it("keeps 0 as 0", () => { + expect(stampPointValue({ points: 0 })).toBe(0); + expect(stampPointValue({ points: 0.5 })).toBe(0); + }); + + it("is 1 when points is missing, negative or not a finite number", () => { + expect(stampPointValue({})).toBe(1); + expect(stampPointValue({ points: -1 })).toBe(1); + expect(stampPointValue({ points: Number.NaN })).toBe(1); + expect(stampPointValue({ points: Number.POSITIVE_INFINITY })).toBe(1); + expect(stampPointValue({ points: "5" as unknown as number })).toBe(1); + }); +}); diff --git a/src/lib/points.ts b/src/lib/points.ts new file mode 100644 index 0000000..a24a6a0 --- /dev/null +++ b/src/lib/points.ts @@ -0,0 +1,13 @@ +import type { Stamp } from "@/lib/firebase/types"; + +/** + * A stamp's effective point value, where 1 point is 1 raffle entry + * @param stamp - the stamp, or just its `points` + * @returns `points` rounded down when it's a finite number of at least 0, otherwise 1, so a + * stamp saved before points existed is worth 1 + */ +export const stampPointValue = (stamp: Pick): number => { + const { points } = stamp; + if (typeof points !== "number" || !Number.isFinite(points) || points < 0) return 1; + return Math.floor(points); +}; diff --git a/src/lib/raffle.test.ts b/src/lib/raffle.test.ts new file mode 100644 index 0000000..ec91891 --- /dev/null +++ b/src/lib/raffle.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, it } from "vitest"; +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 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: "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: 1 }, + ]); + }); + + it("adds CTF points to stamp points for the same hacker", () => { + const entrants = buildRaffleEntrants( + [{ 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: 13 }, + ]); + }); + + it("adds hackers who only have CTF points, named from their application", () => { + 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 or non-finite CTF points and blank emails", () => { + const entrants = buildRaffleEntrants( + [{ email: " ", displayName: "Nobody", stampId: "s1" }], + values, + names, + new Map([ + ["carol@example.com", 0], + ["dave@example.com", Number.NaN], + ["", 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 }, + { 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([ + ["alice@example.com", 11], + ["bob@example.com", 2], + ]); + }); +}); diff --git a/src/lib/raffle.ts b/src/lib/raffle.ts index 801a30a..246bdb5 100644 --- a/src/lib/raffle.ts +++ b/src/lib/raffle.ts @@ -1,12 +1,15 @@ import type { + CtfSolve, HackerStampEntry, 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; @@ -14,29 +17,47 @@ export interface ApplicantName { } /** - * Aggregates collected stamps into one entrant per hacker, where each stamp 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 - * @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[] => { 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 || !Number.isFinite(count) || 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 +67,43 @@ export const buildRaffleEntrants = ( email, preferredName, lastName: applicant?.lastName ?? "", - entries: 1, + entries: count, }); + }; + + // 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()]; }; +/** + * 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; + if (typeof solve.points !== "number" || !Number.isFinite(solve.points)) continue; + points.set(email, (points.get(email) ?? 0) + solve.points); + } + + return points; +}; + /** * Sums every entrant's entries across the pool */ @@ -60,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/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 19306d3..9c8b812 100644 --- a/src/lib/stamps.ts +++ b/src/lib/stamps.ts @@ -1,4 +1,4 @@ -import type { StampCategory } from "@/lib/firebase/types"; +import type { Stamp, StampCategory } from "@/lib/firebase/types"; import { getHackathonType } from "@/lib/utils"; export const SOCIALS_NAME_FALLBACK = "User"; @@ -14,6 +14,27 @@ export const STAMP_CATEGORY_LABELS = Object.fromEntries( STAMP_CATEGORIES.map(({ value, label }) => [value, label]), ) as Record; +/** + * 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 * 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() {
@@ -187,16 +165,6 @@ function RafflePage() { onToggleEmails={setShowEmails} /> - - {selectedHackathon && ( - setStampsOpen(false)} - hackathon={selectedHackathon} - stamps={stamps} - eligibleStampIds={eligibleStampIds} - /> - )} ); } diff --git a/src/services/raffle.ts b/src/services/raffle.ts index a9d47ec..a87cad7 100644 --- a/src/services/raffle.ts +++ b/src/services/raffle.ts @@ -1,13 +1,18 @@ import { auth, db } from "@/lib/firebase/client"; import type { Applicant, + CtfSolve, RaffleEntrant, RafflePrize, - RaffleSettings, RaffleWinner, } from "@/lib/firebase/types"; -import { type ApplicantName, buildRaffleEntrants } 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, @@ -196,54 +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 ?? [] }); - }, - (error) => { - console.error("Error fetching raffle settings:", error); - callback({ eligibleStampIds: [] }); - onError?.(error); - }, - ); - -/** - * Saves which stamps count as raffle entries for a hackathon - * @param hackathon - hackathon ID - * @param eligibleStampIds - the IDs of the stamps that count as entries - */ -export const saveRaffleSettings = async (hackathon: string, eligibleStampIds: string[]) => { - try { - await setDoc( - doc(db, "Hackathons", hackathon, "Raffle", "settings"), - { - eligibleStampIds, - 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>(); @@ -279,27 +236,32 @@ const fetchApplicantNames = async ( }; /** - * Builds the raffle pool for a hackathon, where each eligible stamp a hacker collected is one entry + * Totals CTF points per hacker from the portal's CTF solves + * @param hackathon - hackathon ID + * @returns lowercased email to total CTF points + */ +export const fetchCtfPointsByEmail = async (hackathon: string): Promise> => { + const snapshot = await getDocs(collection(db, "Hackathons", hackathon, "CtfSolves")); + return sumCtfPointsByEmail(snapshot.docs.map((solveDoc) => solveDoc.data() as CtfSolve)); +}; + +/** + * 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 * @param hackathon - hackathon ID - * @param eligibleStampIds - the IDs of the stamps that count as entries * @param refreshNames - re-reads applicant names as well as stamps, for an explicit refresh - * @returns the raffle pool, one entrant per hacker + * @returns the raffle pool, one entrant per hacker with at least one point */ export const fetchRaffleEntrants = async ( hackathon: string, - eligibleStampIds: string[], refreshNames = false, ): Promise => { - if (eligibleStampIds.length === 0) return []; - - const [stampEntries, applicantNames] = await Promise.all([ + const [stampEntries, stamps, applicantNames, ctfPoints] = await Promise.all([ fetchHackersWithStamps(hackathon), + fetchStamps(), fetchApplicantNames(hackathon, refreshNames), + fetchCtfPointsByEmail(hackathon), ]); - const eligible = new Set(eligibleStampIds); - return buildRaffleEntrants( - stampEntries.filter((entry) => eligible.has(entry.stampId)), - applicantNames, - ); + 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