From f6cbfc269c121cd870ef98149f270a8945978c87 Mon Sep 17 00:00:00 2001 From: aamoghS Date: Fri, 27 Nov 2026 01:09:46 -0500 Subject: [PATCH 1/8] feat(discord): an approved volunteer application holds the volunteer role The volunteer role is now the staff tier (while an edition is open or live) or an approved application for the edition (from the announcement until it is over). The edition lookup also finds editions where the person was approved, and a volunteer who is not on the staff tier returns to the volunteer page after linking. --- .../api/src/services/discord/discord.test.ts | 43 +++++++++++-- packages/api/src/services/discord/link.ts | 20 +++--- packages/api/src/services/discord/roles.ts | 62 +++++++++++++++---- packages/api/src/services/volunteer.ts | 26 +++++--- 4 files changed, 119 insertions(+), 32 deletions(-) diff --git a/packages/api/src/services/discord/discord.test.ts b/packages/api/src/services/discord/discord.test.ts index d6be0a94..8f67d7d4 100644 --- a/packages/api/src/services/discord/discord.test.ts +++ b/packages/api/src/services/discord/discord.test.ts @@ -130,27 +130,60 @@ describe("discord roles", () => { }); it("holds each role independently, and any combination", () => { - const base = { participant: null, judge: false, volunteer: false, hackathonStatus: "open" }; + const base = { + participant: null, + judge: false, + staff: false, + approvedVolunteer: 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, staff: true })).toEqual({ ...NO_ROLES, volunteer: true }); + expect(rolesFor({ ...base, approvedVolunteer: true })).toEqual({ + ...NO_ROLES, + volunteer: true, + }); expect( - rolesFor({ ...base, participant: hacker("approved", at), judge: true, volunteer: true }), + rolesFor({ ...base, participant: hacker("approved", at), judge: true, staff: 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", () => { + it("gives the volunteer staff tier a role only while the edition is open or live", () => { const volunteerIn = (hackathonStatus: string) => - rolesFor({ participant: null, judge: false, volunteer: true, hackathonStatus }).volunteer; + rolesFor({ + participant: null, + judge: false, + staff: true, + approvedVolunteer: false, + 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("gives an approved volunteer a role from the announcement until the edition is over", () => { + const applicantIn = (hackathonStatus: string) => + rolesFor({ + participant: null, + judge: false, + staff: false, + approvedVolunteer: true, + hackathonStatus, + }).volunteer; + for (const status of ["announced", "open", "closed", "in_progress"]) { + expect(applicantIn(status)).toBe(true); + } + for (const status of ["draft", "completed", "cancelled"]) { + expect(applicantIn(status)).toBe(false); + } + }); + it("reports whether anyone holds a role", () => { expect(hasDiscordRole(NO_ROLES)).toBe(false); expect(hasDiscordRole({ ...NO_ROLES, volunteer: true })).toBe(true); diff --git a/packages/api/src/services/discord/link.ts b/packages/api/src/services/discord/link.ts index 5fd2d049..29cf7f48 100644 --- a/packages/api/src/services/discord/link.ts +++ b/packages/api/src/services/discord/link.ts @@ -18,7 +18,7 @@ import { roleMetadata, roleSignature, } from "./roles"; -import type { DiscordParticipant, DiscordRoles } from "./roles"; +import type { DiscordContext, DiscordParticipant } from "./roles"; import type { DiscordState } from "./state"; import { withDiscordLock, zeroDiscordRoles } from "./sync"; import { sealTokens } from "./tokens"; @@ -28,10 +28,11 @@ 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. + * page for a judge, the check-in desk for a volunteer on the staff tier, and + * the volunteer application page for one who was approved without it. Each is + * where that role's Discord card lives. */ -export type LinkHome = "hackathon" | "judge" | "scan"; +export type LinkHome = "hackathon" | "judge" | "scan" | "volunteer"; type LinkResult = | { @@ -127,8 +128,11 @@ async function heldByAnother( return !!participant; } -const homeOf = (roles: DiscordRoles): LinkHome => - roles.hacker ? "hackathon" : roles.judge ? "judge" : "scan"; +const homeOf = ({ + roles, + deskStaff, +}: Pick): LinkHome => + roles.hacker ? "hackathon" : roles.judge ? "judge" : deskStaff ? "scan" : "volunteer"; const failWith = (hackathon: HackathonRef, home: LinkHome) => @@ -164,7 +168,7 @@ export async function completeLink(opts: { // Refused here, before Discord is called at all, when they hold no role. const early = await resolveConnectTarget(db, state.u, state.h); if (!early) return { ok: false, reason: "not_accepted" }; - const failEarly = failWith(early.hackathon, homeOf(early.roles)); + const failEarly = failWith(early.hackathon, homeOf(early)); const tokenRes = await doFetch(`${API}/oauth2/token`, { method: "POST", @@ -211,7 +215,7 @@ export async function completeLink(opts: { const target = await resolveConnectTarget(tx, state.u, state.h); if (!target) return { ok: false, reason: "not_accepted" }; const { hackathon, participant, roles } = target; - const home = homeOf(roles); + const home = homeOf(target); const fail = failWith(hackathon, home); if (await heldByAnother(tx, discordId, state.u, hackathon.id)) { diff --git a/packages/api/src/services/discord/roles.ts b/packages/api/src/services/discord/roles.ts index 2e01450b..8fc35728 100644 --- a/packages/api/src/services/discord/roles.ts +++ b/packages/api/src/services/discord/roles.ts @@ -4,6 +4,7 @@ import type { DrizzleDB } from "@query/db"; import { isExpiredAdmin } from "../../types/portal-context"; +import { approvedVolunteerEditions } from "../volunteer"; import { foodGroupByKey } from "./config"; import { ensureFoodGroup } from "./food-group"; @@ -13,7 +14,10 @@ export type DiscordRoles = { hacker: boolean; /** An approved judge of the edition. */ judge: boolean; - /** Event staff of the volunteer tier, while an edition is open or live. */ + /** + * Event staff of the volunteer tier while an edition is open or live, or a + * volunteer an organizer approved for the edition. + */ volunteer: boolean; }; @@ -56,6 +60,18 @@ export const VOLUNTEER_EDITION_STATUSES = [ const isVolunteerEdition = (status: string) => (VOLUNTEER_EDITION_STATUSES as readonly string[]).includes(status); +/** + * An approved volunteer application is for one edition and is taken from the + * announcement on, since that is when applications open. Not a draft, a + * finished or a cancelled edition. + */ +const isApplicantEdition = (status: string) => + status === "announced" || isVolunteerEdition(status); + +/** The volunteer staff tier is what opens the check-in desk. */ +const holdsDesk = (staff: boolean, hackathonStatus: string) => + staff && isVolunteerEdition(hackathonStatus); + /** The roles one person holds in one edition, from what the database says. */ export function rolesFor(input: { participant: { @@ -63,13 +79,18 @@ export function rolesFor(input: { attendanceConfirmedAt: Date | null | undefined; } | null; judge: boolean; - volunteer: boolean; + /** An active, unexpired volunteer staff tier. */ + staff: boolean; + /** An approved volunteer application for this edition. */ + approvedVolunteer: boolean; hackathonStatus: string; }): DiscordRoles { return { hacker: !!input.participant && isConfirmedHacker(input.participant), judge: input.judge, - volunteer: input.volunteer && isVolunteerEdition(input.hackathonStatus), + volunteer: + holdsDesk(input.staff, input.hackathonStatus) || + (input.approvedVolunteer && isApplicantEdition(input.hackathonStatus)), }; } @@ -139,6 +160,8 @@ export type DiscordContext = { hackathon: { id: string; name: string }; participant: DiscordParticipant | null; roles: DiscordRoles; + /** Volunteer through the staff tier, so the check-in desk is theirs. */ + deskStaff: boolean; }; const PARTICIPANT_COLUMNS = { @@ -189,7 +212,7 @@ export async function discordContext( columns: HACKATHON_COLUMNS, }); if (!hackathon) return null; - const [participant, judge, volunteer] = await Promise.all([ + const [participant, judge, staff, approved] = await Promise.all([ db.query.hackathonParticipants.findFirst({ where: { hackathonId, userId }, columns: PARTICIPANT_COLUMNS, @@ -199,6 +222,7 @@ export async function discordContext( columns: { id: true }, }), isVolunteer(db, userId), + approvedVolunteerEditions(db, userId, hackathonId), ]); return { hackathon: { id: hackathon.id, name: hackathon.name }, @@ -206,14 +230,19 @@ export async function discordContext( roles: rolesFor({ participant: participant ?? null, judge: !!judge, - volunteer, + staff, + approvedVolunteer: approved.length > 0, hackathonStatus: hackathon.status, }), + deskStaff: holdsDesk(staff, hackathon.status), }; } - const volunteer = await isVolunteer(db, userId); - const [participants, judgeRows, openEditions] = await Promise.all([ + const [staff, approvedIds] = await Promise.all([ + isVolunteer(db, userId), + approvedVolunteerEditions(db, userId), + ]); + const [participants, judgeRows, volunteerEditions] = await Promise.all([ db.query.hackathonParticipants.findMany({ where: { userId }, columns: PARTICIPANT_COLUMNS, @@ -224,9 +253,18 @@ export async function discordContext( columns: { id: true }, with: { hackathon: { columns: HACKATHON_COLUMNS } }, }), - volunteer + // The editions a volunteer qualifies for: every open or live one for the + // staff tier, the ones they were approved for as an applicant. + staff || approvedIds.length > 0 ? db.query.hackathons.findMany({ - where: { status: { in: [...VOLUNTEER_EDITION_STATUSES] } }, + where: { + OR: [ + ...(staff + ? [{ status: { in: [...VOLUNTEER_EDITION_STATUSES] } }] + : []), + ...(approvedIds.length > 0 ? [{ id: { in: approvedIds } }] : []), + ], + }, columns: HACKATHON_COLUMNS, }) : Promise.resolve([] as Edition[]), @@ -250,7 +288,7 @@ export async function discordContext( for (const { hackathon } of judgeRows) { if (hackathon) entry(hackathon).judge = true; } - for (const edition of openEditions) entry(edition); + for (const edition of volunteerEditions) entry(edition); return ( [...editions.values()] @@ -266,9 +304,11 @@ export async function discordContext( roles: rolesFor({ participant, judge, - volunteer, + staff, + approvedVolunteer: approvedIds.includes(edition.id), hackathonStatus: edition.status, }), + deskStaff: holdsDesk(staff, edition.status), } satisfies DiscordContext, })) .filter(({ context }) => hasDiscordRole(context.roles)) diff --git a/packages/api/src/services/volunteer.ts b/packages/api/src/services/volunteer.ts index 147a964b..91baf4da 100644 --- a/packages/api/src/services/volunteer.ts +++ b/packages/api/src/services/volunteer.ts @@ -176,20 +176,30 @@ const ACCEPTING_STATUSES = ["announced", "open"] as const; const EDITABLE_STATUSES = ["announced", "open", "closed", "in_progress"] as const; /** - * Whether a person has been approved to volunteer at an edition. The one - * place that answers it: the Discord role code should call this rather than - * reading the table, so a change to what "approved" means lands once. + * The editions a person is approved to volunteer at, or just the one named. + * The one place that answers "approved": the Discord role code calls this (or + * `isApprovedVolunteer`) rather than reading the table, so a change to what + * "approved" means lands once. */ +export async function approvedVolunteerEditions( + db: DrizzleDB, + userId: string, + hackathonId?: string, +): Promise { + const rows = await db.query.hackathonVolunteerApplications.findMany({ + where: { userId, status: "approved", ...(hackathonId ? { hackathonId } : {}) }, + columns: { hackathonId: true }, + }); + return rows.map((row) => row.hackathonId); +} + +/** Whether a person has been approved to volunteer at an edition. */ export async function isApprovedVolunteer( db: DrizzleDB, userId: string, hackathonId: string, ): Promise { - const row = await db.query.hackathonVolunteerApplications.findFirst({ - where: { userId, hackathonId, status: "approved" }, - columns: { id: true }, - }); - return !!row; + return (await approvedVolunteerEditions(db, userId, hackathonId)).length > 0; } type Edition = { From 80bce19ace670dc026ba4cbe5eea1498a1049838 Mon Sep 17 00:00:00 2001 From: aamoghS Date: Fri, 27 Nov 2026 01:09:47 -0500 Subject: [PATCH 2/8] feat(volunteer): re-sync Discord roles when an application is decided or withdrawn --- packages/api/src/routers/volunteer/admin.ts | 48 ++++++++++++++------ packages/api/src/routers/volunteer/portal.ts | 40 +++++++++++----- 2 files changed, 61 insertions(+), 27 deletions(-) diff --git a/packages/api/src/routers/volunteer/admin.ts b/packages/api/src/routers/volunteer/admin.ts index 01e8a9c4..db5be556 100644 --- a/packages/api/src/routers/volunteer/admin.ts +++ b/packages/api/src/routers/volunteer/admin.ts @@ -6,6 +6,10 @@ import type { DrizzleDB } from "@query/db"; import { createTRPCRouter } from "../../trpc"; import { isAdmin } from "../../middleware/procedures"; import { recordAdminAction } from "../../middleware/audit"; +import { + markDiscordRolesPending, + syncDiscordRoles, +} from "../../services/discord"; import { portalOrigin } from "../../services/judging/claims"; import { matchingVolunteers, @@ -109,21 +113,31 @@ export const volunteerAdminRouter = createTRPCRouter({ // Conditional on the status read above: two organisers deciding at once // cannot both win, and neither can overwrite a withdrawal that landed // in between. - const [updated] = await db - .update(applications) - .set({ - status: input.decision, - reviewedById: ctx.userId as string, - reviewedAt: new Date(), - updatedAt: new Date(), - }) - .where( - and( - eq(applications.id, input.applicationId), - eq(applications.status, before.status), - ), - ) - .returning({ id: applications.id }); + const updated = await db.transaction(async (tx) => { + const [row] = await tx + .update(applications) + .set({ + status: input.decision, + reviewedById: ctx.userId as string, + reviewedAt: new Date(), + updatedAt: new Date(), + }) + .where( + and( + eq(applications.id, input.applicationId), + eq(applications.status, before.status), + ), + ) + .returning({ id: applications.id }); + // The volunteer role follows the decision, so a linked Discord account + // is owed a sync for as long as the decision stands. + if (row) { + await markDiscordRolesPending(tx as unknown as DrizzleDB, [ + before.userId, + ]); + } + return row; + }); if (!updated) { throw new TRPCError({ code: "CONFLICT", @@ -145,6 +159,10 @@ export const volunteerAdminRouter = createTRPCRouter({ }, }); + // Approving grants the volunteer role to a linked Discord account and + // declining takes it back, with no new link needed. + await syncDiscordRoles(db, before.userId); + // Best-effort: the decision stands if the mail does not go out, and the // log is the only record that it did not. const email = before.user?.email; diff --git a/packages/api/src/routers/volunteer/portal.ts b/packages/api/src/routers/volunteer/portal.ts index 5bf11146..9dcdf896 100644 --- a/packages/api/src/routers/volunteer/portal.ts +++ b/packages/api/src/routers/volunteer/portal.ts @@ -5,6 +5,10 @@ import { hackathonVolunteerApplications as applications } from "@query/db"; import type { DrizzleDB } from "@query/db"; import { createTRPCRouter, protectedProcedure } from "../../trpc"; import { notHackathonBanned } from "../../middleware/procedures"; +import { + markDiscordRolesPending, + syncDiscordRoles, +} from "../../services/discord"; import { allowsEdits, assertEditionNotOver, @@ -158,18 +162,30 @@ export const volunteerPortalRouter = createTRPCRouter({ .input(hackathonInput) .mutation(async ({ ctx, input }) => { const db = ctx.db as DrizzleDB; - const [withdrawn] = await db - .update(applications) - .set({ status: "withdrawn", updatedAt: new Date() }) - .where( - and( - eq(applications.userId, ctx.userId as string), - eq(applications.hackathonId, input.hackathonId), - inArray(applications.status, ["pending", "approved"]), - ), - ) - .returning({ id: applications.id }); - if (withdrawn) return { success: true }; + const userId = ctx.userId as string; + const withdrawn = await db.transaction(async (tx) => { + const [row] = await tx + .update(applications) + .set({ status: "withdrawn", updatedAt: new Date() }) + .where( + and( + eq(applications.userId, userId), + eq(applications.hackathonId, input.hackathonId), + inArray(applications.status, ["pending", "approved"]), + ), + ) + .returning({ id: applications.id }); + // An approved volunteer loses the Discord role by stepping back, so a + // linked account is owed a sync for as long as the withdrawal stands. + if (row) { + await markDiscordRolesPending(tx as unknown as DrizzleDB, [userId]); + } + return row; + }); + if (withdrawn) { + await syncDiscordRoles(db, userId); + return { success: true }; + } const existing = await db.query.hackathonVolunteerApplications.findFirst({ where: { userId: ctx.userId as string, hackathonId: input.hackathonId }, From a6ff650c736b8b17951bfe1954e44bd9a24de101 Mon Sep 17 00:00:00 2001 From: aamoghS Date: Fri, 27 Nov 2026 01:13:24 -0500 Subject: [PATCH 3/8] feat(mainweb): show the Discord card to an approved volunteer on the volunteer page The card sits in the confirmed state of the application page and links through /api/discord/connect. A volunteer who was approved without the staff tier returns to that page after linking, not to the check-in desk. --- .../[id]/volunteer/VolunteerPage.tsx | 2 ++ .../volunteer/VolunteerStatusView.test.tsx | 13 ++++++++++ .../volunteer/VolunteerStatusView.tsx | 9 +++++-- sites/mainweb/lib/discord-route.test.ts | 24 +++++++++++++++++++ sites/mainweb/lib/discord-route.ts | 5 ++-- 5 files changed, 49 insertions(+), 4 deletions(-) create mode 100644 sites/mainweb/lib/discord-route.test.ts diff --git a/sites/mainweb/app/(portal)/hackathons/[id]/volunteer/VolunteerPage.tsx b/sites/mainweb/app/(portal)/hackathons/[id]/volunteer/VolunteerPage.tsx index a71c59f6..a79e11ff 100644 --- a/sites/mainweb/app/(portal)/hackathons/[id]/volunteer/VolunteerPage.tsx +++ b/sites/mainweb/app/(portal)/hackathons/[id]/volunteer/VolunteerPage.tsx @@ -7,6 +7,7 @@ import { CONTACT_EMAIL } from "@query/core"; import { trpc } from "@/lib/trpc"; import { trpcErrorMessage } from "@/lib/trpc-error"; import { LoadingScreen } from "@/components/portal/LoadingScreen"; +import { DiscordCard } from "@/components/hackathon/DiscordCard"; import { HackathonUnavailable } from "@/components/hackathon/HackathonUnavailable"; import { VolunteerForm } from "@/components/volunteer/VolunteerForm"; import { VolunteerStatusView } from "@/components/volunteer/VolunteerStatusView"; @@ -138,6 +139,7 @@ export default function VolunteerPage() { accepting={accepting} canEdit={canEdit} eventHref={eventHref} + discordCard={} contactEmail={contactEmail} busy={withdraw.isPending} onEdit={() => { diff --git a/sites/mainweb/components/volunteer/VolunteerStatusView.test.tsx b/sites/mainweb/components/volunteer/VolunteerStatusView.test.tsx index 4df62aac..11f1d25a 100644 --- a/sites/mainweb/components/volunteer/VolunteerStatusView.test.tsx +++ b/sites/mainweb/components/volunteer/VolunteerStatusView.test.tsx @@ -46,6 +46,7 @@ function render( canEdit?: boolean; name?: string; answers?: VolunteerAnswers; + discordCard?: React.ReactNode; } = {}, ) { const calls = { edit: vi.fn(), withdraw: vi.fn(), again: vi.fn() }; @@ -64,6 +65,7 @@ function render( accepting={over.accepting ?? true} canEdit={over.canEdit ?? true} eventHref="/hackathons/hacklytics-digital-bloom" + discordCard={over.discordCard} contactEmail="hello@hacklytics.io" busy={false} onEdit={calls.edit} @@ -126,6 +128,17 @@ describe("VolunteerStatusView", () => { expect(view.buttons()).toEqual(["Withdraw"]); }); + it("puts the Discord card in an approved volunteer's page, and in no other state", () => { + const card =

Join the Hacklytics Discord

; + const approved = render("approved", { discordCard: card }); + expect(approved.el.querySelector("[data-testid=discord-card]")).not.toBeNull(); + for (const s of ["pending", "declined", "withdrawn"] as const) { + expect( + render(s, { discordCard: card }).el.querySelector("[data-testid=discord-card]"), + ).toBeNull(); + } + }); + it("declines kindly, with no answers and nothing to do", () => { const view = render("declined"); expect(view.el.textContent).toContain("Not placed this time"); diff --git a/sites/mainweb/components/volunteer/VolunteerStatusView.tsx b/sites/mainweb/components/volunteer/VolunteerStatusView.tsx index 726062f1..108b3e13 100644 --- a/sites/mainweb/components/volunteer/VolunteerStatusView.tsx +++ b/sites/mainweb/components/volunteer/VolunteerStatusView.tsx @@ -1,3 +1,4 @@ +import type { ReactNode } from "react"; import Link from "next/link"; import type { VolunteerAnswers, VolunteerStatus } from "@query/db/constants"; import { @@ -20,8 +21,10 @@ type Props = { accepting: boolean; /** Whether a pending application can still be corrected. */ canEdit: boolean; - /** The event page, where the Discord step lives. */ + /** The event page. */ eventHref: string; + /** The Discord step, shown to an approved volunteer. */ + discordCard?: ReactNode; contactEmail: string; busy: boolean; onEdit: () => void; @@ -43,6 +46,7 @@ export function VolunteerStatusView({ accepting, canEdit, eventHref, + discordCard, contactEmail, busy, onEdit, @@ -94,13 +98,14 @@ export function VolunteerStatusView({
  1. Join {discord}. It's required for volunteers, and{" "} - {discordFor}. The link is on the event page. + {discordFor}. Link your account below.
  2. Check the times below. If your plans change, withdraw so organizers can plan around you.
+ {discordCard &&
{discordCard}
} Open the event page diff --git a/sites/mainweb/lib/discord-route.test.ts b/sites/mainweb/lib/discord-route.test.ts new file mode 100644 index 00000000..df887392 --- /dev/null +++ b/sites/mainweb/lib/discord-route.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; +import { backToPortal } from "./discord-route"; + +const hackathon = { id: "8c0e5f7a-0000-4000-8000-000000000001", name: "Hacklytics: Digital Bloom" }; +const locationOf = (response: Response) => new URL(response.headers.get("location") ?? ""); +const where = (home?: Parameters[2]) => { + const url = locationOf(backToPortal(hackathon, { discord: "linked" }, home)); + return `${url.pathname}${url.search}`; +}; + +describe("backToPortal", () => { + it("returns each role to the page its Discord card lives on", () => { + expect(where("judge")).toBe("/judge?discord=linked"); + expect(where("scan")).toBe("/scan?discord=linked"); + expect(where("volunteer")).toMatch(/^\/hackathons\/.+\/volunteer\?discord=linked$/); + expect(where("hackathon")).toMatch(/^\/hackathons\/[^/]+\?discord=linked$/); + }); + + it("goes to the dashboard when no edition is known", () => { + expect(locationOf(backToPortal(null, { discord: "error" }, "volunteer")).pathname).toBe( + "/dashboard", + ); + }); +}); diff --git a/sites/mainweb/lib/discord-route.ts b/sites/mainweb/lib/discord-route.ts index 6eda1a2b..870d0cb5 100644 --- a/sites/mainweb/lib/discord-route.ts +++ b/sites/mainweb/lib/discord-route.ts @@ -33,7 +33,8 @@ export async function overLimit( /** * 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. + * desk for a volunteer on the staff tier, the application page for one who + * was approved without it. The dashboard when no edition is known. */ export function backToPortal( hackathon: { id: string; name: string } | null, @@ -46,7 +47,7 @@ export function backToPortal( ? "/judge" : home === "scan" ? "/scan" - : `/hackathons/${hackathonPathSegment(hackathon.name, hackathon.id)}`; + : `/hackathons/${hackathonPathSegment(hackathon.name, hackathon.id)}${home === "volunteer" ? "/volunteer" : ""}`; const url = new URL(path, siteOrigin()); for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v); return NextResponse.redirect(url); From 56aaa8cec451faacd25f07031d0ef7df74070577 Mon Sep 17 00:00:00 2001 From: aamoghS Date: Fri, 27 Nov 2026 01:16:51 -0500 Subject: [PATCH 4/8] test(discord): approved, declined, withdrawn and pending volunteer applications against a real database --- .../.internal-tests/discord-link.db.test.ts | 178 ++++++++++++++++++ 1 file changed, 178 insertions(+) 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 5eb66aa1..42d915e4 100644 --- a/packages/api/src/.internal-tests/discord-link.db.test.ts +++ b/packages/api/src/.internal-tests/discord-link.db.test.ts @@ -29,6 +29,8 @@ vi.mock("@query/auth/email", () => ({ sendAcceptanceEmail: vi.fn(async () => {}), sendJudgeApprovedEmail: vi.fn(async () => {}), sendJudgeAddedEmail: vi.fn(async () => {}), + sendVolunteerApprovedEmail: vi.fn(async () => {}), + sendVolunteerDeclinedEmail: vi.fn(async () => {}), })); describe.skipIf(!URL)("discord link against a real database", () => { @@ -1225,6 +1227,182 @@ describe.skipIf(!URL)("discord link against a real database", () => { expect(await svc.syncExpiredDiscordRoles(S.db as any)).toEqual({ checked: 0, synced: 0 }); }); + describe("a volunteer application", () => { + const APPLICATION = { + mode: "in_person", + affiliation: "gt_student", + availability: ["sat_morning"], + roles: ["check_in"], + shirtSize: "M", + dietary: [], + phone: "(404) 555-0142", + acknowledged: true, + }; + let organizer: ReturnType; + beforeAll(async () => { + organizer = await staff("va-organizer"); + }); + + /** Applies for the edition, and has an organizer decide it when asked. */ + const apply = async ( + tag: string, + hackathonId: string, + decision?: "approved" | "declined", + userId?: string, + ) => { + const u = userId ?? (await makeUser(tag)); + await appRouterAs(u).volunteer.submit({ hackathonId, answers: APPLICATION }); + const [application] = await S.db! + .select() + .from(S.hackathonVolunteerApplications) + .where(ops.eq(S.hackathonVolunteerApplications.userId, u)); + const decide = (to: "approved" | "declined") => + organizer.volunteer.decide({ applicationId: application!.id, decision: to }); + if (decision) await decide(decision); + return { u, decide }; + }; + const eligible = (u: string, hackathonId: string) => + svc.resolveConnectTarget(S.db as any, u, hackathonId); + + it("an approved applicant with no staff tier is eligible, links, and the PUT carries volunteer=1", async () => { + const h = await makeHackathon("va-approved"); + const { u } = await apply("va-approved", h.id, "approved"); + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: true, + roles: { hacker: false, judge: false, volunteer: true }, + }); + + expect(await linkAs(u, h.id, acct("va-approved"))).toMatchObject({ + ok: true, + // Not the check-in desk: the staff tier is what opens that. + home: "volunteer", + }); + expect(lastFor(acct("va-approved"))).toEqual({ ...ZEROS, volunteer: 1 }); + }); + + it("a pending applicant is not eligible and cannot link", async () => { + const h = await makeHackathon("va-pending"); + const { u } = await apply("va-pending", h.id); + expect(await eligible(u, h.id)).toBeNull(); + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: false, + roles: { volunteer: false }, + }); + const before = world.puts.length; + expect(await linkAs(u, h.id, acct("va-pending"))).toMatchObject({ + ok: false, + reason: "not_accepted", + }); + expect(world.puts).toHaveLength(before); + }); + + it("approving gives the role to someone already linked, and declining takes it back, with no new link", async () => { + const h = await makeHackathon("va-decide"); + const { u: judge } = await newJudge("va-decide", h.id); + await linkAs(judge, h.id, acct("va-decide")); + expect(lastFor(acct("va-decide"))).toEqual({ ...ZEROS, judge: 1 }); + + const { decide } = await apply("va-decide", h.id, undefined, judge); + // Pending changes nothing on Discord. + expect(lastFor(acct("va-decide"))).toEqual({ ...ZEROS, judge: 1 }); + + await decide("approved"); + expect(lastFor(acct("va-decide"))).toEqual({ ...ZEROS, judge: 1, volunteer: 1 }); + await decide("declined"); + expect(lastFor(acct("va-decide"))).toEqual({ ...ZEROS, judge: 1 }); + // Either can follow the other. + await decide("approved"); + expect(lastFor(acct("va-decide"))).toEqual({ ...ZEROS, judge: 1, volunteer: 1 }); + }); + + it("a declined applicant gets volunteer=0, so declining revokes the role", async () => { + const h = await makeHackathon("va-declined"); + const { u, decide } = await apply("va-declined", h.id, "approved"); + await linkAs(u, h.id, acct("va-declined")); + expect(lastFor(acct("va-declined"))).toEqual({ ...ZEROS, volunteer: 1 }); + + await decide("declined"); + expect(lastFor(acct("va-declined"))).toEqual(ZEROS); + expect(await eligible(u, h.id)).toBeNull(); + }); + + it("a withdrawn applicant gets volunteer=0, from the portal", async () => { + const h = await makeHackathon("va-withdrawn"); + const { u } = await apply("va-withdrawn", h.id, "approved"); + await linkAs(u, h.id, acct("va-withdrawn")); + expect(lastFor(acct("va-withdrawn"))).toEqual({ ...ZEROS, volunteer: 1 }); + + await appRouterAs(u).volunteer.withdraw({ hackathonId: h.id }); + expect(lastFor(acct("va-withdrawn"))).toEqual(ZEROS); + expect(await eligible(u, h.id)).toBeNull(); + }); + + it("someone who is a judge and an approved volunteer gets both flags in one link", async () => { + const h = await makeHackathon("va-both"); + const { u } = await newJudge("va-both", h.id); + await apply("va-both", h.id, "approved", u); + expect(await linkAs(u, h.id, acct("va-both"))).toMatchObject({ ok: true, home: "judge" }); + expect(lastFor(acct("va-both"))).toEqual({ ...ZEROS, judge: 1, volunteer: 1 }); + }); + + it("a staff-tier volunteer is unchanged: a declined application does not take the role", async () => { + const h = await makeHackathon("va-staff"); + const u = await makeUser("va-staff"); + await S.db!.insert(S.admins).values({ userId: u, role: "volunteer" }); + expect(await linkAs(u, h.id, acct("va-staff"))).toMatchObject({ ok: true, home: "scan" }); + expect(lastFor(acct("va-staff"))).toEqual({ ...ZEROS, volunteer: 1 }); + + const { decide } = await apply("va-staff", h.id, "approved", u); + expect(lastFor(acct("va-staff"))).toEqual({ ...ZEROS, volunteer: 1 }); + await decide("declined"); + // Still a volunteer by the tier, so what Discord is told does not change. + expect(lastFor(acct("va-staff"))).toEqual({ ...ZEROS, volunteer: 1 }); + expect((await eligible(u, h.id))?.roles.volunteer).toBe(true); + }); + + it("counts from the announcement until the edition is over, and finds the edition without being told", async () => { + const u = await makeUser("va-window"); + const approve = async (hackathonId: string) => + S.db!.insert(S.hackathonVolunteerApplications).values({ + userId: u, + hackathonId, + status: "approved", + mode: "in_person", + answers: APPLICATION as any, + }); + for (const status of ["draft", "completed", "cancelled"]) { + const h = await makeHackathon(`va-w-${status}`, { status }); + await approve(h.id); + expect(await eligible(u, h.id)).toBeNull(); + } + expect(await svc.resolveConnectTarget(S.db as any, u, null)).toBeNull(); + + const announced = await makeHackathon("va-w-announced", { status: "announced" }); + await approve(announced.id); + expect((await eligible(u, announced.id))?.roles.volunteer).toBe(true); + expect((await svc.resolveConnectTarget(S.db as any, u, null))?.hackathon.id).toBe( + announced.id, + ); + }); + + it("a decision Discord cannot take is still owed, and never fails the decision", async () => { + await clearLinks(); + const h = await makeHackathon("va-down"); + const { u, decide } = await apply("va-down", h.id, "approved"); + await linkAs(u, h.id, acct("va-down")); + expect(lastFor(acct("va-down"))).toEqual({ ...ZEROS, volunteer: 1 }); + + world.putStatus = 500; + await expect(decide("declined")).resolves.toMatchObject({ status: "declined" }); + expect(lastFor(acct("va-down"))).toEqual({ ...ZEROS, volunteer: 1 }); + expect((await linkOf(u))?.rolesSig).toBeNull(); + + world.putStatus = 200; + expect(await svc.syncExpiredDiscordRoles(S.db as any)).toEqual({ checked: 1, synced: 1 }); + expect(lastFor(acct("va-down"))).toEqual(ZEROS); + }); + }); + it("a hacker moved out of the accepted statuses, banned, or who withdraws loses the hacker roles", async () => { const h = await makeHackathon("hacker-out"); const admin = await staff("hacker-out-admin"); From f84f47966c83308e28fdbe6effe907c8d65e260b Mon Sep 17 00:00:00 2001 From: aamoghS Date: Fri, 27 Nov 2026 01:17:13 -0500 Subject: [PATCH 5/8] docs: approved volunteer applications hold the Discord volunteer role --- docs/features/discord.md | 6 ++++-- docs/features/hackathons.md | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/features/discord.md b/docs/features/discord.md index 8153e69f..12b07044 100644 --- a/docs/features/discord.md +++ b/docs/features/discord.md @@ -12,7 +12,7 @@ Three roles, held independently. One person can hold several, and the site publi | --- | --- | --- | | Hacker | A participant whose status is `approved` and who pressed "I'm coming" on the hackathon Overview (`attendance_confirmed_at` is set), or who is `checked_in`. Being accepted alone is not enough. | Optional | | Judge | A `judge` row for that edition with `is_active` true, which is what approval sets. A pending, rejected or removed judge holds nothing. | Required | -| Volunteer | An active, unexpired `admin` row with role `volunteer` (added on the staff page). Volunteers are org-wide, not per edition, so the role applies to any edition that is `open`, `closed` or `in_progress`: registration has opened and the event is not over. Not a draft, an announcement, a finished or a cancelled edition. Full staff are not volunteers. | Required | +| Volunteer | An active, unexpired `admin` row with role `volunteer` (added on the staff page). Volunteers are org-wide, not per edition, so the role applies to any edition that is `open`, `closed` or `in_progress`: registration has opened and the event is not over. Not a draft, an announcement, a finished or a cancelled edition. Full staff are not volunteers. Also an `approved` volunteer application for that edition (`isApprovedVolunteer`), from the announcement until the edition is over; a decline, a withdrawal or a pending application holds nothing. Either one is enough. | Required | Judges and volunteers need no registration. The edition is the one in the link (`?hackathon=ID`), or, from Discord's verification URL, the newest edition that is not cancelled or over in which the person holds a role. A confirmed hacker who is also a judge gets both. One Discord account links to one person: `discord_link.discord_user_id` is unique, and the same account may not sit on another person's registration for that hackathon. @@ -36,6 +36,7 @@ It runs after commit on: | --- | --- | | A judge approved, switched off, added or removed | `judge.setActive`, `judge.create`, `judge.remove` | | A volunteer granted, switched off, renewed with a new end date, or removed | `admin.create`, `admin.update`, `admin.remove` | +| A volunteer application approved or declined, or withdrawn by the applicant | `volunteer.decide`, `volunteer.withdraw` | | A hacker's status changed in any direction, banned, or withdrawn | `updateParticipantStatus`, `batchUpdateParticipantStatus`, `banFromHackathons`, `withdrawRegistration`. Moving out of the accepted statuses takes the hacker roles back; moving in can give them, so a judge who is moved to approved after confirming gets the flower role at once. | | Unlink | `unlinkDiscord`: the roles are zeroed with the stored token before the row is deleted. If Discord cannot be reached the unlink fails with an error and nothing is deleted. | | Linking a different Discord account | `completeLink` zeroes the old account first, with the old account's token, then stores the new link. If the old account cannot be reached the link does not move. Linking X, unlinking, then linking Y, or linking Y straight over X, leaves the roles only on Y. | @@ -66,7 +67,8 @@ Not covered: - Judges: a card at the top of the judge page (`/judge`). It reads "Join the Hacklytics Discord. It's required for judges: schedules and room changes are posted there." The approval email and the added-by-organizer email say the same and point to the portal step. - Volunteers: the same card at the top of the check-in desk (`/scan`): "It's required for volunteers: shifts and desk changes are posted there." There is no volunteer email, because a volunteer is added on the staff page and nothing is sent; the card is the notice. -- Someone who is both reads "judges and volunteers". After linking they return to the page the card is on (hackers to the hackathon page, judges to `/judge`, volunteers to `/scan`), or go on to the server invite. +- A volunteer who was approved without the staff tier sees the same card on their application page (`/hackathons//volunteer`) once the application is confirmed, and returns there after linking. +- Someone who is both reads "judges and volunteers". After linking they return to the page the card is on (hackers to the hackathon page, judges to `/judge`, staff-tier volunteers to `/scan`, approved applicants to their application page), or go on to the server invite. - Judges and volunteers have no flower and no Ramadan choice. ## Flowers diff --git a/docs/features/hackathons.md b/docs/features/hackathons.md index 27ecbf42..c94587ec 100644 --- a/docs/features/hackathons.md +++ b/docs/features/hackathons.md @@ -143,7 +143,7 @@ A volunteer runs the weekend (check-in, meals, rooms, help for hackers). It is i - **Organizers** (Volunteers tab next to Judges in the hackathon admin): `volunteer.list` (filters: status, type, in-person role and time block, mentor topic and online hour; coverage counts per time block and role for the venue and per online hour and topic for mentoring, plus how many chose each type, all split approved and pending and taken over everyone so the counts do not move with the filters; someone who chose both counts in both halves), `volunteer.decide` (approve or decline; `isAdmin`, so bug testers and scanner volunteers are refused; audited as `volunteer.approve` and `volunteer.decline`; either can follow the other; a withdrawn application cannot be decided) and `volunteer.exportApplications` (the filtered rows, audited as `volunteer.export`). `list` and `exportApplications` also refuse bug testers: the answers hold phone numbers. The CSV is built in the browser by `lib/volunteer-csv.ts` and carries the type, and the mentor's topics, hours and experience beside the venue's answers. - **Emails** (`sendVolunteerApprovedEmail`, `sendVolunteerDeclinedEmail`, Hacklytics theme for a Hacklytics edition): sent once, on the transition into the status, and best-effort. Nothing is sent on submit. The approval says what their type means: shifts and venue details for in person, the Discord's mentor channels for online, both for both. - **Approving does not grant the `volunteer` staff tier.** That tier is check-in scanner access, and organizers still grant it deliberately on the Staff page. The Volunteers tab says so. -- **Discord.** Eligibility for the volunteer Discord role should use `isApprovedVolunteer(db, userId, hackathonId)` from `@query/api/volunteer` (`packages/api/src/services/volunteer.ts`), not the staff tier and not the table directly. It is true only for an `approved` application at that edition, so a withdrawal or a decline takes it away. +- **Discord.** An `approved` application makes the person eligible for the volunteer Discord role, like the staff tier does (see [Discord](./discord.md)). The role code asks `isApprovedVolunteer` / `approvedVolunteerEditions` in `packages/api/src/services/volunteer.ts`, never the table. `volunteer.decide` (approve or decline) and `volunteer.withdraw` re-sync the person's roles after commit, so a decline or a withdrawal takes the role back. The confirmed state of the application page carries the Discord card. - **Phone.** It lives in `answers.phone` and is only used for contact during the event. Nothing deletes it afterwards yet. ### Content (`content.ts`) From 47fc24b1cd4fb9a2b412e66f242f3d6ac1c3ead5 Mon Sep 17 00:00:00 2001 From: aamoghS Date: Fri, 27 Nov 2026 01:35:17 -0500 Subject: [PATCH 6/8] fix(bans): a ban declines the person's open volunteer applications An approved applicant kept the Discord volunteer role after a ban, because the ban rejected registrations only. It now declines pending and approved volunteer applications in editions that are not over, in the same transaction, and syncs those people's roles. --- .../.internal-tests/discord-link.db.test.ts | 39 +++++++++++ .../hackathon-admin-edge.test.ts | 6 ++ .../.internal-tests/participant-edge.test.ts | 5 ++ packages/api/src/routers/hackathon/bans.ts | 70 +++++++++++++++---- 4 files changed, 105 insertions(+), 15 deletions(-) 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 42d915e4..3bc46eeb 100644 --- a/packages/api/src/.internal-tests/discord-link.db.test.ts +++ b/packages/api/src/.internal-tests/discord-link.db.test.ts @@ -1401,6 +1401,45 @@ describe.skipIf(!URL)("discord link against a real database", () => { expect(await svc.syncExpiredDiscordRoles(S.db as any)).toEqual({ checked: 1, synced: 1 }); expect(lastFor(acct("va-down"))).toEqual(ZEROS); }); + + it("a ban declines the person's open applications and takes the role back, and leaves a finished edition alone", async () => { + const h = await makeHackathon("va-ban"); + const { u } = await apply("va-ban", h.id, "approved"); + await linkAs(u, h.id, acct("va-ban")); + expect(lastFor(acct("va-ban"))).toEqual({ ...ZEROS, volunteer: 1 }); + + // The record of an edition that is over stays as it was. + const done = await makeHackathon("va-ban-done", { status: "completed" }); + await S.db!.insert(S.hackathonVolunteerApplications).values({ + userId: u, + hackathonId: done.id, + status: "approved", + mode: "in_person", + answers: APPLICATION as any, + }); + + const email = ( + await S.db!.select({ email: S.users.email }).from(S.users).where(ops.eq(S.users.id, u)) + )[0]!.email!; + await organizer.hackathon.banFromHackathons({ email, reason: "Testing the ban" }); + await S.db!.delete(S.hackathonBans).where(ops.eq(S.hackathonBans.email, email.toLowerCase())); + + expect(lastFor(acct("va-ban"))).toEqual(ZEROS); + const statusAt = async (hackathonId: string) => + ( + await S.db! + .select({ status: S.hackathonVolunteerApplications.status }) + .from(S.hackathonVolunteerApplications) + .where( + ops.and( + ops.eq(S.hackathonVolunteerApplications.userId, u), + ops.eq(S.hackathonVolunteerApplications.hackathonId, hackathonId), + ), + ) + )[0]?.status; + expect(await statusAt(h.id)).toBe("declined"); + expect(await statusAt(done.id)).toBe("approved"); + }); }); it("a hacker moved out of the accepted statuses, banned, or who withdraws loses the hacker roles", async () => { diff --git a/packages/api/src/.internal-tests/hackathon-admin-edge.test.ts b/packages/api/src/.internal-tests/hackathon-admin-edge.test.ts index f0481780..650a3d76 100644 --- a/packages/api/src/.internal-tests/hackathon-admin-edge.test.ts +++ b/packages/api/src/.internal-tests/hackathon-admin-edge.test.ts @@ -158,6 +158,12 @@ vi.mock("@query/db", () => { email: "email", createdAt: "created_at", }, + hackathonVolunteerApplications: { + _t: "hackathonVolunteerApplications", + userId: "user_id", + hackathonId: "hackathon_id", + status: "status", + }, userProfiles: { _t: "userProfiles", userId: "user_id" }, hackathons: { _t: "hackathons", diff --git a/packages/api/src/.internal-tests/participant-edge.test.ts b/packages/api/src/.internal-tests/participant-edge.test.ts index c3403112..7bef5485 100644 --- a/packages/api/src/.internal-tests/participant-edge.test.ts +++ b/packages/api/src/.internal-tests/participant-edge.test.ts @@ -137,6 +137,11 @@ vi.mock("@query/db", async () => { users: { id: "id", email: "email", name: "name", image: "image" }, userProfiles: { userId: "user_id" }, hackathonBans: { id: "id", email: "email" }, + hackathonVolunteerApplications: { + userId: "user_id", + hackathonId: "hackathon_id", + status: "status", + }, memberResumes: { userId: "user_id" }, hackathons: { id: "id", diff --git a/packages/api/src/routers/hackathon/bans.ts b/packages/api/src/routers/hackathon/bans.ts index e62e27d6..f3494fd8 100644 --- a/packages/api/src/routers/hackathon/bans.ts +++ b/packages/api/src/routers/hackathon/bans.ts @@ -1,6 +1,12 @@ import { z } from "zod"; import { and, eq, inArray, ne, notInArray, sql } from "drizzle-orm"; -import { hackathonBans, hackathonParticipants, hackathons, users } from "@query/db"; +import { + hackathonBans, + hackathonParticipants, + hackathonVolunteerApplications, + hackathons, + users, +} from "@query/db"; import type { DrizzleDB } from "@query/db"; import { createTRPCRouter } from "../../trpc"; import { hackathonBanCacheKey, isAdmin } from "../../middleware/procedures"; @@ -80,8 +86,10 @@ export const hackathonBansRouter = createTRPCRouter({ // banned person's pending or accepted row would otherwise still be // picked by acceptWave, mailed, or scanned in. The ban is by email and // covers every hackathon, so it rejects in every hackathon that is - // still running; finished ones stay as the record of who took part. - const { ban, rejectedUserIds } = await db.transaction(async (tx) => { + // still running; finished ones stay as the record of who took part. Their + // volunteer applications are declined the same way, or an approved one + // would keep the volunteer role. + const { ban, rejectedUserIds, declinedUserIds } = await db.transaction(async (tx) => { // Re-banning updates the reason instead of failing on the unique email. const [ban] = await tx .insert(hackathonBans) @@ -118,23 +126,55 @@ export const hackathonBansRouter = createTRPCRouter({ userId: hackathonParticipants.userId, hackathonId: hackathonParticipants.hackathonId, }); - // Rejected, so a linked Discord account is owed a sync. - await markDiscordRolesPending( - tx as unknown as DrizzleDB, - rejected.map((row) => row.userId), - ); - - return { ban, rejectedUserIds: rejected }; + const declined = await tx + .update(hackathonVolunteerApplications) + .set({ + status: "declined", + reviewedById: ctx.userId as string, + reviewedAt: new Date(), + updatedAt: new Date(), + }) + .where( + and( + inArray(hackathonVolunteerApplications.status, ["pending", "approved"]), + inArray( + hackathonVolunteerApplications.userId, + tx + .select({ id: users.id }) + .from(users) + .where(sql`lower(${users.email}) = ${email}`), + ), + inArray( + hackathonVolunteerApplications.hackathonId, + tx + .select({ id: hackathons.id }) + .from(hackathons) + .where(notInArray(hackathons.status, ["completed", "cancelled"])), + ), + ), + ) + .returning({ userId: hackathonVolunteerApplications.userId }); + // Rejected or declined, so a linked Discord account is owed a sync. + await markDiscordRolesPending(tx as unknown as DrizzleDB, [ + ...rejected.map((row) => row.userId), + ...declined.map((row) => row.userId), + ]); + + return { + ban, + rejectedUserIds: rejected, + declinedUserIds: declined.map((row) => row.userId), + }; }); for (const row of rejectedUserIds) { evictParticipantCaches(ctx.cache, row.hackathonId, [row.userId]); } - // Rejected, so any Discord roles they linked come back off. - await syncDiscordRolesFor( - db, - rejectedUserIds.map((row) => row.userId), - ); + // Rejected or declined, so any Discord roles they linked come back off. + await syncDiscordRolesFor(db, [ + ...rejectedUserIds.map((row) => row.userId), + ...declinedUserIds, + ]); ctx.cache.delete(hackathonBanCacheKey(email)); From 2a3d4ff418f63e7ab961e33ede69b502636539b2 Mon Sep 17 00:00:00 2001 From: aamoghS Date: Fri, 27 Nov 2026 01:39:14 -0500 Subject: [PATCH 7/8] feat(discord): an edition that ends takes its Discord roles with it Moving an edition to completed or cancelled (or back) marks every linked participant, judge, approved volunteer and volunteer-tier staff member pending in the status transaction, then syncs up to 100 of them inline. The daily job clears the rest. rolesFor now returns no role for an edition that is over. --- .../.internal-tests/discord-link.db.test.ts | 82 +++++++++++++++++++ packages/api/src/routers/hackathon/crud.ts | 35 +++++++- .../api/src/services/discord/discord.test.ts | 14 ++++ packages/api/src/services/discord/roles.ts | 6 ++ packages/api/src/services/discord/sync.ts | 64 ++++++++++++++- 5 files changed, 197 insertions(+), 4 deletions(-) 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 3bc46eeb..aa314b11 100644 --- a/packages/api/src/.internal-tests/discord-link.db.test.ts +++ b/packages/api/src/.internal-tests/discord-link.db.test.ts @@ -1440,6 +1440,88 @@ describe.skipIf(!URL)("discord link against a real database", () => { expect(await statusAt(h.id)).toBe("declined"); expect(await statusAt(done.id)).toBe("approved"); }); + + describe("an edition ending", () => { + /** A hacker, a judge and an approved volunteer of one edition, each linked. */ + const linkedPeople = async (hackathonId: string, tag: string) => { + const hacker = await makeUser(`${tag}-h`); + await makeParticipant(hackathonId, hacker); + const { u: judge } = await newJudge(`${tag}-j`, hackathonId); + const { u: volunteer } = await apply(`${tag}-v`, hackathonId, "approved"); + const people = [ + { u: hacker, account: acct(`${tag}-h`) }, + { u: judge, account: acct(`${tag}-j`) }, + { u: volunteer, account: acct(`${tag}-v`) }, + ]; + for (const person of people) await linkAs(person.u, hackathonId, person.account); + expect(lastFor(people[0]!.account)).toMatchObject({ accepted: 1 }); + expect(lastFor(people[1]!.account)).toMatchObject({ judge: 1 }); + expect(lastFor(people[2]!.account)).toMatchObject({ volunteer: 1 }); + return people; + }; + + for (const status of ["completed", "cancelled"] as const) { + it(`${status} takes every role for it back at once`, async () => { + const h = await makeHackathon(`va-end-${status}`); + const people = await linkedPeople(h.id, `va-end-${status}`); + + await organizer.hackathon.update({ id: h.id, status }); + for (const { account } of people) expect(lastFor(account)).toEqual(ZEROS); + }); + } + + it("reopening an edition that was ended by mistake gives the roles back", async () => { + const h = await makeHackathon("va-end-undo"); + const people = await linkedPeople(h.id, "va-end-undo"); + await organizer.hackathon.update({ id: h.id, status: "completed" }); + for (const { account } of people) expect(lastFor(account)).toEqual(ZEROS); + + await organizer.hackathon.update({ id: h.id, status: "open" }); + expect(lastFor(people[0]!.account)).toMatchObject({ accepted: 1 }); + expect(lastFor(people[1]!.account)).toMatchObject({ judge: 1 }); + expect(lastFor(people[2]!.account)).toMatchObject({ volunteer: 1 }); + }); + + it("marks everyone linked to the edition pending in the same change, and two sweeps zero them", async () => { + await clearLinks(); + const h = await makeHackathon("va-end-sweep"); + const people = await linkedPeople(h.id, "va-end-sweep"); + // A judge of another edition is not part of it. + const other = await makeHackathon("va-end-other"); + const { u: bystander } = await newJudge("va-end-by", other.id); + await linkAs(bystander, other.id, acct("va-end-by")); + const sigsOf = async (ids: string[]) => + new Map( + ( + await S.db! + .select({ u: S.discordLinks.userId, sig: S.discordLinks.rolesSig }) + .from(S.discordLinks) + .where(ops.inArray(S.discordLinks.userId, ids)) + ).map((r) => [r.u, r.sig]), + ); + + // With no token secret nothing can be published inline, so what the + // change itself marked is all that shows. + vi.stubEnv("AUTH_SECRET", ""); + await organizer.hackathon.update({ id: h.id, status: "completed" }); + vi.stubEnv("AUTH_SECRET", SECRET); + const sigs = await sigsOf([...people.map((p) => p.u), bystander]); + for (const { u } of people) expect(sigs.get(u)).toBeNull(); + expect(sigs.get(bystander)).not.toBeNull(); + + expect(await svc.syncExpiredDiscordRoles(S.db as any, { limit: 2 })).toEqual({ + checked: 2, + synced: 2, + }); + expect(await svc.syncExpiredDiscordRoles(S.db as any, { limit: 2 })).toEqual({ + checked: 1, + synced: 1, + }); + for (const { account } of people) expect(lastFor(account)).toEqual(ZEROS); + expect(lastFor(acct("va-end-by"))).toEqual({ ...ZEROS, judge: 1 }); + expect(await svc.syncExpiredDiscordRoles(S.db as any)).toEqual({ checked: 0, synced: 0 }); + }); + }); }); it("a hacker moved out of the accepted statuses, banned, or who withdraws loses the hacker roles", async () => { diff --git a/packages/api/src/routers/hackathon/crud.ts b/packages/api/src/routers/hackathon/crud.ts index 8fb5ecc3..7d38f023 100644 --- a/packages/api/src/routers/hackathon/crud.ts +++ b/packages/api/src/routers/hackathon/crud.ts @@ -16,6 +16,11 @@ import { recordAdminAction } from "../../middleware/audit"; import { CacheKeys, VOLATILE_TTL } from "../../middleware/cache"; import type { DrizzleDB } from "@query/db"; import { seatedCounts, withSeatedCounts } from "../../services/derived-counts"; +import { + isOverEdition, + markEditionRolesPending, + syncDiscordRolesFor, +} from "../../services/discord"; // Every hackathon read below returns currentParticipants counted from the // participant rows (one grouped query per call). The stored column is retired: @@ -475,9 +480,14 @@ export const hackathonCrudRouter = createTRPCRouter({ }); } - let updatedHackathon; - try { - [updatedHackathon] = await (ctx.db as DrizzleDB) + // An edition that ends takes its Discord roles with it, and one that is + // reopened gives them back. Everyone linked who held one is marked pending + // in the same transaction as the status. + const flips = + !!updateData.status && + isOverEdition(updateData.status) !== isOverEdition(existing.status); + const write = (db: DrizzleDB) => + db .update(hackathons) .set({ ...updateData, @@ -485,6 +495,21 @@ export const hackathonCrudRouter = createTRPCRouter({ }) .where(eq(hackathons.id, id)) .returning(); + let updatedHackathon; + let owed: string[] = []; + try { + if (flips) { + [updatedHackathon] = await (ctx.db as DrizzleDB).transaction( + async (tx) => { + const db = tx as unknown as DrizzleDB; + const rows = await write(db); + owed = await markEditionRolesPending(db, id); + return rows; + }, + ); + } else { + [updatedHackathon] = await write(ctx.db as DrizzleDB); + } } catch (error) { if (isUniqueViolation(error)) { throw new TRPCError({ @@ -495,6 +520,10 @@ export const hackathonCrudRouter = createTRPCRouter({ throw error; } + // As many as one request has time for are cleared now; the daily job + // takes the rest. + await syncDiscordRolesFor(ctx.db as DrizzleDB, owed); + ctx.cache.delete(CacheKeys.hackathon(id)); ctx.cache.deletePattern("hackathons:*"); diff --git a/packages/api/src/services/discord/discord.test.ts b/packages/api/src/services/discord/discord.test.ts index 8f67d7d4..70429799 100644 --- a/packages/api/src/services/discord/discord.test.ts +++ b/packages/api/src/services/discord/discord.test.ts @@ -184,6 +184,20 @@ describe("discord roles", () => { } }); + it("holds no role at all in an edition that is over", () => { + for (const hackathonStatus of ["completed", "cancelled"]) { + expect( + rolesFor({ + participant: hacker("approved", at), + judge: true, + staff: true, + approvedVolunteer: true, + hackathonStatus, + }), + ).toEqual(NO_ROLES); + } + }); + it("reports whether anyone holds a role", () => { expect(hasDiscordRole(NO_ROLES)).toBe(false); expect(hasDiscordRole({ ...NO_ROLES, volunteer: true })).toBe(true); diff --git a/packages/api/src/services/discord/roles.ts b/packages/api/src/services/discord/roles.ts index 8fc35728..b802d5b5 100644 --- a/packages/api/src/services/discord/roles.ts +++ b/packages/api/src/services/discord/roles.ts @@ -60,6 +60,9 @@ export const VOLUNTEER_EDITION_STATUSES = [ const isVolunteerEdition = (status: string) => (VOLUNTEER_EDITION_STATUSES as readonly string[]).includes(status); +export const isOverEdition = (status: string) => + status === "completed" || status === "cancelled"; + /** * An approved volunteer application is for one edition and is taken from the * announcement on, since that is when applications open. Not a draft, a @@ -85,6 +88,9 @@ export function rolesFor(input: { approvedVolunteer: boolean; hackathonStatus: string; }): DiscordRoles { + // An edition that is over holds nobody to a role: its hackers, judges and + // volunteers lose them at the next sync. + if (isOverEdition(input.hackathonStatus)) return { ...NO_ROLES }; return { hacker: !!input.participant && isConfirmedHacker(input.participant), judge: input.judge, diff --git a/packages/api/src/services/discord/sync.ts b/packages/api/src/services/discord/sync.ts index 18a814a7..22d22c83 100644 --- a/packages/api/src/services/discord/sync.ts +++ b/packages/api/src/services/discord/sync.ts @@ -5,7 +5,13 @@ // A link made before tokens were kept has none, and cannot be revoked here. import { and, eq, inArray, isNotNull, isNull, like, lte, or, sql } from "drizzle-orm"; -import { admins, discordLinks, hackathonParticipants } from "@query/db"; +import { + admins, + discordLinks, + hackathonParticipants, + hackathonVolunteerApplications, + judges, +} from "@query/db"; import type { DrizzleDB } from "@query/db"; import { putRoleConnection, refusal, safeMessage } from "./api"; import { discordConfig, discordTokenSecret } from "./config"; @@ -232,6 +238,62 @@ export async function markDiscordRolesPending( .where(inArray(discordLinks.userId, [...new Set(userIds)])); } +/** + * Marks every linked person who holds a role for one edition as owing a sync, + * for when the edition ends. That is its participants, its judges, those + * approved to volunteer at it, and the volunteer staff tier, whose role follows + * whichever editions are live. Returns the ones it marked. Called inside the + * transaction of the status change, like `markDiscordRolesPending`; the daily + * job clears whoever the request does not reach. + */ +export async function markEditionRolesPending( + db: DrizzleDB, + hackathonId: string, +): Promise { + const rows = await db + .update(discordLinks) + .set({ rolesSig: null }) + .where( + or( + inArray( + discordLinks.userId, + db + .select({ id: hackathonParticipants.userId }) + .from(hackathonParticipants) + .where(eq(hackathonParticipants.hackathonId, hackathonId)), + ), + inArray( + discordLinks.userId, + db + .select({ id: judges.userId }) + .from(judges) + .where(eq(judges.hackathonId, hackathonId)), + ), + inArray( + discordLinks.userId, + db + .select({ id: hackathonVolunteerApplications.userId }) + .from(hackathonVolunteerApplications) + .where( + and( + eq(hackathonVolunteerApplications.hackathonId, hackathonId), + eq(hackathonVolunteerApplications.status, "approved"), + ), + ), + ), + inArray( + discordLinks.userId, + db + .select({ id: admins.userId }) + .from(admins) + .where(and(eq(admins.role, "volunteer"), eq(admins.isActive, true))), + ), + ), + ) + .returning({ userId: discordLinks.userId }); + return rows.map((row) => row.userId); +} + /** * Re-derives what the person holds now and publishes it, or all zeros when * they hold nothing. Call it after the change that could revoke or grant a From a36bee1ccc6431484cb41e546b3d84c51611630d Mon Sep 17 00:00:00 2001 From: aamoghS Date: Fri, 27 Nov 2026 01:40:06 -0500 Subject: [PATCH 8/8] docs: a ban declines volunteer applications, and an ending edition clears Discord roles --- docs/features/discord.md | 5 +++-- docs/features/hackathons.md | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/features/discord.md b/docs/features/discord.md index 12b07044..f1039559 100644 --- a/docs/features/discord.md +++ b/docs/features/discord.md @@ -37,7 +37,8 @@ It runs after commit on: | A judge approved, switched off, added or removed | `judge.setActive`, `judge.create`, `judge.remove` | | A volunteer granted, switched off, renewed with a new end date, or removed | `admin.create`, `admin.update`, `admin.remove` | | A volunteer application approved or declined, or withdrawn by the applicant | `volunteer.decide`, `volunteer.withdraw` | -| A hacker's status changed in any direction, banned, or withdrawn | `updateParticipantStatus`, `batchUpdateParticipantStatus`, `banFromHackathons`, `withdrawRegistration`. Moving out of the accepted statuses takes the hacker roles back; moving in can give them, so a judge who is moved to approved after confirming gets the flower role at once. | +| An edition moved to or from `completed` or `cancelled` | `hackathon.update` | +| A hacker's status changed in any direction, banned (which also declines their volunteer applications), or withdrawn | `updateParticipantStatus`, `batchUpdateParticipantStatus`, `banFromHackathons`, `withdrawRegistration`. Moving out of the accepted statuses takes the hacker roles back; moving in can give them, so a judge who is moved to approved after confirming gets the flower role at once. | | Unlink | `unlinkDiscord`: the roles are zeroed with the stored token before the row is deleted. If Discord cannot be reached the unlink fails with an error and nothing is deleted. | | Linking a different Discord account | `completeLink` zeroes the old account first, with the old account's token, then stores the new link. If the old account cannot be reached the link does not move. Linking X, unlinking, then linking Y, or linking Y straight over X, leaves the roles only on Y. | @@ -50,7 +51,7 @@ If Discord answers `invalid_grant` to a refresh, the person withdrew the connect Not covered: - **Links made before tokens were stored** have no token, so their roles cannot be changed from here. Today that is hackers' `accepted`, flower and Ramadan values, since judges and volunteers could not link before. To revoke one by hand, ask the person to remove the Hacklytics connection under Discord Settings > Connections, or to press "Update my roles" in the portal (which stores a token, after which everything above applies). Taking the server role away by hand is not enough on its own: Linked Roles lets them claim it again while their metadata still qualifies. -- **An edition ending** does not clear anything. A judge or volunteer role stays on until the person is removed, unlinks or their term expires. Hacker roles stay too. +- **An edition ending** clears its roles. `rolesFor` gives no hacker, judge or volunteer role for a `completed` or `cancelled` edition. Moving an edition to either (or back) with `hackathon.update` marks everyone linked who held a role for it pending, in the status transaction (`markEditionRolesPending`: participants, judges, approved volunteer applicants and the volunteer staff tier, whose role follows whichever editions are live), then syncs up to 100 of them inline. The daily job takes the rest, 15 a run, so a large edition takes days to clear fully. - There is no way to un-confirm "I'm coming" from the portal; an organizer changing the status is what takes a hacker's roles back. - A person whose roles apply in more than one live edition is synced for the newest, the same one a fresh link uses. diff --git a/docs/features/hackathons.md b/docs/features/hackathons.md index c94587ec..62fe71bc 100644 --- a/docs/features/hackathons.md +++ b/docs/features/hackathons.md @@ -98,7 +98,7 @@ Roles come from `packages/api/src/middleware/procedures.ts`. `isAdmin` is full s | `list` | public | Hides `draft` and non-public editions for non-admins. Cached per caller type. | | `listAll` | admin | Every edition. | | `getById` | public | Takes an id, exact name or slug. | -| `create`, `update` | admin | Names must be unique, since they appear in admin links. End must follow start. | +| `create`, `update` | admin | Names must be unique, since they appear in admin links. End must follow start. Moving an edition to `completed` or `cancelled` (or back) marks its linked Discord accounts pending in the same transaction and syncs up to 100 inline; the daily job takes the rest (see [Discord](./discord.md#taking-roles-back)). | | `delete` | super admin | Needs `confirmName` typed to match. Every child table (participants, teams, projects, events, announcements, legacy votes and results, all `judging_*`, points and store) cascades. | ### Acceptance (`admin.ts`) @@ -128,7 +128,7 @@ Audiences: `interested`, `registered`, `approved`, `checked_in`, `not_accepted`, ### Bans (`bans.ts`) -`listBans`, `banFromHackathons`, `liftHackathonBan`. A ban is keyed by lowercase email in `hackathon_ban` and leaves club membership alone. Enforcement is the `notHackathonBanned` procedure, used by `register`, `registerInterest`, `updateMyRegistration`, `confirmAttendance`, `createTeam`, `joinTeam`, `submitProject`, the event-code `checkIn`, judge `register` and `judging.hacker.claimByEmail`, `claimByToken` and `invite`. Withdrawing is not blocked. Ban and unban write audit records and clear the ban cache. +`listBans`, `banFromHackathons`, `liftHackathonBan`. A ban is keyed by lowercase email in `hackathon_ban` and leaves club membership alone. It also rejects the person's registrations and declines their pending and approved volunteer applications in every edition that is not over, in the same transaction, and syncs their Discord roles. Enforcement is the `notHackathonBanned` procedure, used by `register`, `registerInterest`, `updateMyRegistration`, `confirmAttendance`, `createTeam`, `joinTeam`, `submitProject`, the event-code `checkIn`, judge `register` and `judging.hacker.claimByEmail`, `claimByToken` and `invite`. Withdrawing is not blocked. Ban and unban write audit records and clear the ban cache. ### Volunteers (`routers/volunteer/`)