From 7afde2c323458779f180888a10c4aeeb6d507c42 Mon Sep 17 00:00:00 2001 From: Dominic Ferrando Date: Sat, 3 Oct 2026 23:01:27 -0400 Subject: [PATCH] Implement .verify bot command --- apps/api/package.json | 3 +- .../api/src/scripts/seed-test-verification.ts | 2 +- apps/api/src/server.ts | 44 ++- apps/api/src/services/accounts.ts | 2 +- apps/api/src/services/verifications.ts | 14 +- apps/bot/package.json | 1 + apps/bot/src/cmd/registry/verify.ts | 299 ++++++++++++++++++ bun.lock | 3 +- package.json | 1 + 9 files changed, 359 insertions(+), 10 deletions(-) create mode 100644 apps/bot/src/cmd/registry/verify.ts diff --git a/apps/api/package.json b/apps/api/package.json index d7e13e7..c17170f 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -35,7 +35,6 @@ "zipcodes-us": "^1.2.0" }, "devDependencies": { - "kysely-codegen": "^0.20.0", - "pino-pretty": "^13.1.3" + "kysely-codegen": "^0.20.0" } } diff --git a/apps/api/src/scripts/seed-test-verification.ts b/apps/api/src/scripts/seed-test-verification.ts index 23c24a1..68fd3b0 100644 --- a/apps/api/src/scripts/seed-test-verification.ts +++ b/apps/api/src/scripts/seed-test-verification.ts @@ -8,7 +8,7 @@ import { env, log } from "../util"; import type { AccountRole } from "../services/accounts"; import { VerificationsService } from "../services/verifications"; -const DEFAULT_DISCORD_ID = "test-verification-seed"; +const DEFAULT_DISCORD_ID = "1325552430942916731"; const FIXTURES_DIR = path.join(import.meta.dir, "fixtures"); const BUCKET = `verification-media${env.NODE_ENV === "production" ? "" : "-dev"}`; diff --git a/apps/api/src/server.ts b/apps/api/src/server.ts index b356d0a..4719722 100644 --- a/apps/api/src/server.ts +++ b/apps/api/src/server.ts @@ -490,6 +490,21 @@ export const app = new Elysia() }, { params: t.Object({ id: AccountIdSchema }) }) + // TODO: for added security, MUST enforce bot or admin only access + .get("/:id/verifications", async ({ query, params: { id } }) => { + return await s.Verifications.list({ + filter: { status: query.status, accountId: id }, + limit: query.limit, + offset: query.offset, + }); + }, { + params: t.Object({ id: AccountIdSchema }), + query: t.Object({ + status: t.Optional(VerificationStatusSchema), + limit: t.Optional(t.Numeric()), + offset: t.Optional(t.Numeric()), + }) + }) .guard({ authAdmin: true }, (app) => app .get("/:id", async ({ params: { id } }) => { const account = await s.Accounts.get(id); @@ -523,6 +538,19 @@ export const app = new Elysia() }, { params: t.Object({ id: BigIntIdSchema }) }) + .get("/verifications", async ({ query, accountId }) => { + return await s.Verifications.list({ + filter: { status: query.status, accountId }, + limit: query.limit, + offset: query.offset, + }); + }, { + query: t.Object({ + status: t.Optional(VerificationStatusSchema), + limit: t.Optional(t.Numeric()), + offset: t.Optional(t.Numeric()), + }) + }) .post("/verifications", async ({ body: { assessmentId }, accountId }) => { const assessment = await s.Assessments.get(assessmentId, accountId); if (!assessment) return status(404, { error: "Assessment not found" }); @@ -599,7 +627,7 @@ export const app = new Elysia() ) // VERIFICATIONS - .group("/verifications", { authAdmin: true }, (app) => app + .group("/verifications", (app) => app .get("/", async ({ query }) => { return await s.Verifications.list({ filter: { status: query.status }, @@ -607,12 +635,14 @@ export const app = new Elysia() offset: query.offset, }); }, { + authAdmin: true, query: t.Object({ status: t.Optional(VerificationStatusSchema), limit: t.Optional(t.Numeric()), offset: t.Optional(t.Numeric()), }) }) + // TODO: dev-only, unguarded so the bot can call it; restore admin/bot auth .get("/:id", async ({ params: { id } }) => { const verification = await s.Verifications.get(id); if (!verification) return status(404, { error: "Verification not found" }); @@ -629,6 +659,7 @@ export const app = new Elysia() }, { params: t.Object({ id: BigIntIdSchema }) }) + // TODO: dev-only, unguarded so the bot can call it; restore admin/bot auth .post("/:id/request-action", async ({ params: { id }, body: { reviewerNotes, activityVerifications } }) => { const updated = await s.Verifications.requestAction(id, reviewerNotes ?? null, activityVerifications); if (updated) return updated; @@ -643,8 +674,14 @@ export const app = new Elysia() activityVerifications: ActivityVerificationsSchema, }) }) - .post("/:id/complete", async ({ params: { id }, body: { activityVerifications }, accountId }) => { - const updated = await s.Verifications.complete(id, accountId, activityVerifications); + // TODO: dev-only, unguarded so the bot can call it; restore admin/bot auth and drop completedBy from the body + .post("/:id/complete", async ({ params: { id }, body: { activityVerifications, completedBy }, jwt, cookie: { auth } }) => { + const portalSession = auth.value && await jwt.verify(auth.value); + const completerId = completedBy ?? (portalSession ? portalSession.accountId?.toString() : undefined); + const completer = completerId && await s.Accounts.get(completerId); + if (!completer || completer.role !== "admin") return status(403, { error: "Only a classmaster can complete a verification" }); + + const updated = await s.Verifications.complete(id, completer.id, activityVerifications); if (updated) return updated; const verification = await s.Verifications.get(id); @@ -654,6 +691,7 @@ export const app = new Elysia() params: t.Object({ id: BigIntIdSchema }), body: t.Object({ activityVerifications: ActivityVerificationsSchema, + completedBy: t.Optional(AccountIdSchema), }) }) ) diff --git a/apps/api/src/services/accounts.ts b/apps/api/src/services/accounts.ts index dab83fd..ea17a65 100644 --- a/apps/api/src/services/accounts.ts +++ b/apps/api/src/services/accounts.ts @@ -9,7 +9,7 @@ export type AccountRole = "user" | "admin"; export class AccountsService { constructor(private Calculator: CalculatorService) { } - private static idComparison(id: string): ["accounts.id" | "accounts.discord_id", "=", string] { + static idComparison(id: string): ["accounts.id" | "accounts.discord_id", "=", string] { return id.startsWith("@") ? ["accounts.discord_id", "=", id.slice(1)] : ["accounts.id", "=", id]; diff --git a/apps/api/src/services/verifications.ts b/apps/api/src/services/verifications.ts index 14829ab..505d4e4 100644 --- a/apps/api/src/services/verifications.ts +++ b/apps/api/src/services/verifications.ts @@ -2,6 +2,7 @@ import { Activity, type ActivityVerifications } from "@blade-and-brawn/domain"; import type { Static } from "@sinclair/typebox"; import { t } from "elysia"; import { db } from "../database/db"; +import { AccountsService } from "./accounts"; export const VerificationStatusSchema = t.Union([ t.Literal("draft"), @@ -40,12 +41,12 @@ export class VerificationsService { async get(id: string, accountId?: string) { return await VerificationsService.baseQuery() .where("verifications.id", "=", id) - .$if(accountId !== undefined, (qb) => qb.where("assessments.account_id", "=", accountId!)) + .$if(accountId !== undefined, (qb) => qb.where("assessments.account_id", "=", VerificationsService.accountIdQuery(accountId!))) .executeTakeFirst(); } async list(opt: { - filter?: { status?: VerificationStatus }, + filter?: { status?: VerificationStatus, accountId?: string }, limit?: number, offset?: number, } = {}) { @@ -53,6 +54,9 @@ export class VerificationsService { .$if(opt.filter?.status !== undefined, (qb) => qb .where("verifications.status", "=", opt.filter!.status!) ) + .$if(opt.filter?.accountId !== undefined, (qb) => qb + .where("assessments.account_id", "=", VerificationsService.accountIdQuery(opt.filter!.accountId!)) + ) .orderBy("verifications.submitted_at", (ob) => ob.desc().nullsLast()) .orderBy("verifications.created_at", "desc") .$if(opt.limit !== undefined, (qb) => qb.limit(opt.limit!)) @@ -106,6 +110,12 @@ export class VerificationsService { .executeTakeFirst(); } + private static accountIdQuery(accountId: string) { + return db.selectFrom("accounts") + .select("id") + .where(...AccountsService.idComparison(accountId)); + } + private static baseQuery() { return db.selectFrom("verifications") .innerJoin("assessments", "assessments.id", "verifications.assessment_id") diff --git a/apps/bot/package.json b/apps/bot/package.json index affa188..94862e5 100644 --- a/apps/bot/package.json +++ b/apps/bot/package.json @@ -8,6 +8,7 @@ }, "peerDependencies": {}, "dependencies": { + "@blade-and-brawn/domain": "workspace:*", "@elysia/eden": "^1.4.10", "discord.js": "^14.27.0" }, diff --git a/apps/bot/src/cmd/registry/verify.ts b/apps/bot/src/cmd/registry/verify.ts new file mode 100644 index 0000000..52895cb --- /dev/null +++ b/apps/bot/src/cmd/registry/verify.ts @@ -0,0 +1,299 @@ +import { + ActionRowBuilder, + ButtonBuilder, + ButtonStyle, + ComponentType, + EmbedBuilder, + MessageFlags, + ModalBuilder, + TextInputStyle, + type Message, +} from "discord.js"; +import { Activity, cmToIn, kgToLb, type ActivityVerifications } from "@blade-and-brawn/domain"; +import type { Command } from "../../models"; +import { api } from "../../util"; + +const REVIEW_TIMEOUT_MS = 15 * 60_000; +const NOTES_TIMEOUT_MS = 10 * 60_000; +const MEDIA_TEXT_LIMIT = 3800; + +const ACTIVITIES = Object.values(Activity); + +const ACTIVITY_LABEL: Record = { + [Activity.BackSquat]: "Back Squat", + [Activity.Deadlift]: "Deadlift", + [Activity.BenchPress]: "Bench Press", + [Activity.Run]: "Run", + [Activity.BroadJump]: "Broad Jump", + [Activity.ConeDrill]: "Cone Drill", +}; + +const VERF_COLUMN = { + [Activity.BackSquat]: "verf_back_squat", + [Activity.Deadlift]: "verf_deadlift", + [Activity.BenchPress]: "verf_bench_press", + [Activity.Run]: "verf_run", + [Activity.BroadJump]: "verf_broad_jump", + [Activity.ConeDrill]: "verf_cone_drill", +} as const satisfies Record; + +const PERF_COLUMN = { + [Activity.BackSquat]: "perf_back_squat", + [Activity.Deadlift]: "perf_deadlift", + [Activity.BenchPress]: "perf_bench_press", + [Activity.Run]: "perf_run", + [Activity.BroadJump]: "perf_broad_jump", + [Activity.ConeDrill]: "perf_cone_drill", +} as const satisfies Record; + +async function loadVerification(id: string) { + return await api.verifications({ id }).get(); +} + +type Verification = NonNullable>["data"]>; +type Result = boolean | null; + +function formatPerformance(activity: Activity, value: number | null): string { + if (value === null) return "—"; + switch (activity) { + case Activity.BackSquat: + case Activity.Deadlift: + case Activity.BenchPress: + return `${Math.round(kgToLb(value))} lb`; + case Activity.Run: { + const totalSeconds = Math.floor(value / 1000); + return `${Math.floor(totalSeconds / 60)}m ${totalSeconds % 60}s`; + } + case Activity.ConeDrill: + return `${(value / 1000).toFixed(2)} seconds`; + case Activity.BroadJump: { + const inches = cmToIn(value); + const ft = Math.floor(inches / 12); + return `${ft}' ${Math.round((inches - ft * 12) * 2) / 2}"`; + } + } +} + +function formatSize(bytes: number | undefined): string { + if (bytes === undefined) return "—"; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +function resultIcon(result: Result): string { + if (result === true) return "✅"; + if (result === false) return "❌"; + return "⬜"; +} + +function nextResult(result: Result): Result { + if (result === null) return true; + if (result === true) return false; + return null; +} + +function errorText(error: { status: number, value: unknown }): string { + return (error.value as { error?: string } | undefined)?.error ?? "Something went wrong talking to the API."; +} + +function mediaText(media: Verification["media"]): string { + if (media.length === 0) return "No media uploaded"; + + const lines: string[] = []; + let length = 0; + for (const [i, file] of media.entries()) { + const line = `[File ${i + 1}](${file.url}) · ${formatSize(file.size)}`; + if (length + line.length > MEDIA_TEXT_LIMIT) { + lines.push(`…and ${media.length - i} more (see the portal)`); + break; + } + lines.push(line); + length += line.length + 1; + } + return lines.join("\n"); +} + +export default { + name: "verify", + description: "Review a player's submitted verification", + usage: ".verify ", + execute: async (message: Message) => { + if (message.mentions.users.size > 1) { + await message.reply("Only one player may be provided."); + return; + } + + const user = message.mentions.users.first(); + if (!user) { + await message.reply("No valid player was provided."); + return; + } + + const classmasterId = message.author.id; + + const listRes = await api.accounts({ id: `@${user.id}` }).verifications.get({ + query: { limit: 1, status: "submitted" }, + }); + if (listRes.error) { + await message.reply(errorText(listRes.error)); + return; + } + + const latest = listRes.data[0]; + if (!latest) { + await message.reply("This player has no submitted verification."); + return; + } + + const res = await loadVerification(latest.id); + if (res.error) { + await message.reply(errorText(res.error)); + return; + } + + const v = res.data; + const results = Object.fromEntries(ACTIVITIES.map((a) => [a, v[VERF_COLUMN[a]]])) as Record; + let notes = v.reviewer_notes ?? ""; + + const reviewedCount = () => ACTIVITIES.filter((a) => results[a] !== null).length; + + const embeds = () => [ + new EmbedBuilder() + .setColor(0xEEE8AA) + .setTitle(v.name) + .setDescription(`${user} · ${v.gender} · age ${v.age} · ${Math.round(kgToLb(v.weight))} lb`) + .addFields( + ACTIVITIES.map((a) => ({ + name: ACTIVITY_LABEL[a], + value: formatPerformance(a, v[PERF_COLUMN[a]]), + inline: true, + })) + ) + .addFields(notes ? [{ name: "Reviewer notes", value: notes.slice(0, 1024) }] : []) + .setFooter({ text: `${reviewedCount()} / ${ACTIVITIES.length} reviewed · Click an activity to cycle Pass → Fail → Unreviewed` }), + new EmbedBuilder() + .setTitle(`Media (${v.media.length})`) + .setDescription(mediaText(v.media)), + ]; + + const components = () => [ + new ActionRowBuilder().addComponents(ACTIVITIES.slice(0, 3).map(activityButton)), + new ActionRowBuilder().addComponents(ACTIVITIES.slice(3).map(activityButton)), + new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId("request-action") + .setLabel("Request action") + .setStyle(ButtonStyle.Primary), + new ButtonBuilder() + .setCustomId("complete") + .setLabel("Complete") + .setStyle(ButtonStyle.Success) + .setDisabled(reviewedCount() < ACTIVITIES.length), + new ButtonBuilder() + .setCustomId("cancel") + .setLabel("Cancel") + .setStyle(ButtonStyle.Secondary), + ), + ]; + + const activityButton = (activity: Activity) => new ButtonBuilder() + .setCustomId(`result:${activity}`) + .setLabel(`${resultIcon(results[activity])} ${ACTIVITY_LABEL[activity]}`) + .setStyle(results[activity] === true ? ButtonStyle.Success : results[activity] === false ? ButtonStyle.Danger : ButtonStyle.Secondary); + + const activityVerifications = (): ActivityVerifications => + Object.fromEntries(ACTIVITIES.filter((a) => results[a] !== null).map((a) => [a, results[a]])); + + const reply = await message.reply({ embeds: embeds(), components: components() }); + + const finish = async (content: string) => { + collector.stop("done"); + await reply.edit({ content, embeds: embeds(), components: [] }); + }; + + const collector = reply.createMessageComponentCollector({ componentType: ComponentType.Button, time: REVIEW_TIMEOUT_MS }); + + collector.on("collect", async (i) => { + if (i.user.id !== classmasterId) { + await i.reply({ content: "Only the classmaster who ran this command can review it.", flags: MessageFlags.Ephemeral }); + return; + } + + if (i.customId.startsWith("result:")) { + const activity = i.customId.slice("result:".length) as Activity; + results[activity] = nextResult(results[activity]); + await i.update({ embeds: embeds(), components: components() }); + return; + } + + if (i.customId === "cancel") { + collector.stop("done"); + await i.deferUpdate(); + await reply.delete(); + return; + } + + if (i.customId === "complete") { + await i.deferUpdate(); + // TODO: drop completedBy once the bot authenticates as the classmaster + const res = await api.verifications({ id: v.id }).complete.post({ + activityVerifications: activityVerifications(), + completedBy: `@${classmasterId}`, + }); + if (res.error) { + await i.followUp({ content: errorText(res.error), flags: MessageFlags.Ephemeral }); + return; + } + await finish(`✅ Verification completed by ${i.user}.`); + return; + } + + if (i.customId === "request-action") { + const modalId = `request-action:${i.id}`; + await i.showModal( + new ModalBuilder() + .setCustomId(modalId) + .setTitle("Request action") + .addLabelComponents((label) => label + .setLabel("What needs to be fixed?") + .setTextInputComponent((input) => { + input + .setCustomId("notes") + .setStyle(TextInputStyle.Paragraph) + .setRequired(false) + .setMaxLength(1000); + return notes ? input.setValue(notes) : input; + }) + ) + ); + + const submitted = await i.awaitModalSubmit({ + time: NOTES_TIMEOUT_MS, + filter: (m) => m.customId === modalId, + }).catch(() => null); + if (!submitted?.isFromMessage()) return; + + await submitted.deferUpdate(); + notes = submitted.fields.getTextInputValue("notes").trim(); + + const res = await api.verifications({ id: v.id })["request-action"].post({ + reviewerNotes: notes || undefined, + activityVerifications: activityVerifications(), + }); + if (res.error) { + await submitted.followUp({ content: errorText(res.error), flags: MessageFlags.Ephemeral }); + return; + } + await finish(`↩️ Action requested by ${i.user}.`); + } + }); + + collector.on("end", async (_, reason) => { + if (reason === "done") return; + await reply.edit({ + content: "⌛ Review timed out. Run `.verify` again to continue.", + components: [], + }).catch(() => { }); + }); + } +} satisfies Command; diff --git a/bun.lock b/bun.lock index 6561f4a..edd66b3 100644 --- a/bun.lock +++ b/bun.lock @@ -7,6 +7,7 @@ "dependencies": { "@sinclair/typebox": "^0.34.52", "pino": "^10.4.0", + "pino-pretty": "^13.1.3", }, "devDependencies": { "@types/bun": "^1.4.2", @@ -32,12 +33,12 @@ }, "devDependencies": { "kysely-codegen": "^0.20.0", - "pino-pretty": "^13.1.3", }, }, "apps/bot": { "name": "@blade-and-brawn/bot", "dependencies": { + "@blade-and-brawn/domain": "workspace:*", "@elysia/eden": "^1.4.10", "discord.js": "^14.27.0", }, diff --git a/package.json b/package.json index daa5610..b7315bc 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ }, "dependencies": { "pino": "^10.4.0", + "pino-pretty": "^13.1.3", "@sinclair/typebox": "^0.34.52" } }