3 Commits
Author SHA1 Message Date
Dominic Ferrando 7afde2c323 Implement .verify bot command 2026-10-03 23:01:27 -04:00
Dominic Ferrando e497982222 Seed script for test verifications 2026-10-03 18:26:53 -04:00
Dominic Ferrando 09e7a9c0fd Refactor verifications portal GUI 2026-10-02 16:33:52 -04:00
14 changed files with 786 additions and 525 deletions
+3
View File
@@ -38,3 +38,6 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Agents
.claude/settings.local.json
# Local test media for seed scripts
apps/api/src/scripts/fixtures
+1 -2
View File
@@ -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"
}
}
+41 -19
View File
@@ -1,49 +1,57 @@
import { Gender, inToCm, lbToKg, minToMs, secToMs } from "@blade-and-brawn/domain";
import { S3Client } from "bun";
import { readdir } from "node:fs/promises";
import path from "node:path";
import { parseArgs } from "node:util";
import { db } from "../database/db";
import { env, log } from "../util";
import type { AccountRole } from "../services/accounts";
import { VerificationsService } from "../services/verifications";
const TEST_DISCORD_ID = "test-verification-seed";
const TEST_ASSESSMENT_NAME = "Test Verification Player";
const DEFAULT_DISCORD_ID = "1325552430942916731";
const FIXTURES_DIR = path.join(import.meta.dir, "fixtures");
const BUCKET = `verification-media${env.NODE_ENV === "production" ? "" : "-dev"}`;
const { values: args } = parseArgs({
args: Bun.argv.slice(2),
options: { "discord-id": { type: "string", default: DEFAULT_DISCORD_ID } },
});
const discordId = args["discord-id"];
const r2 = new S3Client({
accessKeyId: env.R2_ACCESS_KEY_ID,
secretAccessKey: env.R2_SECRET_ACCESS_KEY,
bucket: BUCKET,
endpoint: env.R2_URL,
});
async function seedTestAccount(): Promise<string> {
const existing = await db.selectFrom("accounts")
.select("id")
.where("discord_id", "=", TEST_DISCORD_ID)
.where("discord_id", "=", discordId)
.executeTakeFirst();
if (existing) {
log.info({ id: existing.id }, "test account already seeded, reusing");
log.info({ id: existing.id, discordId }, "account already exists, reusing");
return existing.id;
}
const account = await db.insertInto("accounts")
.values({
discord_id: TEST_DISCORD_ID,
discord_id: discordId,
name: "Test Player",
role: "user" satisfies AccountRole,
})
.returning("id")
.executeTakeFirstOrThrow();
log.info({ id: account.id }, "seeded test account");
log.info({ id: account.id, discordId }, "seeded test account");
return account.id;
}
async function seedTestAssessment(accountId: string): Promise<string> {
const existing = await db.selectFrom("assessments")
.select("id")
.where("account_id", "=", accountId)
.where("name", "=", TEST_ASSESSMENT_NAME)
.executeTakeFirst();
if (existing) {
log.info({ id: existing.id }, "test assessment already seeded, reusing");
return existing.id;
}
const result = await db.insertInto("assessments")
.values({
account_id: accountId,
name: TEST_ASSESSMENT_NAME,
name: `Test Verification ${new Date().toISOString()}`,
gender: Gender.Male,
age: 22,
weight: lbToKg(180),
@@ -60,8 +68,20 @@ async function seedTestAssessment(accountId: string): Promise<string> {
return result.id;
}
async function uploadFixtures(assessmentId: string) {
const names = await readdir(FIXTURES_DIR).catch(() => []);
if (names.length === 0) log.warn({ dir: FIXTURES_DIR }, "no fixture media found, verification will have no media");
for (const name of names) {
const file = Bun.file(path.join(FIXTURES_DIR, name));
const key = `${assessmentId}/${crypto.randomUUID()}`;
await r2.write(key, file, { type: file.type });
log.info({ key, name, size: file.size }, "uploaded fixture media");
}
}
(async () => {
const answer = prompt(`Seed a test verification request in the database (${env.DATABASE_URL})? (y/N)`);
const answer = prompt(`Seed a test verification for discord id "${discordId}" in the database (${env.DATABASE_URL}) and R2 bucket "${BUCKET}"? (y/N)`);
if (answer?.trim().toLowerCase() !== "y") {
log.info("Aborted");
await db.destroy();
@@ -74,7 +94,9 @@ async function seedTestAssessment(accountId: string): Promise<string> {
const verifications = new VerificationsService();
const verification = await verifications.create(assessmentId);
if (!verification) throw new Error("Test assessment already has a verification; clear the verifications table first");
if (!verification) throw new Error("Failed to create test verification");
await uploadFixtures(assessmentId);
const submitted = await verifications.submit(verification.id);
if (!submitted) throw new Error("Failed to submit test verification");
+52 -5
View File
@@ -53,7 +53,7 @@ const r2 = {
verificationMedia: new S3Client({
accessKeyId: env.R2_ACCESS_KEY_ID,
secretAccessKey: env.R2_SECRET_ACCESS_KEY,
bucket: "verification-media",
bucket: `verification-media${env.NODE_ENV === "production" ? "" : "-dev"}`,
endpoint: env.R2_URL,
})
};
@@ -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,19 +635,31 @@ 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" });
return verification;
const { contents = [] } = await r2.verificationMedia.list({ prefix: `${verification.assessment_id}/` });
const media = contents.map(({ key, size, lastModified }) => ({
key,
size,
lastModified,
url: r2.verificationMedia.presign(key, { expiresIn: 60 * 60 }),
}));
return { ...verification, media };
}, {
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;
@@ -634,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);
@@ -645,6 +691,7 @@ export const app = new Elysia()
params: t.Object({ id: BigIntIdSchema }),
body: t.Object({
activityVerifications: ActivityVerificationsSchema,
completedBy: t.Optional(AccountIdSchema),
})
})
)
+1 -1
View File
@@ -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];
+12 -2
View File
@@ -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")
+1
View File
@@ -8,6 +8,7 @@
},
"peerDependencies": {},
"dependencies": {
"@blade-and-brawn/domain": "workspace:*",
"@elysia/eden": "^1.4.10",
"discord.js": "^14.27.0"
},
+299
View File
@@ -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, string> = {
[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<Activity, string>;
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<Activity, string>;
async function loadVerification(id: string) {
return await api.verifications({ id }).get();
}
type Verification = NonNullable<Awaited<ReturnType<typeof loadVerification>>["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 <user>",
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<Activity, Result>;
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<ButtonBuilder>().addComponents(ACTIVITIES.slice(0, 3).map(activityButton)),
new ActionRowBuilder<ButtonBuilder>().addComponents(ACTIVITIES.slice(3).map(activityButton)),
new ActionRowBuilder<ButtonBuilder>().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;
+1 -1
View File
@@ -28,7 +28,7 @@
{
name: "Verification",
path: "/verification",
links: [{ name: "Requests", path: "/requests" }],
links: [{ name: "Verifications", path: "/verifications" }],
},
];
@@ -1,471 +0,0 @@
<script lang="ts">
import { goto } from "$app/navigation";
import { api } from "$lib/api";
import { Activity, cmToIn, kgToLb } from "@blade-and-brawn/domain";
import type { ActivityVerifications } from "@blade-and-brawn/domain";
import type { VerificationStatus } from "@blade-and-brawn/api";
import { onMount } from "svelte";
import type { PageProps } from "./$types";
async function loadVerification(id: string) {
return await api.verifications({ id }).get();
}
type VerificationDetail = NonNullable<
Awaited<ReturnType<typeof loadVerification>>["data"]
>;
type VerfChoice = "unset" | "pass" | "fail";
const ACTIVITIES = Object.values(Activity);
const STATUS_BADGE: Record<VerificationStatus, string> = {
draft: "badge-ghost",
submitted: "badge-info",
in_review: "badge-warning",
action_requested: "badge-error",
completed: "badge-success",
};
const MEDIA_KEY_COLUMN = {
[Activity.BackSquat]: "media_key_back_squat",
[Activity.Deadlift]: "media_key_deadlift",
[Activity.BenchPress]: "media_key_bench_press",
[Activity.Run]: "media_key_run",
[Activity.BroadJump]: "media_key_broad_jump",
[Activity.ConeDrill]: "media_key_cone_drill",
} as const satisfies Record<Activity, keyof VerificationDetail>;
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<Activity, keyof VerificationDetail>;
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<Activity, keyof VerificationDetail>;
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);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}m ${seconds}s`;
}
case Activity.ConeDrill:
return `${(value / 1000).toFixed(2)} seconds`;
case Activity.BroadJump: {
const inches = cmToIn(value);
const ft = Math.floor(inches / 12);
const rem = Math.round((inches - ft * 12) * 2) / 2;
return `${ft}' ${rem}"`;
}
default:
return "—";
}
}
function verfChoiceFrom(value: boolean | null): VerfChoice {
if (value === true) return "pass";
if (value === false) return "fail";
return "unset";
}
function toActivityVerifications(
choices: Record<Activity, VerfChoice>,
): ActivityVerifications {
const result: ActivityVerifications = {};
for (const activity of ACTIVITIES) {
if (choices[activity] === "pass") result[activity] = true;
else if (choices[activity] === "fail") result[activity] = false;
}
return result;
}
function errorMessage(err: unknown): string {
const value = (err as { value?: { error?: string } })?.value;
return (
value?.error ??
(err instanceof Error ? err.message : "Unknown error")
);
}
let { params }: PageProps = $props();
const id = $derived(params.id);
let verification = $state<VerificationDetail | null>(null);
let loading = $state(true);
let loadError = $state<string | null>(null);
let stepIndex = $state(0);
let notes = $state("");
let verf = $state<Record<Activity, VerfChoice>>(
Object.fromEntries(ACTIVITIES.map((a) => [a, "unset"])) as Record<
Activity,
VerfChoice
>,
);
let submitting = $state<"action" | "complete" | undefined>();
let submitError = $state<string | null>(null);
const SUMMARY_STEP = ACTIVITIES.length;
const isSummaryStep = $derived(stepIndex === SUMMARY_STEP);
const reviewedCount = $derived(
ACTIVITIES.filter((a) => verf[a] !== "unset").length,
);
const allReviewed = $derived(reviewedCount === ACTIVITIES.length);
const isReadOnly = $derived(
verification?.status !== "submitted" &&
verification?.status !== "in_review",
);
async function load() {
loading = true;
loadError = null;
try {
const res = await loadVerification(id);
if (res.error) throw res.error;
if (!res.data) throw new Error("Verification not found");
verification = res.data;
notes = verification.reviewer_notes ?? "";
verf = Object.fromEntries(
ACTIVITIES.map((a) => [
a,
verfChoiceFrom(verification![VERF_COLUMN[a]]),
]),
) as Record<Activity, VerfChoice>;
} catch (err) {
loadError = errorMessage(err);
} finally {
loading = false;
}
}
function goPrev() {
stepIndex = Math.max(0, stepIndex - 1);
}
function goNext() {
stepIndex = Math.min(SUMMARY_STEP, stepIndex + 1);
}
function setVerf(activity: Activity, choice: VerfChoice) {
if (isReadOnly) return;
verf[activity] = choice;
}
async function requestAction() {
submitting = "action";
submitError = null;
try {
const res = await api
.verifications({ id })
["request-action"].post({
reviewerNotes: notes || undefined,
activityVerifications: toActivityVerifications(verf),
});
if (res.error) throw res.error;
await goto("/verification/requests");
} catch (err) {
submitError = errorMessage(err);
} finally {
submitting = undefined;
}
}
async function complete() {
submitting = "complete";
submitError = null;
try {
const res = await api.verifications({ id }).complete.post({
activityVerifications: toActivityVerifications(verf),
});
if (res.error) throw res.error;
await goto("/verification/requests");
} catch (err) {
submitError = errorMessage(err);
} finally {
submitting = undefined;
}
}
onMount(load);
</script>
<div class="w-full mt-10 mb-5">
<a href="/verification/requests" class="link link-hover text-sm opacity-70"
>&larr; Back to requests</a
>
</div>
{#if loading}
<div class="w-full flex justify-center pt-10">
<span class="loading loading-spinner loading-lg"></span>
</div>
{:else if loadError}
<div role="alert" class="alert alert-error w-full mb-4">
<span>{loadError}</span>
</div>
{:else if verification}
{@const v = verification}
<div class="w-full flex items-center gap-3 flex-wrap mb-6">
<h1 class="text-xl font-semibold">{v.name}</h1>
<div class="badge {STATUS_BADGE[v.status as VerificationStatus]}">{v.status}</div>
<span class="text-sm opacity-70"
>{v.gender} · age {v.age} · {Math.round(kgToLb(v.weight))} lb</span
>
<div class="flex-1"></div>
<span class="text-sm opacity-70"
>{reviewedCount} / {ACTIVITIES.length} reviewed</span
>
</div>
<div role="tablist" class="tabs tabs-border w-full">
{#each ACTIVITIES as activity, i (activity)}
<button
role="tab"
class="tab gap-2"
class:tab-active={stepIndex === i}
onclick={() => (stepIndex = i)}
>
{activity}
{#if verf[activity] === "pass"}
<span class="text-success">✓</span>
{:else if verf[activity] === "fail"}
<span class="text-error">✕</span>
{/if}
</button>
{/each}
<button
role="tab"
class="tab"
class:tab-active={isSummaryStep}
onclick={() => (stepIndex = SUMMARY_STEP)}
>
Summary
</button>
</div>
{#if !isSummaryStep}
{@const activity = ACTIVITIES[stepIndex]}
<div class="w-full flex flex-col gap-4 bg-base-200/60 rounded-lg p-6 mt-4">
<div class="flex items-center justify-between flex-wrap gap-2">
<h2 class="text-lg font-semibold">{activity}</h2>
<div class="text-right">
<div class="text-xs opacity-60">Claimed</div>
<div class="text-2xl font-bold">
{formatPerformance(activity, v[PERF_COLUMN[activity]])}
</div>
</div>
</div>
{#if v[MEDIA_KEY_COLUMN[activity]]}
{@const videoUrl = v[MEDIA_KEY_COLUMN[activity]]}
<!-- svelte-ignore a11y_media_has_caption -->
<video
class="w-full max-h-[480px] rounded-lg bg-black"
src={videoUrl}
controls
preload="metadata"
></video>
<a
class="link link-primary text-xs self-start"
href={videoUrl}
target="_blank"
rel="noopener noreferrer"
>
Open video in new tab
</a>
{:else}
<div
class="w-full aspect-video rounded-lg bg-base-300 flex items-center justify-center opacity-60"
>
No video uploaded
</div>
{/if}
<div class="flex gap-2 justify-center mt-2">
<button
class="btn btn-sm {verf[activity] === 'pass'
? 'btn-success'
: 'btn-outline btn-success'}"
disabled={isReadOnly}
onclick={() => setVerf(activity, "pass")}
>
Pass
</button>
<button
class="btn btn-sm {verf[activity] === 'fail'
? 'btn-error'
: 'btn-outline btn-error'}"
disabled={isReadOnly}
onclick={() => setVerf(activity, "fail")}
>
Fail
</button>
<button
class="btn btn-sm btn-ghost"
disabled={isReadOnly || verf[activity] === "unset"}
onclick={() => setVerf(activity, "unset")}
>
Clear
</button>
</div>
<div class="flex justify-between mt-2">
<button
class="btn btn-neutral btn-sm"
onclick={goPrev}
disabled={stepIndex === 0}
>
&larr; Previous
</button>
<button class="btn btn-neutral btn-sm" onclick={goNext}>
Next &rarr;
</button>
</div>
</div>
{:else}
<div class="w-full flex flex-col gap-4 bg-base-200/60 rounded-lg p-6 mt-4">
<h2 class="text-lg font-semibold">Review summary</h2>
<div class="overflow-x-auto">
<table class="table table-sm">
<thead>
<tr>
<th>Activity</th>
<th>Claimed</th>
<th>Video</th>
<th>Result</th>
</tr>
</thead>
<tbody>
{#each ACTIVITIES as activity, i (activity)}
<tr>
<td>
<button
class="link link-hover"
onclick={() => (stepIndex = i)}
>
{activity}
</button>
</td>
<td>
{formatPerformance(
activity,
v[PERF_COLUMN[activity]],
)}
</td>
<td>
{#if v[MEDIA_KEY_COLUMN[activity]]}
<a
class="link link-primary"
href={v[MEDIA_KEY_COLUMN[activity]]}
target="_blank"
rel="noopener noreferrer"
>
View
</a>
{:else}
<span class="opacity-50">None</span>
{/if}
</td>
<td>
{#if verf[activity] === "pass"}
<span class="badge badge-success"
>Pass</span
>
{:else if verf[activity] === "fail"}
<span class="badge badge-error"
>Fail</span
>
{:else}
<span class="badge badge-ghost"
>Unreviewed</span
>
{/if}
</td>
</tr>
{/each}
</tbody>
</table>
</div>
<label class="form-control">
<span class="label mb-1 text-xs">Reviewer notes</span>
<textarea
class="textarea textarea-bordered w-full"
rows="3"
placeholder="What needs to be fixed?"
disabled={isReadOnly}
bind:value={notes}
></textarea>
</label>
{#if submitError}
<div role="alert" class="alert alert-error">
<span>{submitError}</span>
</div>
{/if}
<div class="flex items-center gap-2 justify-between">
<button
class="btn btn-neutral btn-sm"
onclick={goPrev}
disabled={stepIndex === 0}
>
&larr; Previous
</button>
{#if isReadOnly}
<span class="text-sm opacity-70">
{v.status === "completed"
? "This verification is completed and read-only."
: v.status === "draft"
? "This verification is still a draft (the player hasn't finished uploading) and is read-only."
: "This verification is waiting on the player to resubmit and is read-only."}
</span>
{:else}
<div class="flex items-center gap-2">
{#if !allReviewed}
<span class="text-xs text-warning"
>Mark every activity Pass or Fail to complete</span
>
{/if}
<button
class="btn btn-warning"
disabled={!!submitting}
onclick={requestAction}
>
{submitting === "action"
? "Submitting..."
: "Request action"}
</button>
<button
class="btn btn-success"
disabled={!!submitting || !allReviewed}
onclick={complete}
>
{submitting === "complete"
? "Submitting..."
: "Complete"}
</button>
</div>
{/if}
</div>
</div>
{/if}
{/if}
@@ -1,6 +1,5 @@
<script lang="ts">
import { api } from "$lib/api";
import { Activity } from "@blade-and-brawn/domain";
import type { VerificationStatus } from "@blade-and-brawn/api";
import { onMount } from "svelte";
@@ -18,19 +17,6 @@
completed: "badge-success",
};
const MEDIA_KEY_COLUMN = {
[Activity.BackSquat]: "media_key_back_squat",
[Activity.Deadlift]: "media_key_deadlift",
[Activity.BenchPress]: "media_key_bench_press",
[Activity.Run]: "media_key_run",
[Activity.BroadJump]: "media_key_broad_jump",
[Activity.ConeDrill]: "media_key_cone_drill",
} as const satisfies Record<Activity, keyof VerificationRow>;
function videoCount(row: VerificationRow): number {
return Object.values(Activity).filter((a) => row[MEDIA_KEY_COLUMN[a]]).length;
}
function formatDate(value: string | Date | null): string {
if (!value) return "—";
return new Date(value).toLocaleString();
@@ -44,7 +30,7 @@
);
}
let requests = $state<VerificationRow[]>([]);
let verifications = $state<VerificationRow[]>([]);
let loading = $state(true);
let loadError = $state<string | null>(null);
let offset = $state(0);
@@ -58,7 +44,7 @@
query: { status: status || undefined, limit: LIMIT, offset },
});
if (res.error) throw res.error;
requests = res.data as VerificationRow[];
verifications = res.data as VerificationRow[];
} catch (err) {
loadError = errorMessage(err);
} finally {
@@ -118,7 +104,7 @@
<button
class="btn btn-neutral btn-sm"
onclick={nextPage}
disabled={requests.length < LIMIT || loading}
disabled={verifications.length < LIMIT || loading}
>
Next
</button>
@@ -136,13 +122,12 @@
<tr>
<th>Player</th>
<th>Status</th>
<th>Videos</th>
<th>Submitted</th>
<th></th>
</tr>
</thead>
<tbody>
{#each requests as row (row.id)}
{#each verifications as row (row.id)}
<tr class="hover:bg-base-300">
<td>{row.name}</td>
<td>
@@ -150,12 +135,11 @@
{row.status}
</div>
</td>
<td>{videoCount(row)} / {Object.values(Activity).length}</td>
<td class="whitespace-nowrap">{formatDate(row.submitted_at)}</td>
<td>
<a
class="btn btn-primary btn-xs"
href="/verification/requests/{row.id}"
href="/verification/verifications/{row.id}"
>
Review
</a>
@@ -163,8 +147,8 @@
</tr>
{:else}
<tr>
<td colspan="5" class="text-center opacity-60">
{loading ? "Loading..." : "No verification requests"}
<td colspan="4" class="text-center opacity-60">
{loading ? "Loading..." : "No verifications"}
</td>
</tr>
{/each}
@@ -0,0 +1,365 @@
<script lang="ts">
import { goto } from "$app/navigation";
import { api } from "$lib/api";
import { Activity, cmToIn, kgToLb } from "@blade-and-brawn/domain";
import type { ActivityVerifications } from "@blade-and-brawn/domain";
import type { VerificationStatus } from "@blade-and-brawn/api";
import { onMount } from "svelte";
import type { PageProps } from "./$types";
async function loadVerification(id: string) {
return await api.verifications({ id }).get();
}
type VerificationDetail = NonNullable<
Awaited<ReturnType<typeof loadVerification>>["data"]
>;
type VerfChoice = "unset" | "pass" | "fail";
const ACTIVITIES = Object.values(Activity);
const STATUS_BADGE: Record<VerificationStatus, string> = {
draft: "badge-ghost",
submitted: "badge-info",
in_review: "badge-warning",
action_requested: "badge-error",
completed: "badge-success",
};
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<Activity, keyof VerificationDetail>;
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<Activity, keyof VerificationDetail>;
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);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}m ${seconds}s`;
}
case Activity.ConeDrill:
return `${(value / 1000).toFixed(2)} seconds`;
case Activity.BroadJump: {
const inches = cmToIn(value);
const ft = Math.floor(inches / 12);
const rem = Math.round((inches - ft * 12) * 2) / 2;
return `${ft}' ${rem}"`;
}
default:
return "—";
}
}
function verfChoiceFrom(value: boolean | null): VerfChoice {
if (value === true) return "pass";
if (value === false) return "fail";
return "unset";
}
function toActivityVerifications(
choices: Record<Activity, VerfChoice>,
): ActivityVerifications {
const result: ActivityVerifications = {};
for (const activity of ACTIVITIES) {
if (choices[activity] === "pass") result[activity] = true;
else if (choices[activity] === "fail") result[activity] = false;
}
return result;
}
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 formatDate(value: string | undefined): string {
return value ? new Date(value).toLocaleString() : "—";
}
function errorMessage(err: unknown): string {
const value = (err as { value?: { error?: string } })?.value;
return (
value?.error ??
(err instanceof Error ? err.message : "Unknown error")
);
}
let { params }: PageProps = $props();
const id = $derived(params.id);
let verification = $state<VerificationDetail | null>(null);
let loading = $state(true);
let loadError = $state<string | null>(null);
let notes = $state("");
let verf = $state<Record<Activity, VerfChoice>>(
Object.fromEntries(ACTIVITIES.map((a) => [a, "unset"])) as Record<
Activity,
VerfChoice
>,
);
let submitting = $state<"action" | "complete" | undefined>();
let submitError = $state<string | null>(null);
const reviewedCount = $derived(
ACTIVITIES.filter((a) => verf[a] !== "unset").length,
);
const allReviewed = $derived(reviewedCount === ACTIVITIES.length);
const isReadOnly = $derived(
verification?.status !== "submitted" &&
verification?.status !== "in_review",
);
async function load() {
loading = true;
loadError = null;
try {
const res = await loadVerification(id);
if (res.error) throw res.error;
if (!res.data) throw new Error("Verification not found");
verification = res.data;
notes = verification.reviewer_notes ?? "";
verf = Object.fromEntries(
ACTIVITIES.map((a) => [
a,
verfChoiceFrom(verification![VERF_COLUMN[a]]),
]),
) as Record<Activity, VerfChoice>;
} catch (err) {
loadError = errorMessage(err);
} finally {
loading = false;
}
}
function toggleVerf(activity: Activity, choice: VerfChoice) {
if (isReadOnly) return;
verf[activity] = verf[activity] === choice ? "unset" : choice;
}
async function requestAction() {
submitting = "action";
submitError = null;
try {
const res = await api
.verifications({ id })
["request-action"].post({
reviewerNotes: notes || undefined,
activityVerifications: toActivityVerifications(verf),
});
if (res.error) throw res.error;
await goto("/verification/verifications");
} catch (err) {
submitError = errorMessage(err);
} finally {
submitting = undefined;
}
}
async function complete() {
submitting = "complete";
submitError = null;
try {
const res = await api.verifications({ id }).complete.post({
activityVerifications: toActivityVerifications(verf),
});
if (res.error) throw res.error;
await goto("/verification/verifications");
} catch (err) {
submitError = errorMessage(err);
} finally {
submitting = undefined;
}
}
onMount(load);
</script>
<div class="w-full mt-10 mb-5">
<a
href="/verification/verifications"
class="link link-hover text-sm opacity-70">&larr; Back to verifications</a
>
</div>
{#if loading}
<div class="w-full flex justify-center pt-10">
<span class="loading loading-spinner loading-lg"></span>
</div>
{:else if loadError}
<div role="alert" class="alert alert-error w-full mb-4">
<span>{loadError}</span>
</div>
{:else if verification}
{@const v = verification}
<div class="w-full flex items-center gap-3 flex-wrap mb-6">
<h1 class="text-xl font-semibold">{v.name}</h1>
<div class="badge {STATUS_BADGE[v.status as VerificationStatus]}">
{v.status}
</div>
<span class="text-sm opacity-70"
>{v.gender} · age {v.age} · {Math.round(kgToLb(v.weight))} lb</span
>
</div>
<div class="w-full flex flex-col gap-4 bg-base-200/60 rounded-lg p-6">
<div class="flex items-center justify-between">
<h2 class="text-lg font-semibold">Activities</h2>
<span class="text-sm opacity-70"
>{reviewedCount} / {ACTIVITIES.length} reviewed</span
>
</div>
<div class="overflow-x-auto">
<table class="table table-sm">
<thead>
<tr>
<th>Activity</th>
<th>Claimed</th>
<th>Result</th>
</tr>
</thead>
<tbody>
{#each ACTIVITIES as activity (activity)}
<tr>
<td>{activity}</td>
<td class="font-semibold">
{formatPerformance(
activity,
v[PERF_COLUMN[activity]],
)}
</td>
<td>
<div class="join">
<button
class="btn btn-xs join-item {verf[
activity
] === 'pass'
? 'btn-success'
: 'btn-outline btn-success'}"
disabled={isReadOnly}
onclick={() =>
toggleVerf(activity, "pass")}
>
Pass
</button>
<button
class="btn btn-xs join-item {verf[
activity
] === 'fail'
? 'btn-error'
: 'btn-outline btn-error'}"
disabled={isReadOnly}
onclick={() =>
toggleVerf(activity, "fail")}
>
Fail
</button>
</div>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
</div>
<div class="w-full flex flex-col gap-4 bg-base-200/60 rounded-lg p-6 mt-4">
<h2 class="text-lg font-semibold">Media ({v.media.length})</h2>
{#if v.media.length === 0}
<span class="opacity-60">No media uploaded</span>
{:else}
<ul class="flex flex-col gap-2">
{#each v.media as file, i (file.key)}
<li class="flex items-center gap-3 flex-wrap">
<a
class="link link-primary"
href={file.url}
target="_blank"
rel="noopener noreferrer"
>
File {i + 1}
</a>
<span class="text-xs opacity-60">
{formatSize(file.size)} · uploaded {formatDate(
file.lastModified,
)}
</span>
</li>
{/each}
</ul>
{/if}
</div>
<div class="w-full flex flex-col gap-4 bg-base-200/60 rounded-lg p-6 mt-4">
<label class="form-control">
<span class="label mb-1 text-xs">Reviewer notes</span>
<textarea
class="textarea textarea-bordered w-full"
rows="3"
placeholder="What needs to be fixed?"
disabled={isReadOnly}
bind:value={notes}
></textarea>
</label>
{#if submitError}
<div role="alert" class="alert alert-error">
<span>{submitError}</span>
</div>
{/if}
<div class="flex items-center gap-2 justify-end">
{#if isReadOnly}
<span class="text-sm opacity-70">
{v.status === "completed"
? "This verification is completed and read-only."
: v.status === "draft"
? "This verification is still a draft (the player hasn't finished uploading) and is read-only."
: "This verification is waiting on the player to resubmit and is read-only."}
</span>
{:else}
{#if !allReviewed}
<span class="text-xs text-warning"
>Mark every activity Pass or Fail to complete</span
>
{/if}
<button
class="btn btn-warning"
disabled={!!submitting}
onclick={requestAction}
>
{submitting === "action" ? "Submitting..." : "Request action"}
</button>
<button
class="btn btn-success"
disabled={!!submitting || !allReviewed}
onclick={complete}
>
{submitting === "complete" ? "Submitting..." : "Complete"}
</button>
{/if}
</div>
</div>
{/if}
+2 -1
View File
@@ -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",
},
+1
View File
@@ -19,6 +19,7 @@
},
"dependencies": {
"pino": "^10.4.0",
"pino-pretty": "^13.1.3",
"@sinclair/typebox": "^0.34.52"
}
}