Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/components/features/auth/sign-in-button.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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) {
Expand Down
8 changes: 8 additions & 0 deletions src/components/features/raffle/raffle-draw-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -36,6 +38,7 @@ export function RaffleDrawPanel({
prizes,
winners,
entrants,
excludedOrganizers,
poolLoading,
poolError,
poolFetchedAt,
Expand Down Expand Up @@ -133,6 +136,11 @@ export function RaffleDrawPanel({
per point
</span>
)}
{excludedOrganizers > 0 && !poolLoading && !poolError && (
<span className="text-xs">
· {excludedOrganizers} organizer account{excludedOrganizers === 1 ? "" : "s"} excluded
</span>
)}
{poolFetchedAt && !poolLoading && (
<span className="text-xs">· as of {poolFetchedAt.toLocaleTimeString()}</span>
)}
Expand Down
9 changes: 8 additions & 1 deletion src/components/features/raffle/raffle-winner-dialog.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -34,6 +34,10 @@ export function RaffleWinnerDialog({
const [phase, setPhase] = useState<DrawPhase>("drawing");
const [shown, setShown] = useState<RaffleEntrant | null>(null);
const [winner, setWinner] = useState<RaffleEntrant | null>(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<boolean>(false);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

Expand All @@ -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;
Expand Down Expand Up @@ -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),
);
Expand Down
17 changes: 16 additions & 1 deletion src/components/features/raffle/raffle-winners-log.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,17 @@ export function RaffleWinnersLog({
Email
</TableHead>
)}
<TableHead className="h-10 px-2 font-medium text-muted-foreground text-sm">
Odds
</TableHead>
<TableHead className="h-10 w-8 px-2" />
</TableRow>
</TableHeader>
<TableBody>
{winners.length === 0 ? (
<TableRow className="hover:bg-transparent">
<TableCell
colSpan={showEmails ? 5 : 4}
colSpan={showEmails ? 6 : 5}
className="py-8 text-center text-muted-foreground text-sm"
>
No winners drawn yet. They'll show up here as you confirm each draw.
Expand All @@ -117,6 +120,18 @@ export function RaffleWinnersLog({
{winner.email}
</TableCell>
)}
<TableCell
className="px-2 py-2 text-muted-foreground text-sm"
title={
winner.poolSize
? `${winner.entryCount} of ${winner.poolEntries} entries across ${winner.poolSize} eligible hackers`
: undefined
}
>
{winner.poolEntries
? `${winner.entryCount} of ${winner.poolEntries}`
: `${winner.entryCount} entries`}
</TableCell>
<TableCell className="px-2 py-2">
<Confirm
variant="ghost"
Expand Down
4 changes: 4 additions & 0 deletions src/lib/firebase/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,10 @@ export interface RaffleWinner {
lastName: string;
email: string;
entryCount: number;
/** hackers eligible for this prize when the draw happened */
poolSize?: number;
/** entries they held between them, so the winner's odds were `entryCount / poolEntries` */
poolEntries?: number;
slot?: number;
drawnAt?: Timestamp;
drawnBy?: string;
Expand Down
127 changes: 126 additions & 1 deletion src/lib/raffle.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import type { Timestamp } from "firebase/firestore";
import { describe, expect, it } from "vitest";
import { buildRaffleEntrants, stampPointsById, sumCtfPointsByEmail, totalEntries } from "./raffle";
import {
buildRaffleEntrants,
defaultRaffleHackathon,
generateWinnersCSV,
isOrganizerEmail,
pickWeightedWinner,
splitOrganizers,
stampPointsById,
sumCtfPointsByEmail,
totalEntries,
} from "./raffle";

const names = new Map([
["alice@example.com", { preferredName: "Alice", lastName: "Applicant" }],
Expand Down Expand Up @@ -132,3 +143,117 @@ describe("sumCtfPointsByEmail", () => {
]);
});
});

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);
});

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("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, 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", () => {
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","","",""');
});
});
Loading
Loading