From 18b2dfe79866a959b628571ae1dfdfb699a2f1c7 Mon Sep 17 00:00:00 2001 From: aamoghS Date: Thu, 26 Nov 2026 21:43:25 -0500 Subject: [PATCH 01/15] feat(db): add discord_link table One row per user holding the Discord account of judges and volunteers, who have no participant row to hold it. Additive only. --- packages/db/src/schemas/hackathons.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/packages/db/src/schemas/hackathons.ts b/packages/db/src/schemas/hackathons.ts index 55aa3921..9f63be71 100644 --- a/packages/db/src/schemas/hackathons.ts +++ b/packages/db/src/schemas/hackathons.ts @@ -411,6 +411,33 @@ export const hackathonApplicationDrafts = pgTable( export type HackathonApplicationDraft = typeof hackathonApplicationDrafts.$inferSelect; +// The Discord account of someone who is not (or not only) a hacker. Judges and +// volunteers have no hackathon_participant row to hold the link, and the +// account is the person's, not an edition's, so it lives here, one row per +// user. A confirmed hacker's link is still mirrored on their participant row +// (it carries the Ramadan choice and the per-edition roster columns); the two +// are written together. Only the id and username Discord gave us are kept, +// never the access token. +export const discordLinks = pgTable( + "discord_link", + { + id: uuid("id").defaultRandom().primaryKey(), + userId: text("user_id") + .notNull() + .references(() => users.id, { onDelete: "cascade" }), + discordUserId: text("discord_user_id").notNull(), + discordUsername: text("discord_username").notNull(), + linkedAt: timestamp("linked_at", { withTimezone: true }).defaultNow().notNull(), + }, + (table) => [ + // One Discord account per person; the first also makes the link upsert safe. + uniqueIndex("discord_link_user_idx").on(table.userId), + uniqueIndex("discord_link_discord_user_idx").on(table.discordUserId), + ], +); + +export type DiscordLink = typeof discordLinks.$inferSelect; + // Event scheduling for hackathons export const hackathonEvents = pgTable( "hackathon_event", From 395de77cd0f84ffe5bc89626ce4f13e28cdf4064 Mon Sep 17 00:00:00 2001 From: aamoghS Date: Thu, 26 Nov 2026 21:54:49 -0500 Subject: [PATCH 02/15] feat(discord): link for judges and volunteers, hackers once they confirm One typed roles model (hacker, judge, volunteer) decides who may link and what the Linked Roles PUT carries. A hacker needs the I'm coming confirmation; approved judges and volunteers link without a registration, stored in discord_link. The callback returns each role to the page its card lives on. --- .../.internal-tests/discord-link.db.test.ts | 375 +++++++++++++++++- packages/api/src/routers/hackathon/discord.ts | 119 ++++-- packages/api/src/services/discord/config.ts | 4 - .../api/src/services/discord/discord.test.ts | 79 ++++ packages/api/src/services/discord/index.ts | 1 + packages/api/src/services/discord/link.ts | 253 ++++++++---- packages/api/src/services/discord/roles.ts | 245 ++++++++++++ .../(portal)/api/discord/callback/route.ts | 16 +- .../app/(portal)/api/discord/connect/route.ts | 5 +- sites/mainweb/lib/discord-route.ts | 18 +- 10 files changed, 971 insertions(+), 144 deletions(-) create mode 100644 packages/api/src/services/discord/roles.ts diff --git a/packages/api/src/.internal-tests/discord-link.db.test.ts b/packages/api/src/.internal-tests/discord-link.db.test.ts index b3fedf81..66d3aab8 100644 --- a/packages/api/src/.internal-tests/discord-link.db.test.ts +++ b/packages/api/src/.internal-tests/discord-link.db.test.ts @@ -5,8 +5,9 @@ import type * as DiscordSvc from "../services/discord"; /** * Real-Postgres test for the Discord link: balanced food groups, the - * Linked Roles callback with a mocked fetch (Discord is never called), the - * default edition for the verification URL, unlink, and the admin bits. + * Linked Roles callback with a mocked fetch (Discord is never called), who may + * link (confirmed hackers, approved judges, volunteers), the default edition + * for the verification URL, unlink, and the admin bits. * Needs TEST_DATABASE_URL (disposable; never Neon or production). */ const URL = process.env.TEST_DATABASE_URL; @@ -67,6 +68,8 @@ describe.skipIf(!URL)("discord link against a real database", () => { hackathonId, userId, registrationStatus: "approved", + // Said "I'm coming": the Discord step waits for it. + attendanceConfirmedAt: new Date(), ramadanFasting: "Yes", ...extra, }) @@ -220,7 +223,13 @@ describe.skipIf(!URL)("discord link against a real database", () => { expect(body).toEqual({ platform_name: "Hacklytics", platform_username: "Ada L", - metadata: { accepted: 1, food_group: number, ramadan: 1 }, + metadata: { + accepted: 1, + food_group: number, + ramadan: 1, + judge: 0, + volunteer: 0, + }, }); expect(stored).toMatchObject({ discordUserId: `d-happy-${suffix}`, @@ -270,6 +279,355 @@ describe.skipIf(!URL)("discord link against a real database", () => { }); }); + describe("who may link: hackers who confirmed, approved judges, volunteers", () => { + const makeJudge = async (hackathonId: string, userId: string, isActive = true) => { + const [judge] = await S.db! + .insert(S.judges) + .values({ userId, hackathonId, name: "Judge", email: `${userId}@example.test`, isActive }) + .returning(); + return judge!; + }; + const makeVolunteer = async (userId: string, extra: Record = {}) => { + await S.db!.insert(S.admins).values({ userId, role: "volunteer", ...extra }); + }; + const sent = (f: ReturnType) => + JSON.parse(f.calls[2]!.init!.body as string).metadata; + const linkRow = async (userId: string) => + ( + await S.db! + .select() + .from(S.discordLinks) + .where(ops.eq(S.discordLinks.userId, userId)) + )[0]; + + it("an accepted hacker who has not said they are coming cannot link or get an invite", async () => { + const h = await makeHackathon("rsvp"); + const u = await makeUser("rsvp"); + const p = await makeParticipant(h.id, u, { attendanceConfirmedAt: null }); + const f = discordFetch(); + expect(await link(u, h.id, f, null, "invite")).toEqual({ + ok: false, + reason: "not_accepted", + }); + expect(f.calls).toHaveLength(0); + expect(await svc.resolveConnectTarget(S.db as any, u, h.id)).toBeNull(); + expect(await svc.resolveConnectTarget(S.db as any, u, null)).toBeNull(); + + // The portal still shows them their flower (it is their meal wave) and + // asks for the answer. + const mine = await hackathonAs(u).myDiscord({ hackathonId: h.id }); + expect(mine).toMatchObject({ + eligible: false, + awaitingConfirmation: true, + roles: { hacker: false, judge: false, volunteer: false }, + linked: false, + }); + expect(mine.foodGroup?.key).toBe((await row(p.id)).foodGroup); + expect(await linkRow(u)).toBeUndefined(); + }); + + it("saying they are coming opens the step, and the metadata says accepted with their flower", async () => { + const h = await makeHackathon("rsvp-yes"); + const u = await makeUser("rsvp-yes"); + const p = await makeParticipant(h.id, u, { attendanceConfirmedAt: null }); + expect((await hackathonAs(u).myDiscord({ hackathonId: h.id })).eligible).toBe(false); + + await hackathonAs(u).confirmAttendance({ hackathonId: h.id }); + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: true, + awaitingConfirmation: false, + roles: { hacker: true, judge: false, volunteer: false }, + }); + + const f = discordFetch({ meId: `d-rsvp-${suffix}` }); + expect(await link(u, h.id, f)).toMatchObject({ ok: true, home: "hackathon" }); + const number = svc.foodGroupByKey((await row(p.id)).foodGroup)!.number; + expect(sent(f)).toEqual({ + accepted: 1, + food_group: number, + ramadan: 0, + judge: 0, + volunteer: 0, + }); + }); + + it("a hacker who is already checked in is through the door without the answer", async () => { + const h = await makeHackathon("rsvp-door"); + const u = await makeUser("rsvp-door"); + await makeParticipant(h.id, u, { + registrationStatus: "checked_in", + attendanceConfirmedAt: null, + }); + expect(await link(u, h.id, discordFetch({ meId: `d-door-${suffix}` }))).toMatchObject({ + ok: true, + }); + }); + + it("an approved judge with no registration can link and gets judge and no hacker values", async () => { + const h = await makeHackathon("judge"); + const u = await makeUser("judge"); + await makeJudge(h.id, u); + const f = discordFetch({ meId: `d-judge-${suffix}` }); + expect(await link(u, h.id, f, null, "invite")).toMatchObject({ + ok: true, + then: "invite", + home: "judge", + username: "ada", + }); + expect(sent(f)).toEqual({ accepted: 0, judge: 1, volunteer: 0 }); + + const stored = await linkRow(u); + expect(stored).toMatchObject({ discordUserId: `d-judge-${suffix}`, discordUsername: "ada" }); + expect(JSON.stringify(stored)).not.toContain("tok-user"); + const participants = await S.db! + .select() + .from(S.hackathonParticipants) + .where(ops.eq(S.hackathonParticipants.userId, u)); + expect(participants).toHaveLength(0); + + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: true, + roles: { hacker: false, judge: true, volunteer: false }, + linked: true, + username: "ada", + foodGroup: null, + fasting: false, + }); + // Updating roles again keeps the one row. + expect(await link(u, h.id, discordFetch({ meId: `d-judge-${suffix}` }))).toMatchObject({ ok: true }); + const again = await S.db! + .select() + .from(S.discordLinks) + .where(ops.eq(S.discordLinks.userId, u)); + expect(again).toHaveLength(1); + + await hackathonAs(u).unlinkDiscord({ hackathonId: h.id }); + expect(await linkRow(u)).toBeUndefined(); + expect((await hackathonAs(u).myDiscord({ hackathonId: h.id })).linked).toBe(false); + }); + + it("a judge who is not approved cannot link", async () => { + const h = await makeHackathon("judge-no"); + const u = await makeUser("judge-no"); + await makeJudge(h.id, u, false); + const f = discordFetch(); + expect(await link(u, h.id, f)).toEqual({ ok: false, reason: "not_accepted" }); + expect(f.calls).toHaveLength(0); + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: false, + roles: { judge: false }, + }); + }); + + it("a volunteer links while an edition is open or live, with volunteer set", async () => { + const h = await makeHackathon("vol"); + const u = await makeUser("vol"); + await makeVolunteer(u); + const f = discordFetch({ meId: `d-vol-${suffix}` }); + expect(await link(u, h.id, f)).toMatchObject({ ok: true, home: "scan" }); + expect(sent(f)).toEqual({ accepted: 0, judge: 0, volunteer: 1 }); + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: true, + roles: { hacker: false, judge: false, volunteer: true }, + linked: true, + }); + }); + + it("a volunteer has no step on an edition that is not open or live", async () => { + const u = await makeUser("vol-status"); + await makeVolunteer(u); + for (const status of ["draft", "announced", "completed", "cancelled"]) { + const h = await makeHackathon(`vol-${status}`, { status }); + expect(await svc.resolveConnectTarget(S.db as any, u, h.id)).toBeNull(); + } + for (const status of ["open", "closed", "in_progress"]) { + const h = await makeHackathon(`vol-${status}`, { status }); + expect((await svc.resolveConnectTarget(S.db as any, u, h.id))?.roles.volunteer).toBe(true); + } + }); + + it("an inactive or expired volunteer, and full staff, are not volunteers", async () => { + const h = await makeHackathon("vol-no"); + const inactive = await makeUser("vol-inactive"); + await makeVolunteer(inactive, { isActive: false }); + const expired = await makeUser("vol-expired"); + await makeVolunteer(expired, { expiresAt: new Date(Date.now() - 60_000) }); + const staff = await makeUser("vol-staff"); + await S.db!.insert(S.admins).values({ userId: staff, role: "admin" }); + for (const u of [inactive, expired, staff]) { + expect(await svc.resolveConnectTarget(S.db as any, u, h.id)).toBeNull(); + } + }); + + it("the default edition for a volunteer is the newest one that is open or live", async () => { + const u = await makeUser("vol-default"); + await makeVolunteer(u); + await makeHackathon("vd-old", { + status: "completed", + startDate: new Date("2026-02-01T00:00:00Z"), + endDate: new Date("2026-02-03T00:00:00Z"), + }); + const live = await makeHackathon("vd-live", { + startDate: new Date("2033-02-01T00:00:00Z"), + endDate: new Date("2033-02-03T00:00:00Z"), + }); + await makeHackathon("vd-next", { + status: "announced", + startDate: new Date("2034-02-01T00:00:00Z"), + endDate: new Date("2034-02-03T00:00:00Z"), + }); + expect((await svc.resolveConnectTarget(S.db as any, u, null))?.hackathon.id).toBe(live.id); + const mine = await hackathonAs(u).myDiscord({}); + expect(mine.hackathon?.id).toBe(live.id); + expect(mine.roles.volunteer).toBe(true); + }); + + it("a judge who is also a confirmed hacker gets both, and both stores hold the link", async () => { + const h = await makeHackathon("both"); + const u = await makeUser("both"); + const p = await makeParticipant(h.id, u); + await makeJudge(h.id, u); + const f = discordFetch({ meId: `d-both-${suffix}` }); + expect(await link(u, h.id, f, 1)).toMatchObject({ ok: true, home: "hackathon" }); + const number = svc.foodGroupByKey((await row(p.id)).foodGroup)!.number; + expect(sent(f)).toEqual({ + accepted: 1, + food_group: number, + ramadan: 1, + judge: 1, + volunteer: 0, + }); + expect(await row(p.id)).toMatchObject({ discordUserId: `d-both-${suffix}`, ramadanRoleOptIn: true }); + expect(await linkRow(u)).toMatchObject({ discordUserId: `d-both-${suffix}` }); + }); + + it("a judge who is an accepted hacker not yet confirmed gets judge only, and the card asks for the answer", async () => { + const h = await makeHackathon("judge-unconfirmed"); + const u = await makeUser("judge-unconfirmed"); + const p = await makeParticipant(h.id, u, { attendanceConfirmedAt: null }); + await makeJudge(h.id, u); + const f = discordFetch({ meId: `d-ju-${suffix}` }); + expect(await link(u, h.id, f)).toMatchObject({ ok: true, home: "judge" }); + expect(sent(f)).toEqual({ accepted: 0, judge: 1, volunteer: 0 }); + // The registration is left alone: no flower role, no mirrored link. + expect((await row(p.id)).discordUserId).toBeNull(); + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: true, + awaitingConfirmation: true, + linked: true, + }); + }); + + it("a judge and a volunteer at once get both", async () => { + const h = await makeHackathon("jv"); + const u = await makeUser("jv"); + await makeJudge(h.id, u); + await makeVolunteer(u); + const f = discordFetch({ meId: `d-jv-${suffix}` }); + expect(await link(u, h.id, f)).toMatchObject({ ok: true }); + expect(sent(f)).toEqual({ accepted: 0, judge: 1, volunteer: 1 }); + }); + + it("un-confirming or withdrawing leaves an existing link in place", async () => { + const h = await makeHackathon("keeplink"); + const u = await makeUser("keeplink"); + const p = await makeParticipant(h.id, u); + expect(await link(u, h.id, discordFetch({ meId: `d-keep2-${suffix}` }))).toMatchObject({ ok: true }); + + await S.db! + .update(S.hackathonParticipants) + .set({ attendanceConfirmedAt: null }) + .where(ops.eq(S.hackathonParticipants.id, p.id)); + const after = await hackathonAs(u).myDiscord({ hackathonId: h.id }); + expect(after).toMatchObject({ + eligible: false, + awaitingConfirmation: true, + linked: true, + username: "ada", + }); + expect(await row(p.id)).toMatchObject({ discordUserId: `d-keep2-${suffix}` }); + + await S.db! + .delete(S.hackathonParticipants) + .where(ops.eq(S.hackathonParticipants.id, p.id)); + expect(await linkRow(u)).toMatchObject({ discordUserId: `d-keep2-${suffix}` }); + }); + + it("a hacker linked before the confirmation step keeps the link", async () => { + const h = await makeHackathon("legacy"); + const u = await makeUser("legacy"); + await makeParticipant(h.id, u, { + attendanceConfirmedAt: null, + discordUserId: `d-legacy-${suffix}`, + discordUsername: "old", + discordLinkedAt: new Date(), + }); + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: false, + awaitingConfirmation: true, + linked: true, + username: "old", + }); + }); + + it("refuses a Discord account another person already holds, whichever store holds it", async () => { + const h = await makeHackathon("held"); + const judgeA = await makeUser("held-a"); + const judgeB = await makeUser("held-b"); + await makeJudge(h.id, judgeA); + await makeJudge(h.id, judgeB); + const shared = `d-held-${suffix}`; + expect(await link(judgeA, h.id, discordFetch({ meId: shared }))).toMatchObject({ ok: true }); + const f = discordFetch({ meId: shared }); + expect(await link(judgeB, h.id, f)).toMatchObject({ ok: false, reason: "already_linked" }); + expect(f.calls).toHaveLength(2); + expect(await linkRow(judgeB)).toBeUndefined(); + + // A hacker linked before this table existed holds the account on the + // registration alone. + const hackerAccount = `d-held-hacker-${suffix}`; + const hacker = await makeUser("held-h"); + await makeParticipant(h.id, hacker, { + discordUserId: hackerAccount, + discordUsername: "old", + discordLinkedAt: new Date(), + }); + const judgeC = await makeUser("held-c"); + await makeJudge(h.id, judgeC); + expect(await link(judgeC, h.id, discordFetch({ meId: hackerAccount }))).toMatchObject({ + ok: false, + reason: "already_linked", + }); + expect(await linkRow(judgeC)).toBeUndefined(); + }); + + it("rolls back a first link, and restores a previous one, when Discord refuses the roles", async () => { + const h = await makeHackathon("rollback"); + const u = await makeUser("rollback"); + await makeJudge(h.id, u); + expect(await link(u, h.id, discordFetch({ meId: `d-rb1-${suffix}`, put: 500 }))).toMatchObject({ + ok: false, + reason: "discord_error", + home: "judge", + }); + expect(await linkRow(u)).toBeUndefined(); + + expect(await link(u, h.id, discordFetch({ meId: `d-rb1-${suffix}` }))).toMatchObject({ ok: true }); + expect(await link(u, h.id, discordFetch({ meId: `d-rb2-${suffix}`, put: 403 }))).toMatchObject({ + ok: false, + reason: "discord_denied", + }); + expect(await linkRow(u)).toMatchObject({ discordUserId: `d-rb1-${suffix}` }); + }); + + it("the signed state stays bound to the user it was made for", () => { + const secret = "s".repeat(40); + const token = svc.signState({ u: "judge-1", h: "hack-1", r: null, t: "portal" }, secret); + expect(svc.verifyState(token, secret, { userId: "judge-1" })).toMatchObject({ u: "judge-1" }); + expect(svc.verifyState(token, secret, { userId: "judge-2" })).toBeNull(); + }); + }); + it("maps Discord errors and leaves nothing linked", async () => { const h = await makeHackathon("errors"); const u = await makeUser("errors"); @@ -331,7 +689,7 @@ describe.skipIf(!URL)("discord link against a real database", () => { await makeParticipant(current.id, u); await makeParticipant(pending.id, u, { registrationStatus: "pending" }); const target = await svc.resolveConnectTarget(S.db as any, u, null); - expect(target?.hackathon?.id).toBe(current.id); + expect(target?.hackathon.id).toBe(current.id); expect(await svc.resolveConnectTarget(S.db as any, u, pending.id)).toBeNull(); }); @@ -346,9 +704,12 @@ describe.skipIf(!URL)("discord link against a real database", () => { expect(before.foodGroup?.name).toBeTruthy(); expect(before.fasting).toBe(true); expect((await row(p.id)).foodGroup).toBe(before.foodGroup?.key); - expect( - await hackathonAs(stranger).myDiscord({ hackathonId: h.id }), - ).toEqual({ eligible: false }); + expect(await hackathonAs(stranger).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: false, + awaitingConfirmation: false, + foodGroup: null, + linked: false, + }); await link(u, h.id, discordFetch({ meId: `d-my-${suffix}` }), 1); const linked = await hackathonAs(u).myDiscord({ hackathonId: h.id }); diff --git a/packages/api/src/routers/hackathon/discord.ts b/packages/api/src/routers/hackathon/discord.ts index 83a7f6af..5da2868d 100644 --- a/packages/api/src/routers/hackathon/discord.ts +++ b/packages/api/src/routers/hackathon/discord.ts @@ -1,73 +1,106 @@ -// The hacker's side of the Discord link: status (with the lazily assigned food -// group) and unlink. Linking itself is the OAuth route in sites/mainweb. +// The Discord link as the signed-in person sees it: which roles they hold, the +// link status (with the lazily assigned flower) and unlink. Linking itself is +// the OAuth route in sites/mainweb. import { z } from "zod"; import { and, eq } from "drizzle-orm"; import { createTRPCRouter, protectedProcedure } from "../../trpc"; -import { hackathonParticipants } from "@query/db"; +import { discordLinks, hackathonParticipants } from "@query/db"; import type { DrizzleDB } from "@query/db"; import { discordConfig, + discordContext, ensureFoodGroup, foodGroupByKey, - isDiscordEligible, + hasDiscordRole, + isAcceptedHacker, + isConfirmedHacker, + NO_ROLES, + storedLink, } from "../../services/discord"; export const hackathonDiscordRouter = createTRPCRouter({ + // With a hackathon id, that edition. Without one (the judge page and the + // check-in desk have none), the newest live edition in which the person + // holds a role. `eligible` means a role applies and they may link. A hacker + // who is accepted but has not said "I'm coming" is not eligible yet: + // `awaitingConfirmation` is what tells the portal to ask for it. Their + // flower is shown either way, because it is also their meal wave. myDiscord: protectedProcedure - .input(z.object({ hackathonId: z.string().uuid() })) + .input(z.object({ hackathonId: z.string().uuid().optional() })) .query(async ({ ctx, input }) => { const db = ctx.db as DrizzleDB; - const row = await db.query.hackathonParticipants.findFirst({ - where: { hackathonId: input.hackathonId, userId: ctx.userId as string }, - columns: { - id: true, - registrationStatus: true, - ramadanFasting: true, - ramadanRoleOptIn: true, - discordUsername: true, - discordLinkedAt: true, - foodGroup: true, - }, - }); - if (!row || !isDiscordEligible(row.registrationStatus)) { - return { eligible: false as const }; + const userId = ctx.userId as string; + const context = await discordContext( + db, + userId, + input.hackathonId ?? null, + ); + const enabled = !!discordConfig(); + if (!context) { + return { + hackathon: null, + enabled, + eligible: false, + roles: NO_ROLES, + awaitingConfirmation: false, + linked: false, + username: null, + foodGroup: null, + fasting: false, + ramadanOptIn: false, + }; } + + const { hackathon, participant, roles } = context; + const accepted = !!participant && isAcceptedHacker(participant.registrationStatus); // The group exists whether or not they ever link: it is their meal wave. const foodGroup = - foodGroupByKey(row.foodGroup) ?? - foodGroupByKey(await ensureFoodGroup(db, input.hackathonId, row.id)); + accepted && participant + ? (foodGroupByKey(participant.foodGroup) ?? + foodGroupByKey(await ensureFoodGroup(db, hackathon.id, participant.id))) + : null; + const link = await storedLink(db, userId, participant); return { - eligible: true as const, - enabled: !!discordConfig(), - linked: !!row.discordLinkedAt, - username: row.discordUsername, + hackathon, + enabled, + eligible: hasDiscordRole(roles), + roles, + awaitingConfirmation: !!participant && accepted && !isConfirmedHacker(participant), + linked: !!link, + username: link?.username ?? null, foodGroup, - fasting: row.ramadanFasting === "Yes", - ramadanOptIn: row.ramadanRoleOptIn ?? false, + fasting: roles.hacker && participant?.ramadanFasting === "Yes", + ramadanOptIn: (roles.hacker && participant?.ramadanRoleOptIn) || false, }; }), - // Clears what we stored. The Discord connection itself lives in the user's + // Clears what we stored: the person's link and, for a hacker, the copy on + // their registration. The Discord connection itself lives in the user's // Discord settings; we hold no token and cannot remove it. unlinkDiscord: protectedProcedure .input(z.object({ hackathonId: z.string().uuid() })) .mutation(async ({ ctx, input }) => { - await (ctx.db as DrizzleDB) - .update(hackathonParticipants) - .set({ - discordUserId: null, - discordUsername: null, - discordLinkedAt: null, - ramadanRoleOptIn: null, - updatedAt: new Date(), - }) - .where( - and( - eq(hackathonParticipants.hackathonId, input.hackathonId), - eq(hackathonParticipants.userId, ctx.userId as string), - ), - ); + const db = ctx.db as DrizzleDB; + const userId = ctx.userId as string; + await db.transaction(async (tx) => { + await tx + .update(hackathonParticipants) + .set({ + discordUserId: null, + discordUsername: null, + discordLinkedAt: null, + ramadanRoleOptIn: null, + updatedAt: new Date(), + }) + .where( + and( + eq(hackathonParticipants.hackathonId, input.hackathonId), + eq(hackathonParticipants.userId, userId), + ), + ); + await tx.delete(discordLinks).where(eq(discordLinks.userId, userId)); + }); return { ok: true }; }), }); diff --git a/packages/api/src/services/discord/config.ts b/packages/api/src/services/discord/config.ts index 8aa13309..af85fecb 100644 --- a/packages/api/src/services/discord/config.ts +++ b/packages/api/src/services/discord/config.ts @@ -28,10 +28,6 @@ export function foodGroupByKey( return FOOD_GROUPS.find((g) => g.key === key) ?? null; } -/** Statuses that may link: accepted, or already through the door. */ -export const isDiscordEligible = (status: string | null | undefined) => - status === "approved" || status === "checked_in"; - export type DiscordConfig = { clientId: string; clientSecret: string; diff --git a/packages/api/src/services/discord/discord.test.ts b/packages/api/src/services/discord/discord.test.ts index 7da70c53..2ea3a76c 100644 --- a/packages/api/src/services/discord/discord.test.ts +++ b/packages/api/src/services/discord/discord.test.ts @@ -2,6 +2,13 @@ import { describe, expect, it, vi } from "vitest"; import { discordConfig, FOOD_GROUPS, foodGroupByKey } from "./config"; import { autoAssignFoodGroups, pickFoodGroup } from "./food-group"; import { ramadanFlag } from "./link"; +import { + hasDiscordRole, + isConfirmedHacker, + NO_ROLES, + roleMetadata, + rolesFor, +} from "./roles"; import { signState, verifyState, STATE_TTL_MS } from "./state"; const SECRET = "x".repeat(40); @@ -100,3 +107,75 @@ describe("ramadanFlag and config", () => { }); }); }); + +describe("discord roles", () => { + const at = new Date("2027-02-01T00:00:00Z"); + const hacker = (registrationStatus: string, attendanceConfirmedAt: Date | null) => ({ + registrationStatus, + attendanceConfirmedAt, + }); + + it("makes a hacker eligible only once they said they are coming, or are checked in", () => { + expect(isConfirmedHacker(hacker("approved", null))).toBe(false); + expect(isConfirmedHacker(hacker("approved", at))).toBe(true); + expect(isConfirmedHacker(hacker("checked_in", null))).toBe(true); + for (const status of ["pending", "waitlisted", "rejected"]) { + expect(isConfirmedHacker(hacker(status, at))).toBe(false); + } + }); + + it("holds each role independently, and any combination", () => { + const base = { participant: null, judge: false, volunteer: false, hackathonStatus: "open" }; + expect(rolesFor(base)).toEqual(NO_ROLES); + expect(rolesFor({ ...base, judge: true })).toEqual({ ...NO_ROLES, judge: true }); + expect(rolesFor({ ...base, volunteer: true })).toEqual({ ...NO_ROLES, volunteer: true }); + expect( + rolesFor({ ...base, participant: hacker("approved", at), judge: true, volunteer: true }), + ).toEqual({ hacker: true, judge: true, volunteer: true }); + expect( + rolesFor({ ...base, participant: hacker("approved", null), judge: true }), + ).toEqual({ hacker: false, judge: true, volunteer: false }); + }); + + it("gives volunteers a role only while the edition is open or live", () => { + const volunteerIn = (hackathonStatus: string) => + rolesFor({ participant: null, judge: false, volunteer: true, hackathonStatus }).volunteer; + for (const status of ["open", "closed", "in_progress"]) expect(volunteerIn(status)).toBe(true); + for (const status of ["draft", "announced", "completed", "cancelled"]) { + expect(volunteerIn(status)).toBe(false); + } + }); + + it("reports whether anyone holds a role", () => { + expect(hasDiscordRole(NO_ROLES)).toBe(false); + expect(hasDiscordRole({ ...NO_ROLES, volunteer: true })).toBe(true); + }); + + it("sends accepted, the flower and Ramadan to hackers only, and judge and volunteer always", () => { + const flower = { foodGroup: 4, ramadan: 1 as const }; + expect(roleMetadata({ hacker: true, judge: false, volunteer: false }, flower)).toEqual({ + accepted: 1, + food_group: 4, + ramadan: 1, + judge: 0, + volunteer: 0, + }); + expect(roleMetadata({ hacker: false, judge: true, volunteer: false }, null)).toEqual({ + accepted: 0, + judge: 1, + volunteer: 0, + }); + expect(roleMetadata({ hacker: false, judge: false, volunteer: true }, null)).toEqual({ + accepted: 0, + judge: 0, + volunteer: 1, + }); + expect(roleMetadata({ hacker: true, judge: true, volunteer: true }, flower)).toEqual({ + accepted: 1, + food_group: 4, + ramadan: 1, + judge: 1, + volunteer: 1, + }); + }); +}); diff --git a/packages/api/src/services/discord/index.ts b/packages/api/src/services/discord/index.ts index d6be4d8a..9694eed1 100644 --- a/packages/api/src/services/discord/index.ts +++ b/packages/api/src/services/discord/index.ts @@ -1,4 +1,5 @@ export * from "./config"; export * from "./state"; export * from "./food-group"; +export * from "./roles"; export * from "./link"; diff --git a/packages/api/src/services/discord/link.ts b/packages/api/src/services/discord/link.ts index d57744a1..2854c44f 100644 --- a/packages/api/src/services/discord/link.ts +++ b/packages/api/src/services/discord/link.ts @@ -1,9 +1,11 @@ -import { and, eq } from "drizzle-orm"; -import { hackathonParticipants } from "@query/db"; +import { and, eq, ne } from "drizzle-orm"; +import { discordLinks, hackathonParticipants } from "@query/db"; import type { DrizzleDB } from "@query/db"; -import { foodGroupByKey, isDiscordEligible } from "./config"; +import { foodGroupByKey } from "./config"; import type { DiscordConfig } from "./config"; import { ensureFoodGroup } from "./food-group"; +import { discordContext, hasDiscordRole, roleMetadata } from "./roles"; +import type { DiscordParticipant } from "./roles"; import type { DiscordState } from "./state"; import { isUniqueViolation } from "../../middleware/db-errors"; @@ -19,66 +21,111 @@ type LinkErrorReason = type HackathonRef = { id: string; name: string }; +/** + * Where the person goes back to: the hackathon page for a hacker, the judge + * page for a judge, the check-in desk for a volunteer. Each is where that + * role's Discord card lives. + */ +export type LinkHome = "hackathon" | "judge" | "scan"; + type LinkResult = | { ok: true; then: DiscordState["t"]; hackathon: HackathonRef; + home: LinkHome; username: string; } | { ok: false; reason: LinkErrorReason; hackathon?: HackathonRef; + home?: LinkHome; retryAfter?: number; }; /** - * The participant a connect request is for. With a hackathon id, that one; - * without (Discord's Linked Roles verification URL sends none), the newest - * edition that is not cancelled or over which the user is accepted to. - * Null when they are not accepted there. + * The edition a connect request is for, with what the person holds there. + * With a hackathon id, that one; without (Discord's Linked Roles verification + * URL sends none), the newest edition that is not cancelled or over in which + * they hold a role. Null when they hold none: not a confirmed hacker, an + * approved judge or a volunteer. */ export async function resolveConnectTarget( db: DrizzleDB, userId: string, hackathonId: string | null, ) { - if (hackathonId) { - const row = await db.query.hackathonParticipants.findFirst({ - where: { hackathonId, userId }, - with: { hackathon: { columns: { id: true, name: true } } }, - }); - return row && isDiscordEligible(row.registrationStatus) ? row : null; - } - const rows = await db.query.hackathonParticipants.findMany({ - where: { userId }, - with: { - hackathon: { - columns: { id: true, name: true, status: true, startDate: true }, - }, - }, - }); - const live = rows - .filter( - (r) => - isDiscordEligible(r.registrationStatus) && - r.hackathon && - r.hackathon.status !== "cancelled" && - r.hackathon.status !== "completed", - ) - .sort( - (a, b) => - new Date(b.hackathon!.startDate).getTime() - - new Date(a.hackathon!.startDate).getTime(), - ); - return live[0] ?? null; + const context = await discordContext(db, userId, hackathonId); + return context && hasDiscordRole(context.roles) ? context : null; } /** The Ramadan flag Discord receives: opted in AND fasting is "Yes". */ export const ramadanFlag = (optIn: boolean, fasting: string | null | undefined) => optIn && fasting === "Yes" ? 1 : 0; +/** + * The Discord account stored for this person: the one on their participant + * row (where hackers linked before judges and volunteers could), else their + * own link row. + */ +export async function storedLink( + db: DrizzleDB, + userId: string, + participant: Pick< + DiscordParticipant, + "discordUsername" | "discordLinkedAt" + > | null, +): Promise<{ username: string; linkedAt: Date } | null> { + if (participant?.discordLinkedAt && participant.discordUsername) { + return { + username: participant.discordUsername, + linkedAt: participant.discordLinkedAt, + }; + } + const [row] = await db + .select({ + username: discordLinks.discordUsername, + linkedAt: discordLinks.linkedAt, + }) + .from(discordLinks) + .where(eq(discordLinks.userId, userId)) + .limit(1); + return row ?? null; +} + +/** Whether somebody else already holds this Discord account, in either store. */ +async function heldByAnother( + db: DrizzleDB, + discordUserId: string, + userId: string, + hackathonId: string, +): Promise { + const [link] = await db + .select({ id: discordLinks.id }) + .from(discordLinks) + .where( + and( + eq(discordLinks.discordUserId, discordUserId), + ne(discordLinks.userId, userId), + ), + ) + .limit(1); + if (link) return true; + const [participant] = await db + .select({ id: hackathonParticipants.id }) + .from(hackathonParticipants) + .where( + and( + eq(hackathonParticipants.hackathonId, hackathonId), + eq(hackathonParticipants.discordUserId, discordUserId), + ne(hackathonParticipants.userId, userId), + ), + ) + .limit(1); + return !!participant; +} + function failureFor(status: number): LinkErrorReason { if (status === 429) return "rate_limited"; if (status === 401 || status === 403) return "discord_denied"; @@ -126,16 +173,18 @@ export async function completeLink(opts: { const { db, config, state, code } = opts; const doFetch = opts.fetchImpl ?? fetch; - const participant = await resolveConnectTarget(db, state.u, state.h); - if (!participant) return { ok: false, reason: "not_accepted" }; - const hackathon: HackathonRef = { - id: participant.hackathon!.id, - name: participant.hackathon!.name, - }; + const target = await resolveConnectTarget(db, state.u, state.h); + if (!target) return { ok: false, reason: "not_accepted" }; + const { hackathon, participant, roles } = target; + const home: LinkHome = roles.hacker + ? "hackathon" + : roles.judge + ? "judge" + : "scan"; const fail = ( reason: LinkErrorReason, extra: { retryAfter?: number } = {}, - ): LinkResult => ({ ok: false, reason, hackathon, ...extra }); + ): LinkResult => ({ ok: false, reason, hackathon, home, ...extra }); const tokenRes = await doFetch(`${API}/oauth2/token`, { method: "POST", @@ -172,41 +221,80 @@ export async function completeLink(opts: { if (!me.id || !me.username) return fail("discord_error"); const displayName = me.global_name || me.username; - // The food group first, so the metadata always has one. - const groupKey = await ensureFoodGroup(db, hackathon.id, participant.id); - const optIn = - state.r === null - ? (participant.ramadanRoleOptIn ?? false) - : state.r === 1; - const ramadan = ramadanFlag(optIn, participant.ramadanFasting); - const before = { + if (await heldByAnother(db, me.id, state.u, hackathon.id)) { + return fail("already_linked"); + } + + // Only a confirmed hacker has a flower and a Ramadan choice. The flower is + // assigned first, so the metadata always has one. + let hacker: { foodGroup: number; ramadan: 0 | 1 } | null = null; + if (roles.hacker && participant) { + const groupKey = await ensureFoodGroup(db, hackathon.id, participant.id); + const optIn = + state.r === null + ? (participant.ramadanRoleOptIn ?? false) + : state.r === 1; + hacker = { + foodGroup: foodGroupByKey(groupKey)?.number ?? 0, + ramadan: ramadanFlag(optIn, participant.ramadanFasting), + }; + } + + const [priorLink] = await db + .select() + .from(discordLinks) + .where(eq(discordLinks.userId, state.u)) + .limit(1); + const before = participant && { discordUserId: participant.discordUserId, discordUsername: participant.discordUsername, discordLinkedAt: participant.discordLinkedAt, ramadanRoleOptIn: participant.ramadanRoleOptIn, }; + const linkedAt = new Date(); try { - await db - .update(hackathonParticipants) - .set({ - discordUserId: me.id, - discordUsername: me.username, - discordLinkedAt: new Date(), - ramadanRoleOptIn: ramadan === 1, - updatedAt: new Date(), - }) - .where( - and( - eq(hackathonParticipants.id, participant.id), - eq(hackathonParticipants.hackathonId, hackathon.id), - ), - ); + await db.transaction(async (tx) => { + await tx + .insert(discordLinks) + .values({ + userId: state.u, + discordUserId: me.id!, + discordUsername: me.username!, + linkedAt, + }) + .onConflictDoUpdate({ + target: discordLinks.userId, + set: { + discordUserId: me.id!, + discordUsername: me.username!, + linkedAt, + }, + }); + // A confirmed hacker's link is mirrored on their participant row, which + // carries the Ramadan choice and the roster columns. + if (hacker && participant) { + await tx + .update(hackathonParticipants) + .set({ + discordUserId: me.id, + discordUsername: me.username, + discordLinkedAt: linkedAt, + ramadanRoleOptIn: hacker.ramadan === 1, + updatedAt: linkedAt, + }) + .where( + and( + eq(hackathonParticipants.id, participant.id), + eq(hackathonParticipants.hackathonId, hackathon.id), + ), + ); + } + }); } catch (error) { if (isUniqueViolation(error)) return fail("already_linked"); throw error; } - const group = foodGroupByKey(groupKey); const putRes = await doFetch( `${API}/users/@me/applications/${config.clientId}/role-connection`, { @@ -218,21 +306,33 @@ export async function completeLink(opts: { body: JSON.stringify({ platform_name: "Hacklytics", platform_username: displayName, - metadata: { - accepted: 1, - food_group: group?.number ?? 0, - ramadan, - }, + metadata: roleMetadata(roles, hacker), }), }, ); if (!putRes.ok) { // Roll the link back: a stored link whose roles never reached Discord // would read as done. - await db - .update(hackathonParticipants) - .set(before) - .where(eq(hackathonParticipants.id, participant.id)); + await db.transaction(async (tx) => { + if (priorLink) { + await tx + .update(discordLinks) + .set({ + discordUserId: priorLink.discordUserId, + discordUsername: priorLink.discordUsername, + linkedAt: priorLink.linkedAt, + }) + .where(eq(discordLinks.userId, state.u)); + } else { + await tx.delete(discordLinks).where(eq(discordLinks.userId, state.u)); + } + if (hacker && participant && before) { + await tx + .update(hackathonParticipants) + .set(before) + .where(eq(hackathonParticipants.id, participant.id)); + } + }); const { status, retryAfter } = await refusal("role-connection", putRes); return fail(failureFor(status), { retryAfter }); } @@ -241,6 +341,7 @@ export async function completeLink(opts: { ok: true, then: state.t, hackathon, + home, username: me.username, }; } diff --git a/packages/api/src/services/discord/roles.ts b/packages/api/src/services/discord/roles.ts new file mode 100644 index 00000000..557fdf6d --- /dev/null +++ b/packages/api/src/services/discord/roles.ts @@ -0,0 +1,245 @@ +// Who may link Discord, and what Discord is told about them. One typed model +// for the three roles instead of booleans repeated across the router, the link +// flow and the portal. See docs/features/discord.md. + +import type { DrizzleDB } from "@query/db"; +import { isExpiredAdmin } from "../../types/portal-context"; + +/** One person can hold several of these at once. */ +export type DiscordRoles = { + /** Accepted and said "I'm coming" (or already checked in). */ + hacker: boolean; + /** An approved judge of the edition. */ + judge: boolean; + /** Event staff of the volunteer tier, while an edition is open or live. */ + volunteer: boolean; +}; + +export const NO_ROLES: DiscordRoles = { + hacker: false, + judge: false, + volunteer: false, +}; + +export const hasDiscordRole = (roles: DiscordRoles) => + roles.hacker || roles.judge || roles.volunteer; + +/** Accepted: seated, whether or not they have said they are coming. */ +export const isAcceptedHacker = (status: string | null | undefined) => + status === "approved" || status === "checked_in"; + +/** + * A hacker earns the Discord step by answering "I'm coming" on the hackathon + * Overview. Being accepted alone is not enough. Checked in counts without the + * answer: they are in the building. + */ +export const isConfirmedHacker = (p: { + registrationStatus: string | null | undefined; + attendanceConfirmedAt: Date | null | undefined; +}) => + p.registrationStatus === "checked_in" || + (p.registrationStatus === "approved" && !!p.attendanceConfirmedAt); + +/** + * Volunteers are org-wide staff, not tied to one edition, so they qualify for + * any edition that is open or live: registration has opened and the event is + * not over. Not a draft, an announcement, a finished or a cancelled edition. + */ +export const VOLUNTEER_EDITION_STATUSES = [ + "open", + "closed", + "in_progress", +] as const; + +const isVolunteerEdition = (status: string) => + (VOLUNTEER_EDITION_STATUSES as readonly string[]).includes(status); + +/** The roles one person holds in one edition, from what the database says. */ +export function rolesFor(input: { + participant: { + registrationStatus: string | null | undefined; + attendanceConfirmedAt: Date | null | undefined; + } | null; + judge: boolean; + volunteer: boolean; + hackathonStatus: string; +}): DiscordRoles { + return { + hacker: !!input.participant && isConfirmedHacker(input.participant), + judge: input.judge, + volunteer: input.volunteer && isVolunteerEdition(input.hackathonStatus), + }; +} + +/** + * What the Linked Roles PUT carries. `accepted` is 1 only for confirmed + * hackers. `food_group` and `ramadan` are hackers' alone and left out + * otherwise. `judge` and `volunteer` are always sent, 1 or 0, so a role that + * no longer applies is cleared the next time the person updates their roles. + */ +export function roleMetadata( + roles: DiscordRoles, + hacker: { foodGroup: number; ramadan: 0 | 1 } | null, +) { + return { + accepted: roles.hacker ? 1 : 0, + ...(roles.hacker && hacker + ? { food_group: hacker.foodGroup, ramadan: hacker.ramadan } + : {}), + judge: roles.judge ? 1 : 0, + volunteer: roles.volunteer ? 1 : 0, + }; +} + +export type DiscordParticipant = { + id: string; + registrationStatus: string; + attendanceConfirmedAt: Date | null; + foodGroup: string | null; + ramadanFasting: string | null; + ramadanRoleOptIn: boolean | null; + discordUserId: string | null; + discordUsername: string | null; + discordLinkedAt: Date | null; +}; + +export type DiscordContext = { + hackathon: { id: string; name: string }; + participant: DiscordParticipant | null; + roles: DiscordRoles; +}; + +const PARTICIPANT_COLUMNS = { + id: true, + registrationStatus: true, + attendanceConfirmedAt: true, + foodGroup: true, + ramadanFasting: true, + ramadanRoleOptIn: true, + discordUserId: true, + discordUsername: true, + discordLinkedAt: true, +} as const; + +const HACKATHON_COLUMNS = { + id: true, + name: true, + status: true, + startDate: true, +} as const; + +type Edition = { id: string; name: string; status: string; startDate: Date }; + +/** An active, unexpired admin row of the volunteer tier. */ +async function isVolunteer(db: DrizzleDB, userId: string): Promise { + const admin = await db.query.admins.findFirst({ + where: { userId, isActive: true, role: "volunteer" }, + columns: { expiresAt: true }, + }); + return !!admin && !isExpiredAdmin(admin); +} + +/** + * Everything the Discord step knows about one person for one edition. With a + * hackathon id, that edition, even when they hold no role there (the portal + * still shows a hacker who has not confirmed). Without one, which is what + * Discord's Linked Roles verification URL sends, the newest edition that is + * not cancelled or over in which they hold a role. Null when there is none. + */ +export async function discordContext( + db: DrizzleDB, + userId: string, + hackathonId: string | null, +): Promise { + if (hackathonId) { + const hackathon = await db.query.hackathons.findFirst({ + where: { id: hackathonId }, + columns: HACKATHON_COLUMNS, + }); + if (!hackathon) return null; + const [participant, judge, volunteer] = await Promise.all([ + db.query.hackathonParticipants.findFirst({ + where: { hackathonId, userId }, + columns: PARTICIPANT_COLUMNS, + }), + db.query.judges.findFirst({ + where: { hackathonId, userId, isActive: true }, + columns: { id: true }, + }), + isVolunteer(db, userId), + ]); + return { + hackathon: { id: hackathon.id, name: hackathon.name }, + participant: participant ?? null, + roles: rolesFor({ + participant: participant ?? null, + judge: !!judge, + volunteer, + hackathonStatus: hackathon.status, + }), + }; + } + + const volunteer = await isVolunteer(db, userId); + const [participants, judgeRows, openEditions] = await Promise.all([ + db.query.hackathonParticipants.findMany({ + where: { userId }, + columns: PARTICIPANT_COLUMNS, + with: { hackathon: { columns: HACKATHON_COLUMNS } }, + }), + db.query.judges.findMany({ + where: { userId, isActive: true }, + columns: { id: true }, + with: { hackathon: { columns: HACKATHON_COLUMNS } }, + }), + volunteer + ? db.query.hackathons.findMany({ + where: { status: { in: [...VOLUNTEER_EDITION_STATUSES] } }, + columns: HACKATHON_COLUMNS, + }) + : Promise.resolve([] as Edition[]), + ]); + + const editions = new Map< + string, + { edition: Edition; participant: DiscordParticipant | null; judge: boolean } + >(); + const entry = (edition: Edition) => { + let held = editions.get(edition.id); + if (!held) { + held = { edition, participant: null, judge: false }; + editions.set(edition.id, held); + } + return held; + }; + for (const { hackathon, ...participant } of participants) { + if (hackathon) entry(hackathon).participant = participant; + } + for (const { hackathon } of judgeRows) { + if (hackathon) entry(hackathon).judge = true; + } + for (const edition of openEditions) entry(edition); + + return ( + [...editions.values()] + .filter( + ({ edition }) => + edition.status !== "cancelled" && edition.status !== "completed", + ) + .map(({ edition, participant, judge }) => ({ + start: new Date(edition.startDate).getTime(), + context: { + hackathon: { id: edition.id, name: edition.name }, + participant, + roles: rolesFor({ + participant, + judge, + volunteer, + hackathonStatus: edition.status, + }), + } satisfies DiscordContext, + })) + .filter(({ context }) => hasDiscordRole(context.roles)) + .sort((a, b) => b.start - a.start)[0]?.context ?? null + ); +} diff --git a/sites/mainweb/app/(portal)/api/discord/callback/route.ts b/sites/mainweb/app/(portal)/api/discord/callback/route.ts index 7f9b7e0e..cf913602 100644 --- a/sites/mainweb/app/(portal)/api/discord/callback/route.ts +++ b/sites/mainweb/app/(portal)/api/discord/callback/route.ts @@ -18,8 +18,8 @@ export const dynamic = "force-dynamic"; /** * Discord sends the user back here with ?code=&state=. Checks the signed * state and the signed-in user, then links. On success it goes to the server - * invite (first join) or the portal; on any failure back to the hackathon page - * with ?discord=error&reason=. + * invite (first join) or the portal; on any failure back to the page the role's + * card lives on with ?discord=error&reason=. */ export async function GET(request: NextRequest) { const config = discordConfig(); @@ -64,14 +64,14 @@ export async function GET(request: NextRequest) { if (!result.ok) { const extra: Record = {}; if (result.retryAfter) extra.retry = String(result.retryAfter); - return backToPortal(result.hackathon ?? null, { - discord: "error", - reason: result.reason, - ...extra, - }); + return backToPortal( + result.hackathon ?? null, + { discord: "error", reason: result.reason, ...extra }, + result.home, + ); } if (result.then === "invite") { return NextResponse.redirect(config.inviteUrl); } - return backToPortal(result.hackathon, { discord: "linked" }); + return backToPortal(result.hackathon, { discord: "linked" }, result.home); } diff --git a/sites/mainweb/app/(portal)/api/discord/connect/route.ts b/sites/mainweb/app/(portal)/api/discord/connect/route.ts index 44a08742..06f7920a 100644 --- a/sites/mainweb/app/(portal)/api/discord/connect/route.ts +++ b/sites/mainweb/app/(portal)/api/discord/connect/route.ts @@ -25,7 +25,8 @@ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; /** * Starts the Discord link. Also the "Linked Roles Verification URL" in the * Discord developer portal, which sends no query: the edition then defaults to - * the live one the signed-in user is accepted to. + * the newest live one in which the signed-in user holds a role (a hacker who + * confirmed they are coming, an approved judge, or a volunteer). * * ?hackathon=ID optional * ?ramadan=1|0 optional; absent keeps the stored choice @@ -64,7 +65,7 @@ export async function GET(request: NextRequest) { userId, hackathonId, ); - if (!target?.hackathon) { + if (!target) { return backToPortal(null, { discord: "error", reason: "not_accepted" }); } diff --git a/sites/mainweb/lib/discord-route.ts b/sites/mainweb/lib/discord-route.ts index bb75aef2..6eda1a2b 100644 --- a/sites/mainweb/lib/discord-route.ts +++ b/sites/mainweb/lib/discord-route.ts @@ -6,6 +6,7 @@ import { rateLimitShared, resolveClientIp, } from "@query/api/middleware/security"; +import type { LinkHome } from "@query/api/discord"; import { hackathonPathSegment } from "@/lib/hackathon-slug"; export function authSecret(): string | null { @@ -29,14 +30,23 @@ export async function overLimit( return !allowed; } -/** Back to the hackathon page (or the dashboard) with a Discord outcome. */ +/** + * Back to the page the person's Discord card lives on, with a Discord outcome: + * the hackathon page for a hacker, the judge page for a judge, the check-in + * desk for a volunteer. The dashboard when no edition is known. + */ export function backToPortal( hackathon: { id: string; name: string } | null, params: Record, + home: LinkHome = "hackathon", ) { - const path = hackathon - ? `/hackathons/${hackathonPathSegment(hackathon.name, hackathon.id)}` - : "/dashboard"; + const path = !hackathon + ? "/dashboard" + : home === "judge" + ? "/judge" + : home === "scan" + ? "/scan" + : `/hackathons/${hackathonPathSegment(hackathon.name, hackathon.id)}`; const url = new URL(path, siteOrigin()); for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v); return NextResponse.redirect(url); From dddd065194b90dc97e9f554aff4ab2deda55f43a Mon Sep 17 00:00:00 2001 From: aamoghS Date: Thu, 26 Nov 2026 22:03:44 -0500 Subject: [PATCH 03/15] feat(portal): Discord card for judges and volunteers, confirm step for hackers Judges see the card on the judge page and volunteers on the check-in desk, told joining is required. An accepted hacker who has not said they are coming is asked to confirm before the invite, and the dashboard step says so. --- .../hackathons/[id]/HackathonDetailPage.tsx | 2 +- .../mainweb/app/(portal)/judge/JudgePage.tsx | 7 + sites/mainweb/app/(portal)/scan/ScanPage.tsx | 6 + .../components/hackathon/DiscordCard.test.tsx | 161 ++++++++++++++++-- .../components/hackathon/DiscordCard.tsx | 109 +++++++++--- .../mainweb/components/hackathon/InfoTab.tsx | 2 + sites/mainweb/lib/hackathon-next-step.test.ts | 63 +++++++ sites/mainweb/lib/hackathon-next-step.ts | 47 +++-- 8 files changed, 346 insertions(+), 51 deletions(-) diff --git a/sites/mainweb/app/(portal)/hackathons/[id]/HackathonDetailPage.tsx b/sites/mainweb/app/(portal)/hackathons/[id]/HackathonDetailPage.tsx index f508d1ad..d709a881 100644 --- a/sites/mainweb/app/(portal)/hackathons/[id]/HackathonDetailPage.tsx +++ b/sites/mainweb/app/(portal)/hackathons/[id]/HackathonDetailPage.tsx @@ -279,7 +279,7 @@ export default function HackathonDetailPage() { // wrapper only re-points the colour and font tokens, so every other // hackathon is untouched. const bloom = isHacklyticsName(hackathon.name); - const foodGroup = discord.data?.eligible ? discord.data.foodGroup : null; + const foodGroup = discord.data?.foodGroup ?? null; const content = (
diff --git a/sites/mainweb/app/(portal)/judge/JudgePage.tsx b/sites/mainweb/app/(portal)/judge/JudgePage.tsx index e0788a26..8df04311 100644 --- a/sites/mainweb/app/(portal)/judge/JudgePage.tsx +++ b/sites/mainweb/app/(portal)/judge/JudgePage.tsx @@ -12,6 +12,7 @@ import { FormChipSelect } from "@query/ui/FormChipSelect"; import { useIsClient } from "@/lib/use-is-client"; import { usePortalContext } from "@/lib/use-portal-context"; import { LoadingScreen } from "@/components/portal/LoadingScreen"; +import { DiscordCard } from "@/components/hackathon/DiscordCard"; import { body, btnSecondary, @@ -165,6 +166,12 @@ export default function JudgePage() {

+ {/* The card shows itself only to an approved judge, for the newest live + edition; empty, the wrapper and its rule are hidden too. */} +
+ +
+ {judging.length > 0 && (

You are judging

diff --git a/sites/mainweb/app/(portal)/scan/ScanPage.tsx b/sites/mainweb/app/(portal)/scan/ScanPage.tsx index 62820b17..d6805b22 100644 --- a/sites/mainweb/app/(portal)/scan/ScanPage.tsx +++ b/sites/mainweb/app/(portal)/scan/ScanPage.tsx @@ -14,6 +14,7 @@ import { pageTitle, } from "@query/ui/classes"; import { ScanAccess } from "@/components/portal/ScanAccess"; +import { DiscordCard } from "@/components/hackathon/DiscordCard"; // Only scanners use the desk, so the page ships without it. It starts loading // as soon as the role is known, alongside the hackathon list it waits on. @@ -62,6 +63,11 @@ export default function ScanPage() {

Check-in desk

+ {/* The card shows itself only to volunteers; empty, the wrapper hides. */} +
+ +
+ {showPicker && (