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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ Edition-scoped event operations. Everything hangs off `hackathon`.
- Editions, interest list, registration, teams, project submission
- Weekend schedule (`hackathon_event`) and badge scans
- Judge roster (`judge`, `judge_assignment`): applications and approval
- Judging: room-based judging with Devpost import — `judging_*` tables (`judging.ts`). The older pool-dispatch tables (`judging_project`, `judge_vote`, `judge_queue`, `hackathon_result`) are retired and kept for past editions' results
- Judging: room-based judging with Devpost import — `judging_*` tables (`judging.ts`). The older pool-dispatch tables (`judging_project`, `judge_vote`, `hackathon_result`) are retired and kept for past editions' results
- Points: `hackathon_event` points, staff adjustments and the point store (`points.ts`)
- Event check-in rules: nobody is checked into two events that run at the same time, or into two less than 30 minutes apart (meals are exempt). `recordEventAttendance` enforces this for pass scans, event codes and manual check-in
- Check-in rule-break flags: each refused attempt is recorded (`hackathon_check_in_flag`, `services/check-in-flags.ts`) and shown in judging on the hacker's team, in full to organisers and as a bare marker to judges. Organisers decide whether to pull the team from prizes (`judging_entry.prize_ineligible_at`). A flag outlives the events it names (deleting one clears its id and the organiser view shows "A deleted event"). Hackers never see flags, and they stay out of public and cached payloads
Expand Down
2 changes: 1 addition & 1 deletion docs/bootcamp-materials.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,4 @@ An upload and a removal of the same file can race, because the object write and

## Legacy table

`bootcamp_material` (#390's per-event handouts) is still declared in the schema, but nothing reads or writes it. Deploys run `drizzle-kit push`, and removing the declaration would make push stop at a DROP TABLE prompt. Drop the table in a separate change.
`bootcamp_material` (#390's per-event handouts) was dropped in November 2026 (`packages/db/sql/2026-11-drop-retired.sql`); nothing had read or written it since `bootcamp_workshop` replaced it.
4 changes: 2 additions & 2 deletions docs/features/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ sequenceDiagram
| Already has a row for this event | `CONFLICT` "Already checked in" |
| Count of `event_check_in` rows `>= maxCheckIns` (event row locked `FOR UPDATE`, only when capped) | `BAD_REQUEST` "Event is full" |

There is no earliest time: a scan is accepted before the event starts. Membership is not checked. The member row is looked up only so a member's check-in carries `member_id`. The `events.membersOnly` column is no longer read.
There is no earliest time: a scan is accepted before the event starts. Membership is not checked. The member row is looked up only so a member's check-in carries `member_id`.

The 24 hour limit matches the public list, which stops marking an event open after the same cutoff, so a photographed QR cannot keep admitting people.

Expand Down Expand Up @@ -119,7 +119,7 @@ The scanner hook (`components/portal/EventCheckIn.tsx`) also recognises a hackat
| `event` | `title`, `event_date`, `qr_code` (unique), `check_in_enabled`, `max_check_ins`, `bootcamp_week`, `bootcamp_term`, `bootcamp_only`, `kind` (generated), `created_by_id` |
| `event_check_in` | `event_id`, `user_id`, `member_id` (null for non-members), `check_in_method` (`qr_code` or `manual`), `checked_in_at`. Unique on `(event_id, user_id)` |

The check-in count is `count(*)` of `event_check_in` rows, taken under the event row lock for the capacity check and as a subquery for `currentCheckIns` in event reads. The old `current_check_ins` column is no longer read or written and will be dropped in a later change.
The check-in count is `count(*)` of `event_check_in` rows, taken under the event row lock for the capacity check, and by one grouped query per list for `currentCheckIns` in event reads (`services/derived-counts.ts`). There is no stored counter.

## Code and tests

Expand Down
2 changes: 1 addition & 1 deletion docs/features/hackathons.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ Roles come from `packages/api/src/middleware/procedures.ts`. `isAdmin` is full s
| `sendMassAcceptanceEmails` | Mails accepted people in batches. Resumable per person through `acceptance_email_sent_at`. |
| `analytics` | Counts for the dashboard. |

`max_participants` caps acceptances, not applications. Seats taken are counted from `approved` plus `checked_in` rows on every read (`currentParticipants` in hackathon reads) and under the hackathon row lock in `assertSeats`. The `current_participants` and team `current_members` columns are no longer read or written and will be dropped in a later change.
`max_participants` caps acceptances, not applications. Seats taken are counted from `approved` plus `checked_in` rows on every read (`currentParticipants` in hackathon reads) and under the hackathon row lock in `assertSeats`. A team's `currentMembers` is its participant rows the same way. Neither is a stored column.

### Interest list (`interest.ts`)

Expand Down
2 changes: 1 addition & 1 deletion docs/features/judge-portal.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ Schema: `packages/db/src/schemas/judge.ts`.
| `judge_assignment` | The application: edition, `track`, `status` (`pending`, `approved`, `rejected`), `is_lead`. |
| `judge_interest` | Public interest leads from the Hacklytics site (above). |

The same file also declares `judging_project`, `judge_vote`, `hackathon_result` and `judge_queue` from the retired pool-dispatch judging. Nothing writes them now, but past editions' data stays, and `hackathon.getResults` still reads `hackathon_result`.
The same file also declares `judging_project`, `judge_vote` and `hackathon_result` from the retired pool-dispatch judging. Nothing writes them now, but past editions' data stays, and `hackathon.getResults` still reads `hackathon_result`.

## Code and tests

Expand Down
2 changes: 1 addition & 1 deletion docs/judging/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ The order is a checklist, not a hard gate. `judging.admin.checklist` reports sev
| `judging_repo_check` | Per project: GitHub last-push check against the submission deadline and the organiser decision, see [repo check](./repo-check.md) |
| `judging_announcement` | The pinned message for all judges or one room |

The older `judging_project`, `judge_vote`, `judge_queue` and `hackathon_result` tables are retired and kept for past editions. `hackathon.getResults` still merges their published rows with new placements.
The older `judging_project`, `judge_vote` and `hackathon_result` tables are retired and kept for past editions. `hackathon.getResults` still merges their published rows with new placements.

## Where the code lives

Expand Down
16 changes: 13 additions & 3 deletions docs/packages/db.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ Files in `src/schemas/`, re-exported from `schemas/index.ts`. `drizzle.config.ts
| `members.ts` | `user_profile`, `member`, `membership_history` |
| `admins.ts` | `admin` |
| `hackathons.ts` | `hackathon`, `hackathon_team`, `hackathon_participant`, `hackathon_project`, `hackathon_interest`, `hackathon_event`, `hackathon_event_attendee`, `hackathon_check_in_flag`, `hackathon_announcement`, `hackathon_announcement_recipient` |
| `judge.ts` | `judge`, `judge_assignment` (live roster); `judging_project`, `judge_vote`, `judge_queue`, `hackathon_result` (retired, kept for past editions) |
| `judge.ts` | `judge`, `judge_assignment` (live roster); `judging_project`, `judge_vote`, `hackathon_result` (retired, kept for past editions) |
| `judging.ts` | `judging_*`: config, entries and members, challenges, buildings, rooms and room links, judges, guest sessions, presence, schedule and appointments, rubric, evaluations, deliberation, placements, repo checks |
| `points.ts` | `hackathon_point_adjustment`, `hackathon_store_item`, `hackathon_store_purchase` |
| `retired.ts` | Enum types the retired panel judging service left in the database, declared so push does not try to drop them |
| `initiatives.ts` | `project_leader`, `initiative`, `initiative_application` |
| `events.ts` | `event`, `event_check_in` |
| `bootcamp.ts` | `bootcamp_workshop` (metadata; the ZIPs are in Cloud Storage). `bootcamp_material` is legacy and unused |
| `bootcamp.ts` | `bootcamp_workshop` (metadata; the ZIPs are in Cloud Storage) |
| `stripe.ts` | `stripe_payment`, `user_account_link` |
| `security.ts` | `audit_logs` (+ `security_severity` enum) |
| `settings.ts` | `system_settings` (single row, `id = 'default'`) |
Expand Down Expand Up @@ -122,7 +122,7 @@ erDiagram
judging_entry ||--o{ judging_placement : "final placement"
```

Other tables include: `user_profile`, `club_project`, `subteam` and `subteam_application`, `member_resume`, `bootcamp_workshop` and `bootcamp_material`, `hackathon_announcement` and recipients, `hackathon_ban`, `hackathon_check_in_flag`, point adjustments, store items and purchases, `audit_logs`, `system_settings`, `admin`, `project_leader`, `user_account_link`, `verificationToken`, `judging_announcement`, `judging_rubric_item`, `judging_evaluation_draft` and `judging_evaluation_response`. The older `judging_project`, `judge_vote`, `judge_queue` and `hackathon_result` tables are retired and kept for past editions.
Other tables include: `user_profile`, `club_project`, `subteam` and `subteam_application`, `member_resume`, `bootcamp_workshop`, `hackathon_announcement` and recipients, `hackathon_ban`, `hackathon_check_in_flag`, point adjustments, store items and purchases, `audit_logs`, `system_settings`, `admin`, `project_leader`, `user_account_link`, `verificationToken`, `judging_announcement`, `judging_rubric_item`, `judging_evaluation_draft` and `judging_evaluation_response`. The older `judging_project`, `judge_vote` and `hackathon_result` tables are retired and kept for past editions.

## Membership service

Expand All @@ -148,6 +148,16 @@ pnpm --filter @query/db db:seed # scripts/seed.ts

The repo is **push-based**: `packages/db/drizzle/meta/_journal.json` has no migration entries. App Hosting runs `drizzle-kit push --verbose < /dev/null` then `db:check`. Destructive prompts cannot be confirmed, so the push aborts rather than dropping columns; `db:check` is the real gate (push can still exit 0).

### Dropping a column or table

Push never drops anything in a deploy, so a drop ships as two things in one change: the schema stops declaring it, and a file in `packages/db/sql/` drops it. Run that file against production **before** the change deploys:

```bash
psql "$PROD_DATABASE_URL" -v ON_ERROR_STOP=1 -f packages/db/sql/<file>.sql
```

The other order is the dangerous one. If the schema stops declaring a column production still has, every later push stops at the data-loss prompt and applies nothing, so new columns stop reaching production too. Each file runs in one transaction and uses `IF EXISTS`, so a failure changes nothing and a second run is a no-op. Rehearse it on a PGX clone first: run the file, then `migrate:push` should report no drops, and `db:check` should pass.

`scripts/link-payments.ts` is a one-off to attach historical paid Stripe rows to matching user emails:

```bash
Expand Down
32 changes: 10 additions & 22 deletions packages/api/src/.internal-tests/derived-counts.db.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ import type * as CountHelpers from "../services/derived-counts";
*
* Needs TEST_DATABASE_URL (a local, disposable database; never Neon or
* production) and skips without it. It inserts its own rows under a random
* suffix and removes them afterwards. The stored counters are set to wrong
* numbers on purpose, so a read that still used them would fail.
* suffix and removes them afterwards.
*/
const URL = process.env.TEST_DATABASE_URL;

Expand Down Expand Up @@ -58,23 +57,22 @@ describe.skipIf(!URL)("derived counts against a real database", () => {
userIds.map((id) => ({ id, email: `${id}@example.test`, name: id })),
);

// Event with 3 check-ins and a stored counter of 99.
// Event with 3 check-ins.
const [event] = await db
.insert(S.events)
.values({
title: `dc event ${suffix}`,
eventDate: new Date(),
qrCode: crypto.randomUUID(),
createdById: userIds[0]!,
currentCheckIns: 99,
})
.returning({ id: S.events.id });
eventId = event!.id;
await db.insert(S.eventCheckIns).values(
userIds.slice(0, 3).map((userId) => ({ eventId, userId })),
);

// Capped event: cap 2, two real rows, stored counter 0.
// Capped event: cap 2, two real rows.
cappedQr = crypto.randomUUID();
const [capped] = await db
.insert(S.events)
Expand All @@ -84,16 +82,14 @@ describe.skipIf(!URL)("derived counts against a real database", () => {
qrCode: cappedQr,
createdById: userIds[0]!,
maxCheckIns: 2,
currentCheckIns: 0,
})
.returning({ id: S.events.id });
cappedEventId = capped!.id;
await db.insert(S.eventCheckIns).values(
userIds.slice(0, 2).map((userId) => ({ eventId: cappedEventId, userId })),
);

// Hackathon: 2 approved + 1 checked_in + 2 pending/rejected = 3 seats,
// stored counter 42.
// Hackathon: 2 approved + 1 checked_in + 2 pending/rejected = 3 seats.
const [hackathon] = await db
.insert(S.hackathons)
.values({
Expand All @@ -102,7 +98,6 @@ describe.skipIf(!URL)("derived counts against a real database", () => {
endDate: new Date(Date.now() + 2 * 86_400_000),
status: "open",
maxParticipants: 10,
currentParticipants: 42,
})
.returning({ id: S.hackathons.id });
hackathonId = hackathon!.id;
Expand All @@ -114,13 +109,11 @@ describe.skipIf(!URL)("derived counts against a real database", () => {
hackathonId,
name: `dc team ${suffix}`,
captainId: userIds[0]!,
currentMembers: 7,
},
{
hackathonId,
name: `dc empty ${suffix}`,
captainId: userIds[5]!,
currentMembers: 3,
},
])
.returning({ id: S.hackathonTeams.id });
Expand Down Expand Up @@ -194,7 +187,7 @@ describe.skipIf(!URL)("derived counts against a real database", () => {
expect(counts.size).toBe(0);
});

it("events.list returns the row count, not the stored counter", async () => {
it("events.list returns the row count", async () => {
const { cache } = await import("../middleware/cache");
cache.clear();
const list = await appRouter.createCaller(ctx()).events.list();
Expand All @@ -205,7 +198,7 @@ describe.skipIf(!URL)("derived counts against a real database", () => {
);
});

it("hackathon.getById returns the seats held by rows, not the stored counter", async () => {
it("hackathon.getById returns the seats held by rows", async () => {
const { cache } = await import("../middleware/cache");
cache.clear();
const row = await appRouter
Expand All @@ -223,7 +216,7 @@ describe.skipIf(!URL)("derived counts against a real database", () => {
).toBe(3);
});

it("team.list returns the roster size, not the stored counter", async () => {
it("team.list returns the roster size", async () => {
const { cache } = await import("../middleware/cache");
cache.clear();
const teams = await appRouter
Expand All @@ -235,18 +228,18 @@ describe.skipIf(!URL)("derived counts against a real database", () => {
);
});

it("refuses a check-in when rows fill the event although the stored counter reads 0", async () => {
it("refuses a check-in when the rows fill the event", async () => {
await expect(
appRouter
.createCaller(ctx(userIds[4]))
.events.checkIn({ qrCode: cappedQr }),
).rejects.toMatchObject({ message: "Event is full" });
});

it("admits a check-in once the rows leave room although the stored counter reads full", async () => {
it("admits a check-in once a row leaves room", async () => {
const db = S.db!;
const { and, eq } = drizzleOps;
// Free a seat by deleting a row, and set the counter to read full.
// Free a seat by deleting a row.
await db
.delete(S.eventCheckIns)
.where(
Expand All @@ -255,11 +248,6 @@ describe.skipIf(!URL)("derived counts against a real database", () => {
eq(S.eventCheckIns.userId, userIds[1]!),
),
);
await db
.update(S.events)
.set({ currentCheckIns: 2 })
.where(eq(S.events.id, cappedEventId));

await expect(
appRouter
.createCaller(ctx(userIds[4]))
Expand Down
3 changes: 2 additions & 1 deletion packages/api/src/routers/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ export const eventRouter = createTRPCRouter({
// Invalidate all event-related cache entries after creation
ctx.cache.deletePattern("event*");

return newEvent;
// A new event has nobody checked in, and the QR modal shows the count.
return newEvent && { ...newEvent, currentCheckIns: 0 };
}),

// Corrects a club event in place. Without it the only way to fix a typo was
Expand Down
12 changes: 7 additions & 5 deletions packages/api/src/routers/hackathon/crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,9 @@ export const hackathonCrudRouter = createTRPCRouter({
)
.query(async ({ ctx, input }) => {
type DB = DrizzleDB;
type HackathonList = Awaited<
type HackathonList = (Awaited<
ReturnType<DB["query"]["hackathons"]["findMany"]>
>;
>[number] & { currentParticipants: number })[];

// Staff-only statuses stay listable by admins (the setup and judging pages
// pick a hackathon off this endpoint), so both the rows and the cache entry
Expand Down Expand Up @@ -187,9 +187,11 @@ export const hackathonCrudRouter = createTRPCRouter({
.input(z.object({ id: z.string() }))
.query(async ({ ctx, input }) => {
type DB = DrizzleDB;
type HackathonItem = Awaited<
ReturnType<DB["query"]["hackathons"]["findFirst"]>
>;
type HackathonItem =
| (NonNullable<
Awaited<ReturnType<DB["query"]["hackathons"]["findFirst"]>>
> & { currentParticipants: number })
| undefined;
// list() hides staff-only statuses, but this endpoint is reachable by id or
// name, so a draft stays fetchable by anyone who guesses either. The cache
// entry is shared, so visibility is enforced on the way out — otherwise one
Expand Down
30 changes: 30 additions & 0 deletions packages/db/sql/2026-11-drop-retired.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
-- Drops what the schema stopped declaring in the same change as this file.
--
-- Run it against production BEFORE that change deploys. Deploys run
-- `drizzle-kit push < /dev/null`: a declared-but-missing column is created,
-- but an undeclared-but-present one is a DROP, which push will only do after a
-- prompt the build cannot answer. It then exits 0 having applied nothing, and
-- every later schema change is silently skipped until the drop happens.
--
-- Nothing in the app reads or writes any of these:
-- event.current_check_ins, hackathon_team.current_members,
-- hackathon.current_participants counters, now counted from rows
-- event.members_only check-in is open to everyone signed in
-- hackathon.judging_backend retired panel judging switch
-- bootcamp_material superseded by bootcamp_workshop
-- judge_queue retired pool-judging visit log
--
-- Irreversible: the dropped data is gone. One transaction, so a failure
-- changes nothing. IF EXISTS makes a second run a no-op.

begin;

alter table "event" drop column if exists "current_check_ins";
alter table "event" drop column if exists "members_only";
alter table "hackathon_team" drop column if exists "current_members";
alter table "hackathon" drop column if exists "current_participants";
alter table "hackathon" drop column if exists "judging_backend";
drop table if exists "bootcamp_material";
drop table if exists "judge_queue";

commit;
Loading
Loading