Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db206bafa3 | ||
|
|
91f682ec71 | ||
|
|
930bd61e62 | ||
|
|
b66980c0fb | ||
|
|
5101bd3259 |
@@ -19,3 +19,4 @@ advisor and code reviewer, not an implementer:
|
|||||||
- Only give a code review when explicitly asked (e.g. "review this",
|
- Only give a code review when explicitly asked (e.g. "review this",
|
||||||
`/code-review`, `/security-review`) — don't volunteer review commentary
|
`/code-review`, `/security-review`) — don't volunteer review commentary
|
||||||
on code you see in passing.
|
on code you see in passing.
|
||||||
|
- Reduce comment usage as much as possible unless the code is particularly confusing and needs an explanation
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ export async function up(db: Kysely<any>): Promise<void> {
|
|||||||
await db.schema.createTable("verifications")
|
await db.schema.createTable("verifications")
|
||||||
.$call(addDefaultColumns)
|
.$call(addDefaultColumns)
|
||||||
.addColumn("assessment_id", "bigint", (cb) => cb.notNull().unique())
|
.addColumn("assessment_id", "bigint", (cb) => cb.notNull().unique())
|
||||||
.addColumn("status", "text", (cb) => cb.notNull().defaultTo("request")) // request | in_review | action_requested | completed
|
.addColumn("status", "text", (cb) => cb.notNull().defaultTo("draft")) // draft | submitted | in_review | action_requested | completed
|
||||||
|
.addColumn("submitted_at", "timestamptz")
|
||||||
.addColumn("completed_at", "timestamptz")
|
.addColumn("completed_at", "timestamptz")
|
||||||
.addColumn("completed_by", "uuid")
|
.addColumn("completed_by", "uuid")
|
||||||
.addColumn("media_key_back_squat", "text")
|
.addColumn("media_key_back_squat", "text")
|
||||||
|
|||||||
@@ -73,17 +73,20 @@ async function seedTestAssessment(accountId: string): Promise<string> {
|
|||||||
const assessmentId = await seedTestAssessment(accountId);
|
const assessmentId = await seedTestAssessment(accountId);
|
||||||
|
|
||||||
const verifications = new VerificationsService();
|
const verifications = new VerificationsService();
|
||||||
const verification = await verifications.request(assessmentId, accountId, {
|
const verification = await verifications.create(assessmentId, {
|
||||||
[Activity.BackSquat]: "https://example.com/videos/back-squat.mp4",
|
[Activity.BackSquat]: `verifications/${assessmentId}/back-squat.mp4`,
|
||||||
[Activity.Deadlift]: "https://example.com/videos/deadlift.mp4",
|
[Activity.Deadlift]: `verifications/${assessmentId}/deadlift.mp4`,
|
||||||
[Activity.BenchPress]: "https://example.com/videos/bench-press.mp4",
|
[Activity.BenchPress]: `verifications/${assessmentId}/bench-press.mp4`,
|
||||||
[Activity.Run]: "https://example.com/videos/run.mp4",
|
[Activity.Run]: `verifications/${assessmentId}/run.png`,
|
||||||
[Activity.BroadJump]: "https://example.com/videos/broad-jump.mp4",
|
[Activity.BroadJump]: `verifications/${assessmentId}/broad-jump.mp4`,
|
||||||
[Activity.ConeDrill]: "https://example.com/videos/cone-drill.mp4",
|
[Activity.ConeDrill]: `verifications/${assessmentId}/cone-drill.mp4`,
|
||||||
});
|
});
|
||||||
if (!verification) throw new Error("Failed to seed verification request — assessment ownership check failed");
|
if (!verification) throw new Error("Test assessment already has a verification; clear the verifications table first");
|
||||||
|
|
||||||
log.info({ id: verification.id, assessmentId, accountId }, "seeded test verification request");
|
const submitted = await verifications.submit(verification.id);
|
||||||
|
if (!submitted) throw new Error("Failed to submit test verification");
|
||||||
|
|
||||||
|
log.info({ id: submitted.id, status: submitted.status, assessmentId, accountId }, "seeded test verification request");
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
log.error({ err }, "seed failed");
|
log.error({ err }, "seed failed");
|
||||||
|
|||||||
+147
-68
@@ -1,23 +1,26 @@
|
|||||||
import {
|
import {
|
||||||
ActivityPerformanceSchema,
|
ActivityPerformanceSchema,
|
||||||
ActivityVerificationsSchema,
|
ActivityVerificationsSchema,
|
||||||
ActivityVideosSchema,
|
ActivityMediaKeysSchema,
|
||||||
PlayerSchema,
|
PlayerSchema,
|
||||||
|
minToMs,
|
||||||
|
Activity,
|
||||||
} from "@blade-and-brawn/domain"
|
} from "@blade-and-brawn/domain"
|
||||||
import { cors } from "@elysiajs/cors";
|
import { cors } from "@elysiajs/cors";
|
||||||
import { Elysia, NotFoundError, redirect, status, t } from "elysia";
|
import { Elysia, redirect, status, t } from "elysia";
|
||||||
import {
|
import {
|
||||||
PrintfulError,
|
PrintfulError,
|
||||||
WebflowError,
|
WebflowError,
|
||||||
Printful,
|
Printful,
|
||||||
Webflow,
|
Webflow,
|
||||||
} from "@blade-and-brawn/commerce";
|
} from "@blade-and-brawn/commerce";
|
||||||
import { DEFAULT_NAME, DUMMY_PASSWORD_HASH, env, log } from "./util";
|
import { AccountIdSchema, BigIntIdSchema, DEFAULT_NAME, DUMMY_PASSWORD_HASH, env, log } from "./util";
|
||||||
import serverTiming from "@elysia/server-timing";
|
import serverTiming from "@elysia/server-timing";
|
||||||
import jwt from "@elysia/jwt";
|
import jwt from "@elysia/jwt";
|
||||||
import { CommerceService, WOrderStatusSchema } from "./services/commerce";
|
import { CommerceService, WOrderStatusSchema } from "./services/commerce";
|
||||||
import cluster from "node:cluster";
|
import cluster from "node:cluster";
|
||||||
import { randomUUIDv7, sleep } from "bun";
|
import { randomUUIDv7, sleep, S3Client } from "bun";
|
||||||
|
import { DatabaseError } from "pg";
|
||||||
import { CalculatorService, CalculatorUnavailableError } from "./services/calculator";
|
import { CalculatorService, CalculatorUnavailableError } from "./services/calculator";
|
||||||
import { StandardsParamsSchema } from "@blade-and-brawn/calculator";
|
import { StandardsParamsSchema } from "@blade-and-brawn/calculator";
|
||||||
import { StandardsService } from "./services/standards";
|
import { StandardsService } from "./services/standards";
|
||||||
@@ -46,6 +49,17 @@ const s = (() => {
|
|||||||
return { Standards, Calculator, Commerce, Accounts, Events, Assessments, Verifications };
|
return { Standards, Calculator, Commerce, Accounts, Events, Assessments, Verifications };
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
// R2 BUCKETS
|
||||||
|
// -----------------------
|
||||||
|
const r2 = {
|
||||||
|
verificationMedia: new S3Client({
|
||||||
|
accessKeyId: env.R2_ACCESS_KEY_ID,
|
||||||
|
secretAccessKey: env.R2_SECRET_ACCESS_KEY,
|
||||||
|
bucket: "verification-media",
|
||||||
|
endpoint: env.R2_URL,
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
// QUEUES
|
// QUEUES
|
||||||
// -----------------------
|
// -----------------------
|
||||||
const queues = [
|
const queues = [
|
||||||
@@ -62,14 +76,14 @@ const authPlugin = new Elysia({ name: "auth" })
|
|||||||
authAdmin: {
|
authAdmin: {
|
||||||
async resolve({ jwt, cookie: { auth } }) {
|
async resolve({ jwt, cookie: { auth } }) {
|
||||||
const token = auth.value && await jwt.verify(auth.value);
|
const token = auth.value && await jwt.verify(auth.value);
|
||||||
if (!token || token.role !== "admin" || !token.accountId || !token.sessionId) throw status(401, "Unauthorized");
|
if (!token || token.role !== "admin" || !token.accountId || !token.sessionId) return status(401, { error: "Unauthorized" });
|
||||||
return { role: token.role.toString(), sessionId: token.sessionId.toString(), accountId: token.accountId.toString() };
|
return { role: token.role.toString(), sessionId: token.sessionId.toString(), accountId: token.accountId.toString() };
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
auth: {
|
auth: {
|
||||||
async resolve({ jwt, cookie: { auth } }) {
|
async resolve({ jwt, cookie: { auth } }) {
|
||||||
const token = auth.value && await jwt.verify(auth.value);
|
const token = auth.value && await jwt.verify(auth.value);
|
||||||
if (!token || !token.role || !token.accountId || !token.sessionId) throw status(401, "Unauthorized");
|
if (!token || !token.role || !token.accountId || !token.sessionId) return status(401, { error: "Unauthorized" });
|
||||||
return { role: token.role.toString(), sessionId: token.sessionId.toString(), accountId: token.accountId.toString() };
|
return { role: token.role.toString(), sessionId: token.sessionId.toString(), accountId: token.accountId.toString() };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -106,6 +120,11 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
|
|
||||||
.onError(({ code, error }) => {
|
.onError(({ code, error }) => {
|
||||||
|
// Database Errors
|
||||||
|
if (error instanceof DatabaseError && error.code === "23505")
|
||||||
|
return status(409, { error: "Conflicts with an existing record" });
|
||||||
|
|
||||||
|
// Custom Errors
|
||||||
switch (code) {
|
switch (code) {
|
||||||
case "PrintfulError":
|
case "PrintfulError":
|
||||||
case "WebflowError":
|
case "WebflowError":
|
||||||
@@ -126,16 +145,18 @@ export const app = new Elysia()
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
.onAfterResponse(({ request, status, path }) => {
|
.onAfterResponse(({ request, set, path, responseValue }) => {
|
||||||
if (env.NODE_ENV === "development") {
|
if (env.NODE_ENV === "development") {
|
||||||
const skip: Record<string, string[]> = { "/commerce/products/sync/": ["GET"] };
|
const skip: Record<string, string[]> = { "/commerce/products/sync/": ["GET"] };
|
||||||
if (skip[path]?.includes(request.method)) return;
|
if (skip[path]?.includes(request.method)) return;
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info({
|
const failed = Number(set.status) >= 400;
|
||||||
|
log[failed ? "warn" : "info"]({
|
||||||
method: request.method,
|
method: request.method,
|
||||||
path,
|
path,
|
||||||
status
|
status: set.status,
|
||||||
|
...(failed && { response: responseValue }),
|
||||||
}, "request");
|
}, "request");
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -146,7 +167,7 @@ export const app = new Elysia()
|
|||||||
.post("/auth/login", async ({ jwt, body: { password, email }, cookie: { auth } }) => {
|
.post("/auth/login", async ({ jwt, body: { password, email }, cookie: { auth } }) => {
|
||||||
const account = await s.Accounts.getByEmail(email);
|
const account = await s.Accounts.getByEmail(email);
|
||||||
const password_match = await Bun.password.verify(password, account?.password_hash ?? DUMMY_PASSWORD_HASH);
|
const password_match = await Bun.password.verify(password, account?.password_hash ?? DUMMY_PASSWORD_HASH);
|
||||||
if (!account || !password_match) throw status(401, "Invalid credentials");
|
if (!account || !password_match) return status(401, { error: "Invalid credentials" });
|
||||||
|
|
||||||
auth.set({
|
auth.set({
|
||||||
value: await jwt.sign({ role: account.role, sessionId: randomUUIDv7(), accountId: account.id, exp: JWT_EXP }),
|
value: await jwt.sign({ role: account.role, sessionId: randomUUIDv7(), accountId: account.id, exp: JWT_EXP }),
|
||||||
@@ -184,10 +205,10 @@ export const app = new Elysia()
|
|||||||
return redirect(url.toString(), 302);
|
return redirect(url.toString(), 302);
|
||||||
})
|
})
|
||||||
.get("/callback", async ({ query, cookie: { authDiscord, auth }, jwt }) => {
|
.get("/callback", async ({ query, cookie: { authDiscord, auth }, jwt }) => {
|
||||||
if (query.error) throw status(400, { error: query.error_description ? `${query.error}: ${query.error_description}` : query.error });
|
if (query.error) return status(400, { error: query.error_description ? `${query.error}: ${query.error_description}` : query.error });
|
||||||
|
|
||||||
if (!query.state) throw status(400, "No Discord OAuth2 state query parameter provided");
|
if (!query.state) return status(400, { error: "No Discord OAuth2 state query parameter provided" });
|
||||||
if (query.state !== authDiscord.value) throw status(400, "Invalid Discord OAuth state");
|
if (query.state !== authDiscord.value) return status(400, { error: "Invalid Discord OAuth state" });
|
||||||
|
|
||||||
const tokenRes = await fetch("https://discord.com/api/oauth2/token", {
|
const tokenRes = await fetch("https://discord.com/api/oauth2/token", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -204,7 +225,7 @@ export const app = new Elysia()
|
|||||||
});
|
});
|
||||||
if (!tokenRes.ok) {
|
if (!tokenRes.ok) {
|
||||||
const errorBody = await tokenRes.json().catch(() => null);
|
const errorBody = await tokenRes.json().catch(() => null);
|
||||||
throw status(502, { error: errorBody ?? "Discord token exchange failed" });
|
return status(502, { error: errorBody ?? "Discord token exchange failed" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const tokenResPayload = await tokenRes.json();
|
const tokenResPayload = await tokenRes.json();
|
||||||
@@ -215,7 +236,7 @@ export const app = new Elysia()
|
|||||||
});
|
});
|
||||||
if (!identityRes.ok) {
|
if (!identityRes.ok) {
|
||||||
const errorBody = await identityRes.json().catch(() => null);
|
const errorBody = await identityRes.json().catch(() => null);
|
||||||
throw status(502, { error: errorBody ?? "Failed to fetch Discord identity" });
|
return status(502, { error: errorBody ?? "Failed to fetch Discord identity" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const identityResPayload = await identityRes.json();
|
const identityResPayload = await identityRes.json();
|
||||||
@@ -274,7 +295,7 @@ export const app = new Elysia()
|
|||||||
.post("/standards/config/switch", async ({ body: { standardsConfigId } }) => {
|
.post("/standards/config/switch", async ({ body: { standardsConfigId } }) => {
|
||||||
await s.Calculator.Standards.Config.switch(standardsConfigId);
|
await s.Calculator.Standards.Config.switch(standardsConfigId);
|
||||||
}, {
|
}, {
|
||||||
body: t.Object({ standardsConfigId: t.String() })
|
body: t.Object({ standardsConfigId: BigIntIdSchema })
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -282,7 +303,7 @@ export const app = new Elysia()
|
|||||||
.post("/configs", async ({ body: { name, datasetId, params } }) => {
|
.post("/configs", async ({ body: { name, datasetId, params } }) => {
|
||||||
return await s.Standards.Configs.create(name, datasetId, params);
|
return await s.Standards.Configs.create(name, datasetId, params);
|
||||||
}, {
|
}, {
|
||||||
body: t.Object({ name: t.String(), datasetId: t.String(), params: StandardsParamsSchema })
|
body: t.Object({ name: t.String(), datasetId: BigIntIdSchema, params: StandardsParamsSchema })
|
||||||
})
|
})
|
||||||
.get("/configs", async () => {
|
.get("/configs", async () => {
|
||||||
return await s.Standards.Configs.list();
|
return await s.Standards.Configs.list();
|
||||||
@@ -290,29 +311,29 @@ export const app = new Elysia()
|
|||||||
.get("/configs/:id", async ({ params: { id } }) => {
|
.get("/configs/:id", async ({ params: { id } }) => {
|
||||||
return await s.Standards.Configs.get(id);
|
return await s.Standards.Configs.get(id);
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() })
|
params: t.Object({ id: BigIntIdSchema })
|
||||||
})
|
})
|
||||||
.put("/configs/:id", async ({ params: { id }, body: { name, datasetId, params: parameters } }) => {
|
.put("/configs/:id", async ({ params: { id }, body: { name, datasetId, params: parameters } }) => {
|
||||||
await s.Standards.Configs.update(id, name, datasetId, parameters);
|
await s.Standards.Configs.update(id, name, datasetId, parameters);
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() }),
|
params: t.Object({ id: BigIntIdSchema }),
|
||||||
body: t.Object({ name: t.String(), datasetId: t.String(), params: StandardsParamsSchema })
|
body: t.Object({ name: t.String(), datasetId: BigIntIdSchema, params: StandardsParamsSchema })
|
||||||
})
|
})
|
||||||
.delete("/configs/:id", async ({ params: { id } }) => {
|
.delete("/configs/:id", async ({ params: { id } }) => {
|
||||||
await s.Standards.Configs.delete(id);
|
await s.Standards.Configs.delete(id);
|
||||||
}, { params: t.Object({ id: t.String() }) })
|
}, { params: t.Object({ id: BigIntIdSchema }) })
|
||||||
.get("/datasets", async () => {
|
.get("/datasets", async () => {
|
||||||
return await s.Standards.Datasets.list();
|
return await s.Standards.Datasets.list();
|
||||||
})
|
})
|
||||||
.get("/datasets/:id", async ({ params: { id } }) => {
|
.get("/datasets/:id", async ({ params: { id } }) => {
|
||||||
return await s.Standards.Datasets.get(id);
|
return await s.Standards.Datasets.get(id);
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() })
|
params: t.Object({ id: BigIntIdSchema })
|
||||||
})
|
})
|
||||||
.patch("/datasets/:id", async ({ params: { id }, body: { name } }) => {
|
.patch("/datasets/:id", async ({ params: { id }, body: { name } }) => {
|
||||||
await s.Standards.Datasets.update(id, name);
|
await s.Standards.Datasets.update(id, name);
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() }),
|
params: t.Object({ id: BigIntIdSchema }),
|
||||||
body: t.Object({ name: t.String() })
|
body: t.Object({ name: t.String() })
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
@@ -343,7 +364,7 @@ export const app = new Elysia()
|
|||||||
// Sync status
|
// Sync status
|
||||||
.get("/", async ({ sessionId }) => {
|
.get("/", async ({ sessionId }) => {
|
||||||
const latestSyncState = await s.Commerce.Apparel.Syncs.getLatestSyncState(sessionId);
|
const latestSyncState = await s.Commerce.Apparel.Syncs.getLatestSyncState(sessionId);
|
||||||
if (!latestSyncState) throw new NotFoundError("No product sync found for the provided session");
|
if (!latestSyncState) return status(404, { error: "No product sync found for the provided session" });
|
||||||
return latestSyncState;
|
return latestSyncState;
|
||||||
})
|
})
|
||||||
// Run sync
|
// Run sync
|
||||||
@@ -362,10 +383,10 @@ export const app = new Elysia()
|
|||||||
)
|
)
|
||||||
.get("/:pProductId", async ({ params: { pProductId } }) => {
|
.get("/:pProductId", async ({ params: { pProductId } }) => {
|
||||||
const pProduct = await s.Commerce.Printful.Products.get(pProductId);
|
const pProduct = await s.Commerce.Printful.Products.get(pProductId);
|
||||||
if (!pProduct) throw new NotFoundError("Missing printful product");
|
if (!pProduct) return status(404, { error: "Missing printful product" });
|
||||||
|
|
||||||
const wProductId = pProduct.sync_product.external_id.split("-")[0];
|
const wProductId = pProduct.sync_product.external_id.split("-")[0];
|
||||||
if (!wProductId) throw new NotFoundError("Missing webflow product ID");
|
if (!wProductId) return status(404, { error: "Missing webflow product ID" });
|
||||||
|
|
||||||
const wProduct = await s.Commerce.Webflow.Products.get(wProductId);
|
const wProduct = await s.Commerce.Webflow.Products.get(wProductId);
|
||||||
|
|
||||||
@@ -398,7 +419,7 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
.get("/:wOrderId", async ({ params: { wOrderId } }) => {
|
.get("/:wOrderId", async ({ params: { wOrderId } }) => {
|
||||||
const wOrder = await s.Commerce.Webflow.Orders.get(wOrderId);
|
const wOrder = await s.Commerce.Webflow.Orders.get(wOrderId);
|
||||||
if (!wOrder) throw new NotFoundError("Missing webflow order");
|
if (!wOrder) return status(404, { error: "Missing webflow order" });
|
||||||
|
|
||||||
const pOrder = await s.Commerce.Printful.Orders.get(`@${wOrder.orderId}`);
|
const pOrder = await s.Commerce.Printful.Orders.get(`@${wOrder.orderId}`);
|
||||||
|
|
||||||
@@ -406,10 +427,10 @@ export const app = new Elysia()
|
|||||||
}, { params: t.Object({ wOrderId: t.String() }) })
|
}, { params: t.Object({ wOrderId: t.String() }) })
|
||||||
.post("/sync/:wOrderId", async ({ params: { wOrderId } }) => {
|
.post("/sync/:wOrderId", async ({ params: { wOrderId } }) => {
|
||||||
const wOrder = await s.Commerce.Webflow.Orders.get(wOrderId);
|
const wOrder = await s.Commerce.Webflow.Orders.get(wOrderId);
|
||||||
if (!wOrder) throw new NotFoundError("Missing webflow order");
|
if (!wOrder) return status(404, { error: "Missing webflow order" });
|
||||||
|
|
||||||
const pOrder = await s.Commerce.Printful.Orders.get(`@${wOrder.orderId}`);
|
const pOrder = await s.Commerce.Printful.Orders.get(`@${wOrder.orderId}`);
|
||||||
if (pOrder) throw status(409, { error: "Cannot sync an already synced webflow order" });
|
if (pOrder) return status(409, { error: "Cannot sync an already synced webflow order" });
|
||||||
|
|
||||||
await s.Commerce.Apparel.Orders.Queue.enqueue({
|
await s.Commerce.Apparel.Orders.Queue.enqueue({
|
||||||
type: "apparel_order_create",
|
type: "apparel_order_create",
|
||||||
@@ -441,16 +462,16 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
.get("/:id", async ({ params: { id } }) => {
|
.get("/:id", async ({ params: { id } }) => {
|
||||||
const event = await s.Events.get(id);
|
const event = await s.Events.get(id);
|
||||||
if (!event) throw new NotFoundError("Event not found");
|
if (!event) return status(404, { error: "Event not found" });
|
||||||
return { ...event, status: EventsService.status(event) };
|
return { ...event, status: EventsService.status(event) };
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() })
|
params: t.Object({ id: BigIntIdSchema })
|
||||||
})
|
})
|
||||||
.post("/:id/retry", async ({ params: { id } }) => {
|
.post("/:id/retry", async ({ params: { id } }) => {
|
||||||
const retried = await s.Events.retry(id);
|
const retried = await s.Events.retry(id);
|
||||||
if (!retried) throw new NotFoundError("Event not found or not in a failed state");
|
if (!retried) return status(404, { error: "Event not found or not in a failed state" });
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() })
|
params: t.Object({ id: BigIntIdSchema })
|
||||||
})
|
})
|
||||||
.get("/groups", async ({ }) => queues.map((q) => q.group))
|
.get("/groups", async ({ }) => queues.map((q) => q.group))
|
||||||
)
|
)
|
||||||
@@ -460,24 +481,24 @@ export const app = new Elysia()
|
|||||||
// TODO: for added security, could enforce bot or admin only access
|
// TODO: for added security, could enforce bot or admin only access
|
||||||
.get("/:id/stats", async ({ params: { id } }) => {
|
.get("/:id/stats", async ({ params: { id } }) => {
|
||||||
const stats = await s.Accounts.stats(id);
|
const stats = await s.Accounts.stats(id);
|
||||||
if (!stats) throw new NotFoundError("Account stats not found");
|
if (!stats) return status(404, { error: "Account stats not found" });
|
||||||
return stats;
|
return stats;
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() })
|
params: t.Object({ id: AccountIdSchema })
|
||||||
})
|
})
|
||||||
.guard({ authAdmin: true }, (app) => app
|
.guard({ authAdmin: true }, (app) => app
|
||||||
.get("/:id", async ({ params: { id } }) => {
|
.get("/:id", async ({ params: { id } }) => {
|
||||||
const account = await s.Accounts.get(id);
|
const account = await s.Accounts.get(id);
|
||||||
if (!account) throw new NotFoundError("Account not found");
|
if (!account) return status(404, { error: "Account not found" });
|
||||||
return account;
|
return account;
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() })
|
params: t.Object({ id: AccountIdSchema })
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
.group("/me", { auth: true }, (app) => app
|
.group("/me", { auth: true }, (app) => app
|
||||||
.get("/stats", async ({ accountId }) => {
|
.get("/stats", async ({ accountId }) => {
|
||||||
const stats = await s.Accounts.stats(accountId);
|
const stats = await s.Accounts.stats(accountId);
|
||||||
if (!stats) throw new NotFoundError("Account stats not found");
|
if (!stats) return status(404, { error: "Account stats not found" });
|
||||||
return stats;
|
return stats;
|
||||||
})
|
})
|
||||||
.post("/assessments", async ({ body: { player, activityPerformances }, accountId }) => {
|
.post("/assessments", async ({ body: { player, activityPerformances }, accountId }) => {
|
||||||
@@ -488,32 +509,91 @@ export const app = new Elysia()
|
|||||||
activityPerformances: t.Array(ActivityPerformanceSchema)
|
activityPerformances: t.Array(ActivityPerformanceSchema)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
// TODO: handle @ formatted accountIds
|
||||||
.get("/assessments", async ({ accountId }) => {
|
.get("/assessments", async ({ accountId }) => {
|
||||||
return await s.Assessments.list({ filter: { accountId } });
|
return await s.Assessments.list({ filter: { accountId } });
|
||||||
})
|
})
|
||||||
.delete("/assessments/:id", async ({ params: { id }, accountId }) => {
|
.delete("/assessments/:id", async ({ params: { id }, accountId }) => {
|
||||||
const deleted = await s.Assessments.delete(id, accountId);
|
const deleted = await s.Assessments.delete(id, accountId);
|
||||||
if (!deleted) throw new NotFoundError("Assessment not found");
|
if (!deleted) return status(404, { error: "Assessment not found" });
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() })
|
params: t.Object({ id: BigIntIdSchema })
|
||||||
})
|
})
|
||||||
.post("/verifications", async ({ body: { assessmentId, activityVideoUrls }, accountId }) => {
|
.post("/verifications", async ({ body: { assessmentId }, accountId }) => {
|
||||||
const requested = await s.Verifications.request(assessmentId, accountId, activityVideoUrls);
|
const assessment = await s.Assessments.get(assessmentId, accountId);
|
||||||
if (!requested) throw new NotFoundError("Assessment not found");
|
if (!assessment) return status(404, { error: "Assessment not found" });
|
||||||
return requested;
|
|
||||||
|
// TODO: only allow a single active non-completed verification at a time
|
||||||
|
|
||||||
|
const created = await s.Verifications.create(assessmentId);
|
||||||
|
if (!created) return status(409, { error: "This assessment already has a verification" });
|
||||||
|
|
||||||
|
// Generate upload urls
|
||||||
|
const activityMediaUrls: Record<string, string> = {};
|
||||||
|
for (const activity of Object.values(Activity)) {
|
||||||
|
activityMediaUrls[activity] = r2.verificationMedia.presign(
|
||||||
|
`${assessmentId}/${activity}-${crypto.randomUUID()}`,
|
||||||
|
{
|
||||||
|
method: "PUT",
|
||||||
|
expiresIn: 30 * 60 // 30 minutes
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { created, activityMediaUrls };
|
||||||
}, {
|
}, {
|
||||||
body: t.Object({
|
body: t.Object({
|
||||||
assessmentId: t.String(),
|
assessmentId: BigIntIdSchema
|
||||||
activityVideoUrls: ActivityVideosSchema,
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
.patch("/verifications/:id", async ({ params: { id }, body: { assessmentId, activityMediaKeys }, accountId }) => {
|
||||||
|
const verification = await s.Verifications.get(id, accountId);
|
||||||
|
if (!verification) return status(404, { error: "Verification not found" });
|
||||||
|
|
||||||
|
if (assessmentId === undefined && Object.keys(activityMediaKeys ?? {}).length === 0)
|
||||||
|
return status(400, { error: "Nothing to update" });
|
||||||
|
|
||||||
|
if (assessmentId !== undefined && !await s.Assessments.get(assessmentId, accountId))
|
||||||
|
return status(404, { error: "Assessment not found" });
|
||||||
|
|
||||||
|
const updated = await s.Verifications.update(id, { assessmentId, activityMediaKeys });
|
||||||
|
if (!updated) return status(409, { error: `Cannot update a ${verification.status} verification` });
|
||||||
|
return updated;
|
||||||
|
}, {
|
||||||
|
params: t.Object({ id: BigIntIdSchema }),
|
||||||
|
body: t.Object({
|
||||||
|
assessmentId: t.Optional(BigIntIdSchema),
|
||||||
|
activityMediaKeys: t.Optional(ActivityMediaKeysSchema),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.post("/verifications/:id/submit", async ({ params: { id }, accountId }) => {
|
||||||
|
if (!await s.Verifications.get(id, accountId)) return status(404, { error: "Verification not found" });
|
||||||
|
|
||||||
|
const submitted = await s.Verifications.submit(id);
|
||||||
|
if (submitted) {
|
||||||
|
// TODO: trigger discord webhook here
|
||||||
|
return submitted;
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = await s.Verifications.get(id, accountId);
|
||||||
|
if (!current) return status(404, { error: "Verification not found" });
|
||||||
|
if (current.status === "submitted") return { id: current.id, status: current.status };
|
||||||
|
|
||||||
|
const missingActivityMediaKeys = VerificationsService.missingActivityMediaKeys(current);
|
||||||
|
return status(409, {
|
||||||
|
error: current.status === "draft" && missingActivityMediaKeys.length > 0
|
||||||
|
? `Missing media for: ${missingActivityMediaKeys.join(", ")}`
|
||||||
|
: `Cannot submit a ${current.status} verification`
|
||||||
|
});
|
||||||
|
}, {
|
||||||
|
params: t.Object({ id: BigIntIdSchema })
|
||||||
|
})
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
// ASSESSMENTS
|
// ASSESSMENTS
|
||||||
.group("/assessments", { authAdmin: true }, (app) => app
|
.group("/assessments", { authAdmin: true }, (app) => app
|
||||||
.post("/", async ({ body: { player, activityPerformances, id } }) => {
|
.post("/", async ({ body: { player, activityPerformances, id } }) => {
|
||||||
await s.Assessments.create(player, activityPerformances, id);
|
return await s.Assessments.create(player, activityPerformances, id);
|
||||||
}, {
|
}, {
|
||||||
body: t.Object({
|
body: t.Object({
|
||||||
player: PlayerSchema,
|
player: PlayerSchema,
|
||||||
@@ -523,9 +603,10 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
.put("/:id", async ({ body: { player, activityPerformances }, params: { id } }) => {
|
.put("/:id", async ({ body: { player, activityPerformances }, params: { id } }) => {
|
||||||
const updated = await s.Assessments.update(id, player, activityPerformances);
|
const updated = await s.Assessments.update(id, player, activityPerformances);
|
||||||
if (!updated) throw new NotFoundError("Assessment not found");
|
if (!updated) return status(404, { error: "Assessment not found" });
|
||||||
|
return updated;
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() }),
|
params: t.Object({ id: BigIntIdSchema }),
|
||||||
body: t.Object({
|
body: t.Object({
|
||||||
player: PlayerSchema,
|
player: PlayerSchema,
|
||||||
activityPerformances: t.Array(ActivityPerformanceSchema),
|
activityPerformances: t.Array(ActivityPerformanceSchema),
|
||||||
@@ -550,36 +631,34 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
.get("/:id", async ({ params: { id } }) => {
|
.get("/:id", async ({ params: { id } }) => {
|
||||||
const verification = await s.Verifications.get(id);
|
const verification = await s.Verifications.get(id);
|
||||||
if (!verification) throw new NotFoundError("Verification not found");
|
if (!verification) return status(404, { error: "Verification not found" });
|
||||||
return verification;
|
return verification;
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() })
|
params: t.Object({ id: BigIntIdSchema })
|
||||||
})
|
})
|
||||||
.post("/:id/request-action", async ({ params: { id }, body: { reviewerNotes, activityVerifications } }) => {
|
.post("/:id/request-action", async ({ params: { id }, body: { reviewerNotes, activityVerifications } }) => {
|
||||||
const verification = await s.Verifications.get(id);
|
|
||||||
if (!verification) throw new NotFoundError("Verification not found");
|
|
||||||
if (verification.status === "completed" || verification.status === "action_requested")
|
|
||||||
throw status(409, { error: "Cannot modify a completed or action-requested verification" });
|
|
||||||
|
|
||||||
const updated = await s.Verifications.requestAction(id, reviewerNotes ?? null, activityVerifications);
|
const updated = await s.Verifications.requestAction(id, reviewerNotes ?? null, activityVerifications);
|
||||||
if (!updated) throw new NotFoundError("Verification not found");
|
if (updated) return updated;
|
||||||
|
|
||||||
|
const verification = await s.Verifications.get(id);
|
||||||
|
if (!verification) return status(404, { error: "Verification not found" });
|
||||||
|
return status(409, { error: `Cannot request action on a ${verification.status} verification` });
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() }),
|
params: t.Object({ id: BigIntIdSchema }),
|
||||||
body: t.Object({
|
body: t.Object({
|
||||||
reviewerNotes: t.Optional(t.String()),
|
reviewerNotes: t.Optional(t.String()),
|
||||||
activityVerifications: ActivityVerificationsSchema,
|
activityVerifications: ActivityVerificationsSchema,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.post("/:id/complete", async ({ params: { id }, body: { activityVerifications }, accountId }) => {
|
.post("/:id/complete", async ({ params: { id }, body: { activityVerifications }, accountId }) => {
|
||||||
const verification = await s.Verifications.get(id);
|
|
||||||
if (!verification) throw new NotFoundError("Verification not found");
|
|
||||||
if (verification.status === "completed" || verification.status === "action_requested")
|
|
||||||
throw status(409, { error: "Cannot modify a completed or action-requested verification" });
|
|
||||||
|
|
||||||
const updated = await s.Verifications.complete(id, accountId, activityVerifications);
|
const updated = await s.Verifications.complete(id, accountId, activityVerifications);
|
||||||
if (!updated) throw new NotFoundError("Verification not found");
|
if (updated) return updated;
|
||||||
|
|
||||||
|
const verification = await s.Verifications.get(id);
|
||||||
|
if (!verification) return status(404, { error: "Verification not found" });
|
||||||
|
return status(409, { error: `Cannot complete a ${verification.status} verification` });
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: t.String() }),
|
params: t.Object({ id: BigIntIdSchema }),
|
||||||
body: t.Object({
|
body: t.Object({
|
||||||
activityVerifications: ActivityVerificationsSchema,
|
activityVerifications: ActivityVerificationsSchema,
|
||||||
})
|
})
|
||||||
@@ -590,7 +669,7 @@ export const app = new Elysia()
|
|||||||
.post("/webhooks/printful", async ({ body, query }) => {
|
.post("/webhooks/printful", async ({ body, query }) => {
|
||||||
// https://webflow.com/integrations/printful
|
// https://webflow.com/integrations/printful
|
||||||
if (!s.Commerce.Printful.Util.verifySecret(query.secret))
|
if (!s.Commerce.Printful.Util.verifySecret(query.secret))
|
||||||
throw status(400, "Invalid secret");
|
return status(400, { error: "Invalid secret" });
|
||||||
|
|
||||||
const payload = body as Printful.Webhook.EventPayload;
|
const payload = body as Printful.Webhook.EventPayload;
|
||||||
|
|
||||||
@@ -613,7 +692,7 @@ export const app = new Elysia()
|
|||||||
const pProduct = payload.data.sync_product;
|
const pProduct = payload.data.sync_product;
|
||||||
const wProductId = pProduct.external_id.split("-")[0];
|
const wProductId = pProduct.external_id.split("-")[0];
|
||||||
log.info({ externalId: payload.data.sync_product.external_id, wProductId }, "printful webhook: product deleted");
|
log.info({ externalId: payload.data.sync_product.external_id, wProductId }, "printful webhook: product deleted");
|
||||||
if (!wProductId) throw new NotFoundError("Missing webflow product ID");
|
if (!wProductId) return status(404, { error: "Missing webflow product ID" });
|
||||||
|
|
||||||
await s.Commerce.Apparel.Syncs.Queue.enqueue({
|
await s.Commerce.Apparel.Syncs.Queue.enqueue({
|
||||||
type: "apparel_sync_delete",
|
type: "apparel_sync_delete",
|
||||||
@@ -645,7 +724,7 @@ export const app = new Elysia()
|
|||||||
}, { query: t.Object({ secret: t.String() }) })
|
}, { query: t.Object({ secret: t.String() }) })
|
||||||
.post("/webhooks/webflow", async ({ request, body }) => {
|
.post("/webhooks/webflow", async ({ request, body }) => {
|
||||||
if (!s.Commerce.Webflow.Util.verifySecret(request, body))
|
if (!s.Commerce.Webflow.Util.verifySecret(request, body))
|
||||||
throw status(400, "Invalid signature");
|
return status(400, { error: "Invalid signature" });
|
||||||
|
|
||||||
const payload = body as Webflow.Webhook.EventPayload;
|
const payload = body as Webflow.Webhook.EventPayload;
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,14 @@ export class AssessmentsService {
|
|||||||
.executeTakeFirstOrThrow();
|
.executeTakeFirstOrThrow();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async get(id: string, accountId?: string) {
|
||||||
|
return await db.selectFrom("assessments")
|
||||||
|
.selectAll()
|
||||||
|
.where("id", "=", id)
|
||||||
|
.$if(accountId !== undefined, (qb) => qb.where("account_id", "=", accountId!))
|
||||||
|
.executeTakeFirst();
|
||||||
|
}
|
||||||
|
|
||||||
async list(opt: {
|
async list(opt: {
|
||||||
filter?: { accountId?: string },
|
filter?: { accountId?: string },
|
||||||
limit?: number,
|
limit?: number,
|
||||||
@@ -41,7 +49,7 @@ export class AssessmentsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async update(id: string, player: Player, activityPerformances: ActivityPerformance[]) {
|
async update(id: string, player: Player, activityPerformances: ActivityPerformance[]) {
|
||||||
const result = await db.updateTable("assessments")
|
return await db.updateTable("assessments")
|
||||||
.where("id", "=", id)
|
.where("id", "=", id)
|
||||||
.set({
|
.set({
|
||||||
name: player.name ?? "Anonymous",
|
name: player.name ?? "Anonymous",
|
||||||
@@ -55,8 +63,8 @@ export class AssessmentsService {
|
|||||||
perf_run: AssessmentsService.performanceFor(activityPerformances, Activity.Run),
|
perf_run: AssessmentsService.performanceFor(activityPerformances, Activity.Run),
|
||||||
perf_cone_drill: AssessmentsService.performanceFor(activityPerformances, Activity.ConeDrill),
|
perf_cone_drill: AssessmentsService.performanceFor(activityPerformances, Activity.ConeDrill),
|
||||||
})
|
})
|
||||||
|
.returning("id")
|
||||||
.executeTakeFirst();
|
.executeTakeFirst();
|
||||||
return result.numUpdatedRows > 0n;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async delete(id: string, accountId: string): Promise<boolean> {
|
async delete(id: string, accountId: string): Promise<boolean> {
|
||||||
|
|||||||
@@ -1,66 +1,159 @@
|
|||||||
import { Activity, type ActivityVerifications, type ActivityVideoUrls } from "@blade-and-brawn/domain";
|
import { Activity, type ActivityVerifications, type ActivityMediaKeys } from "@blade-and-brawn/domain";
|
||||||
import type { Static } from "@sinclair/typebox";
|
import type { Static } from "@sinclair/typebox";
|
||||||
import { t } from "elysia";
|
import { t } from "elysia";
|
||||||
|
import type { Selectable } from "kysely";
|
||||||
import { db } from "../database/db";
|
import { db } from "../database/db";
|
||||||
|
import type { DB } from "../database/out/db";
|
||||||
|
|
||||||
export const VerificationStatusSchema = t.Union([
|
export const VerificationStatusSchema = t.Union([
|
||||||
t.Literal("request"),
|
t.Literal("draft"),
|
||||||
|
t.Literal("submitted"),
|
||||||
t.Literal("in_review"),
|
t.Literal("in_review"),
|
||||||
t.Literal("action_requested"),
|
t.Literal("action_requested"),
|
||||||
t.Literal("completed"),
|
t.Literal("completed"),
|
||||||
]);
|
]);
|
||||||
export type VerificationStatus = Static<typeof VerificationStatusSchema>;
|
export type VerificationStatus = Static<typeof VerificationStatusSchema>;
|
||||||
|
|
||||||
export class VerificationsService {
|
const MEDIA_KEY_COLUMN = {
|
||||||
async request(assessmentId: string, accountId: string, activityVideoUrls: ActivityVideoUrls) {
|
[Activity.BackSquat]: "media_key_back_squat",
|
||||||
// Only the owning account may request verification of their own assessment.
|
[Activity.Deadlift]: "media_key_deadlift",
|
||||||
const assessment = await db.selectFrom("assessments")
|
[Activity.BenchPress]: "media_key_bench_press",
|
||||||
.select("id")
|
[Activity.BroadJump]: "media_key_broad_jump",
|
||||||
.where("id", "=", assessmentId)
|
[Activity.Run]: "media_key_run",
|
||||||
.where("account_id", "=", accountId)
|
[Activity.ConeDrill]: "media_key_cone_drill",
|
||||||
.executeTakeFirst();
|
} as const satisfies Record<Activity, keyof DB["verifications"]>;
|
||||||
if (!assessment) return undefined;
|
|
||||||
|
|
||||||
|
const ALLOWED_FROM = {
|
||||||
|
update: ["draft", "action_requested"],
|
||||||
|
submit: ["draft"],
|
||||||
|
requestAction: ["submitted", "in_review"],
|
||||||
|
complete: ["submitted", "in_review"],
|
||||||
|
} satisfies Record<string, VerificationStatus[]>;
|
||||||
|
|
||||||
|
export class VerificationsService {
|
||||||
|
static readonly REQUIRED_MEDIA_ACTIVITIES = Object.values(Activity);
|
||||||
|
static readonly ALLOWED_MEDIA_RE = /^(video\/(mp4|quicktime|webm)|image\/(png|jpeg))$/;
|
||||||
|
|
||||||
|
static missingActivityMediaKeys(verification: Pick<Selectable<DB["verifications"]>, (typeof MEDIA_KEY_COLUMN)[Activity]>) {
|
||||||
|
return VerificationsService.REQUIRED_MEDIA_ACTIVITIES.filter((activity) => !verification[MEDIA_KEY_COLUMN[activity]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(assessmentId: string, activityMediaKeys?: ActivityMediaKeys) {
|
||||||
return await db.insertInto("verifications")
|
return await db.insertInto("verifications")
|
||||||
.values({
|
.values({
|
||||||
assessment_id: assessmentId,
|
assessment_id: assessmentId,
|
||||||
status: "request" satisfies VerificationStatus,
|
status: "draft" satisfies VerificationStatus,
|
||||||
media_key_back_squat: activityVideoUrls[Activity.BackSquat] ?? null,
|
media_key_back_squat: activityMediaKeys?.[Activity.BackSquat] ?? null,
|
||||||
media_key_deadlift: activityVideoUrls[Activity.Deadlift] ?? null,
|
media_key_deadlift: activityMediaKeys?.[Activity.Deadlift] ?? null,
|
||||||
media_key_bench_press: activityVideoUrls[Activity.BenchPress] ?? null,
|
media_key_bench_press: activityMediaKeys?.[Activity.BenchPress] ?? null,
|
||||||
media_key_broad_jump: activityVideoUrls[Activity.BroadJump] ?? null,
|
media_key_broad_jump: activityMediaKeys?.[Activity.BroadJump] ?? null,
|
||||||
media_key_run: activityVideoUrls[Activity.Run] ?? null,
|
media_key_run: activityMediaKeys?.[Activity.Run] ?? null,
|
||||||
media_key_cone_drill: activityVideoUrls[Activity.ConeDrill] ?? null,
|
media_key_cone_drill: activityMediaKeys?.[Activity.ConeDrill] ?? null,
|
||||||
})
|
})
|
||||||
.onConflict((oc) => oc
|
.onConflict((oc) => oc.column("assessment_id").doNothing())
|
||||||
.column("assessment_id")
|
.returning(["id", "status"])
|
||||||
.doUpdateSet((eb) => ({
|
.executeTakeFirst();
|
||||||
status: "request" satisfies VerificationStatus,
|
}
|
||||||
media_key_back_squat: eb.ref("excluded.media_key_back_squat"),
|
|
||||||
media_key_deadlift: eb.ref("excluded.media_key_deadlift"),
|
async update(id: string, { assessmentId, activityMediaKeys = {} }: { assessmentId?: string, activityMediaKeys?: ActivityMediaKeys }) {
|
||||||
media_key_bench_press: eb.ref("excluded.media_key_bench_press"),
|
const replaced = (activity: Activity) => activityMediaKeys[activity] ? null : undefined;
|
||||||
media_key_broad_jump: eb.ref("excluded.media_key_broad_jump"),
|
|
||||||
media_key_run: eb.ref("excluded.media_key_run"),
|
return await db.updateTable("verifications")
|
||||||
media_key_cone_drill: eb.ref("excluded.media_key_cone_drill"),
|
.where("id", "=", id)
|
||||||
// Re-requesting means new videos are under review, so the
|
.where("status", "in", ALLOWED_FROM.update)
|
||||||
// previous cycle's per-activity judgments and completion
|
.set({
|
||||||
// info no longer apply.
|
status: "draft" satisfies VerificationStatus,
|
||||||
verf_back_squat: null,
|
submitted_at: null,
|
||||||
verf_deadlift: null,
|
assessment_id: assessmentId,
|
||||||
verf_bench_press: null,
|
media_key_back_squat: activityMediaKeys[Activity.BackSquat],
|
||||||
verf_broad_jump: null,
|
media_key_deadlift: activityMediaKeys[Activity.Deadlift],
|
||||||
verf_run: null,
|
media_key_bench_press: activityMediaKeys[Activity.BenchPress],
|
||||||
verf_cone_drill: null,
|
media_key_broad_jump: activityMediaKeys[Activity.BroadJump],
|
||||||
completed_at: null,
|
media_key_run: activityMediaKeys[Activity.Run],
|
||||||
completed_by: null,
|
media_key_cone_drill: activityMediaKeys[Activity.ConeDrill],
|
||||||
}))
|
verf_back_squat: replaced(Activity.BackSquat),
|
||||||
)
|
verf_deadlift: replaced(Activity.Deadlift),
|
||||||
.returning("id")
|
verf_bench_press: replaced(Activity.BenchPress),
|
||||||
.executeTakeFirstOrThrow();
|
verf_broad_jump: replaced(Activity.BroadJump),
|
||||||
|
verf_run: replaced(Activity.Run),
|
||||||
|
verf_cone_drill: replaced(Activity.ConeDrill),
|
||||||
|
})
|
||||||
|
.returning(["id", "status"])
|
||||||
|
.executeTakeFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
async get(id: string, accountId?: string) {
|
||||||
|
return await VerificationsService.baseQuery()
|
||||||
|
.where("verifications.id", "=", id)
|
||||||
|
.$if(accountId !== undefined, (qb) => qb.where("assessments.account_id", "=", accountId!))
|
||||||
|
.executeTakeFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
async list(opt: {
|
||||||
|
filter?: { status?: VerificationStatus },
|
||||||
|
limit?: number,
|
||||||
|
offset?: number,
|
||||||
|
} = {}) {
|
||||||
|
return await VerificationsService.baseQuery()
|
||||||
|
.$if(opt.filter?.status !== undefined, (qb) => qb
|
||||||
|
.where("verifications.status", "=", opt.filter!.status!)
|
||||||
|
)
|
||||||
|
.orderBy("verifications.submitted_at", (ob) => ob.desc().nullsLast())
|
||||||
|
.orderBy("verifications.created_at", "desc")
|
||||||
|
.$if(opt.limit !== undefined, (qb) => qb.limit(opt.limit!))
|
||||||
|
.$if(opt.offset !== undefined, (qb) => qb.offset(opt.offset!))
|
||||||
|
.execute();
|
||||||
|
}
|
||||||
|
|
||||||
|
async submit(id: string) {
|
||||||
|
return await db.updateTable("verifications")
|
||||||
|
.where("id", "=", id)
|
||||||
|
.where("status", "in", ALLOWED_FROM.submit)
|
||||||
|
.where((eb) => eb.and(
|
||||||
|
VerificationsService.REQUIRED_MEDIA_ACTIVITIES.map((activity) => eb(MEDIA_KEY_COLUMN[activity], "is not", null))
|
||||||
|
))
|
||||||
|
.set({ status: "submitted" satisfies VerificationStatus, submitted_at: new Date() })
|
||||||
|
.returning(["id", "status"])
|
||||||
|
.executeTakeFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
async requestAction(id: string, reviewerNotes: string | null, activityVerifications: ActivityVerifications) {
|
||||||
|
return await db.updateTable("verifications")
|
||||||
|
.where("id", "=", id)
|
||||||
|
.where("status", "in", ALLOWED_FROM.requestAction)
|
||||||
|
.set({
|
||||||
|
status: "action_requested" satisfies VerificationStatus,
|
||||||
|
reviewer_notes: reviewerNotes,
|
||||||
|
verf_back_squat: activityVerifications[Activity.BackSquat] ?? null,
|
||||||
|
verf_deadlift: activityVerifications[Activity.Deadlift] ?? null,
|
||||||
|
verf_bench_press: activityVerifications[Activity.BenchPress] ?? null,
|
||||||
|
verf_broad_jump: activityVerifications[Activity.BroadJump] ?? null,
|
||||||
|
verf_run: activityVerifications[Activity.Run] ?? null,
|
||||||
|
verf_cone_drill: activityVerifications[Activity.ConeDrill] ?? null,
|
||||||
|
})
|
||||||
|
.returning(["id", "status"])
|
||||||
|
.executeTakeFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
async complete(id: string, completedBy: string, activityVerifications: ActivityVerifications) {
|
||||||
|
return await db.updateTable("verifications")
|
||||||
|
.where("id", "=", id)
|
||||||
|
.where("status", "in", ALLOWED_FROM.complete)
|
||||||
|
.set({
|
||||||
|
status: "completed" satisfies VerificationStatus,
|
||||||
|
completed_at: new Date(),
|
||||||
|
completed_by: completedBy,
|
||||||
|
verf_back_squat: activityVerifications[Activity.BackSquat] ?? null,
|
||||||
|
verf_deadlift: activityVerifications[Activity.Deadlift] ?? null,
|
||||||
|
verf_bench_press: activityVerifications[Activity.BenchPress] ?? null,
|
||||||
|
verf_broad_jump: activityVerifications[Activity.BroadJump] ?? null,
|
||||||
|
verf_run: activityVerifications[Activity.Run] ?? null,
|
||||||
|
verf_cone_drill: activityVerifications[Activity.ConeDrill] ?? null,
|
||||||
|
})
|
||||||
|
.returning(["id", "status"])
|
||||||
|
.executeTakeFirst();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Joined with the assessment being verified, since reviewing a request
|
|
||||||
// requires seeing the player's claimed performance alongside the videos.
|
|
||||||
private static baseQuery() {
|
private static baseQuery() {
|
||||||
return db.selectFrom("verifications")
|
return db.selectFrom("verifications")
|
||||||
.innerJoin("assessments", "assessments.id", "verifications.assessment_id")
|
.innerJoin("assessments", "assessments.id", "verifications.assessment_id")
|
||||||
@@ -69,6 +162,7 @@ export class VerificationsService {
|
|||||||
"verifications.assessment_id",
|
"verifications.assessment_id",
|
||||||
"verifications.status",
|
"verifications.status",
|
||||||
"verifications.created_at",
|
"verifications.created_at",
|
||||||
|
"verifications.submitted_at",
|
||||||
"verifications.completed_at",
|
"verifications.completed_at",
|
||||||
"verifications.completed_by",
|
"verifications.completed_by",
|
||||||
"verifications.reviewer_notes",
|
"verifications.reviewer_notes",
|
||||||
@@ -96,60 +190,4 @@ export class VerificationsService {
|
|||||||
"assessments.perf_cone_drill",
|
"assessments.perf_cone_drill",
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
async get(id: string) {
|
|
||||||
return await VerificationsService.baseQuery()
|
|
||||||
.where("verifications.id", "=", id)
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async list(opt: {
|
|
||||||
filter?: { status?: VerificationStatus },
|
|
||||||
limit?: number,
|
|
||||||
offset?: number,
|
|
||||||
} = {}) {
|
|
||||||
return await VerificationsService.baseQuery()
|
|
||||||
.$if(opt.filter?.status !== undefined, (qb) => qb
|
|
||||||
.where("verifications.status", "=", opt.filter!.status!)
|
|
||||||
)
|
|
||||||
.orderBy("verifications.created_at", "desc")
|
|
||||||
.$if(opt.limit !== undefined, (qb) => qb.limit(opt.limit!))
|
|
||||||
.$if(opt.offset !== undefined, (qb) => qb.offset(opt.offset!))
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async requestAction(id: string, reviewerNotes: string | null, activityVerifications: ActivityVerifications) {
|
|
||||||
const result = await db.updateTable("verifications")
|
|
||||||
.where("id", "=", id)
|
|
||||||
.set({
|
|
||||||
status: "action_requested" satisfies VerificationStatus,
|
|
||||||
reviewer_notes: reviewerNotes,
|
|
||||||
verf_back_squat: activityVerifications[Activity.BackSquat] ?? null,
|
|
||||||
verf_deadlift: activityVerifications[Activity.Deadlift] ?? null,
|
|
||||||
verf_bench_press: activityVerifications[Activity.BenchPress] ?? null,
|
|
||||||
verf_broad_jump: activityVerifications[Activity.BroadJump] ?? null,
|
|
||||||
verf_run: activityVerifications[Activity.Run] ?? null,
|
|
||||||
verf_cone_drill: activityVerifications[Activity.ConeDrill] ?? null,
|
|
||||||
})
|
|
||||||
.executeTakeFirst();
|
|
||||||
return result.numUpdatedRows > 0n;
|
|
||||||
}
|
|
||||||
|
|
||||||
async complete(id: string, completedBy: string, activityVerifications: ActivityVerifications) {
|
|
||||||
const result = await db.updateTable("verifications")
|
|
||||||
.where("id", "=", id)
|
|
||||||
.set({
|
|
||||||
status: "completed" satisfies VerificationStatus,
|
|
||||||
completed_at: new Date(),
|
|
||||||
completed_by: completedBy,
|
|
||||||
verf_back_squat: activityVerifications[Activity.BackSquat] ?? null,
|
|
||||||
verf_deadlift: activityVerifications[Activity.Deadlift] ?? null,
|
|
||||||
verf_bench_press: activityVerifications[Activity.BenchPress] ?? null,
|
|
||||||
verf_broad_jump: activityVerifications[Activity.BroadJump] ?? null,
|
|
||||||
verf_run: activityVerifications[Activity.Run] ?? null,
|
|
||||||
verf_cone_drill: activityVerifications[Activity.ConeDrill] ?? null,
|
|
||||||
})
|
|
||||||
.executeTakeFirst();
|
|
||||||
return result.numUpdatedRows > 0n;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import cluster from 'node:cluster';
|
|||||||
import { createHash } from 'node:crypto';
|
import { createHash } from 'node:crypto';
|
||||||
import { pino } from 'pino';
|
import { pino } from 'pino';
|
||||||
import os from 'node:os'
|
import os from 'node:os'
|
||||||
|
import { t } from 'elysia';
|
||||||
|
|
||||||
export const log = pino({
|
export const log = pino({
|
||||||
level: Bun.env.LOG_LEVEL ?? "info",
|
level: Bun.env.LOG_LEVEL ?? "info",
|
||||||
@@ -31,12 +32,19 @@ export const env = {
|
|||||||
BOT_CLIENT_SECRET: requireEnv("BOT_CLIENT_SECRET"),
|
BOT_CLIENT_SECRET: requireEnv("BOT_CLIENT_SECRET"),
|
||||||
BOT_REDIRECT_URL: requireEnv("BOT_REDIRECT_URL"),
|
BOT_REDIRECT_URL: requireEnv("BOT_REDIRECT_URL"),
|
||||||
BOT_LOGIN_REDIRECT_URL: requireEnv("BOT_LOGIN_REDIRECT_URL"),
|
BOT_LOGIN_REDIRECT_URL: requireEnv("BOT_LOGIN_REDIRECT_URL"),
|
||||||
|
CLOUDFLARE_TOKEN: requireEnv("CLOUDFLARE_TOKEN"),
|
||||||
|
R2_ACCESS_KEY_ID: requireEnv("R2_ACCESS_KEY_ID"),
|
||||||
|
R2_SECRET_ACCESS_KEY: requireEnv("R2_SECRET_ACCESS_KEY"),
|
||||||
|
R2_URL: requireEnv("R2_URL")
|
||||||
};
|
};
|
||||||
|
|
||||||
export const WORKER_COUNT = Math.min(os.availableParallelism(), +env.MAX_WORKER_COUNT);
|
export const WORKER_COUNT = Math.min(os.availableParallelism(), +env.MAX_WORKER_COUNT);
|
||||||
export const DEFAULT_NAME = "Default";
|
export const DEFAULT_NAME = "Default";
|
||||||
export const DUMMY_PASSWORD_HASH = await Bun.password.hash("Dummy");
|
export const DUMMY_PASSWORD_HASH = await Bun.password.hash("Dummy");
|
||||||
|
|
||||||
|
export const BigIntIdSchema = t.String({ pattern: "^\\d+$" });
|
||||||
|
export const AccountIdSchema = t.String({ pattern: "^(@.+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$" });
|
||||||
|
|
||||||
function requireEnv(key: string): string {
|
function requireEnv(key: string): string {
|
||||||
const val = Bun.env[key];
|
const val = Bun.env[key];
|
||||||
if (!val) {
|
if (!val) {
|
||||||
|
|||||||
@@ -11,7 +11,8 @@
|
|||||||
const LIMIT = 25;
|
const LIMIT = 25;
|
||||||
|
|
||||||
const STATUS_BADGE: Record<VerificationStatus, string> = {
|
const STATUS_BADGE: Record<VerificationStatus, string> = {
|
||||||
request: "badge-info",
|
draft: "badge-ghost",
|
||||||
|
submitted: "badge-info",
|
||||||
in_review: "badge-warning",
|
in_review: "badge-warning",
|
||||||
action_requested: "badge-error",
|
action_requested: "badge-error",
|
||||||
completed: "badge-success",
|
completed: "badge-success",
|
||||||
@@ -47,7 +48,7 @@
|
|||||||
let loading = $state(true);
|
let loading = $state(true);
|
||||||
let loadError = $state<string | null>(null);
|
let loadError = $state<string | null>(null);
|
||||||
let offset = $state(0);
|
let offset = $state(0);
|
||||||
let status = $state<VerificationStatus | "">("request");
|
let status = $state<VerificationStatus | "">("submitted");
|
||||||
|
|
||||||
async function refresh() {
|
async function refresh() {
|
||||||
loading = true;
|
loading = true;
|
||||||
@@ -91,7 +92,8 @@
|
|||||||
onchange={(e) => setStatus(e.currentTarget.value)}
|
onchange={(e) => setStatus(e.currentTarget.value)}
|
||||||
>
|
>
|
||||||
<option value="">All statuses</option>
|
<option value="">All statuses</option>
|
||||||
<option value="request">Request</option>
|
<option value="draft">Draft</option>
|
||||||
|
<option value="submitted">Submitted</option>
|
||||||
<option value="action_requested">Action requested</option>
|
<option value="action_requested">Action requested</option>
|
||||||
<option value="completed">Completed</option>
|
<option value="completed">Completed</option>
|
||||||
</select>
|
</select>
|
||||||
@@ -135,7 +137,7 @@
|
|||||||
<th>Player</th>
|
<th>Player</th>
|
||||||
<th>Status</th>
|
<th>Status</th>
|
||||||
<th>Videos</th>
|
<th>Videos</th>
|
||||||
<th>Requested</th>
|
<th>Submitted</th>
|
||||||
<th></th>
|
<th></th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -149,7 +151,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td>{videoCount(row)} / {Object.values(Activity).length}</td>
|
<td>{videoCount(row)} / {Object.values(Activity).length}</td>
|
||||||
<td class="whitespace-nowrap">{formatDate(row.created_at)}</td>
|
<td class="whitespace-nowrap">{formatDate(row.submitted_at)}</td>
|
||||||
<td>
|
<td>
|
||||||
<a
|
<a
|
||||||
class="btn btn-primary btn-xs"
|
class="btn btn-primary btn-xs"
|
||||||
|
|||||||
@@ -19,7 +19,8 @@
|
|||||||
const ACTIVITIES = Object.values(Activity);
|
const ACTIVITIES = Object.values(Activity);
|
||||||
|
|
||||||
const STATUS_BADGE: Record<VerificationStatus, string> = {
|
const STATUS_BADGE: Record<VerificationStatus, string> = {
|
||||||
request: "badge-info",
|
draft: "badge-ghost",
|
||||||
|
submitted: "badge-info",
|
||||||
in_review: "badge-warning",
|
in_review: "badge-warning",
|
||||||
action_requested: "badge-error",
|
action_requested: "badge-error",
|
||||||
completed: "badge-success",
|
completed: "badge-success",
|
||||||
@@ -126,8 +127,8 @@
|
|||||||
);
|
);
|
||||||
const allReviewed = $derived(reviewedCount === ACTIVITIES.length);
|
const allReviewed = $derived(reviewedCount === ACTIVITIES.length);
|
||||||
const isReadOnly = $derived(
|
const isReadOnly = $derived(
|
||||||
verification?.status === "completed" ||
|
verification?.status !== "submitted" &&
|
||||||
verification?.status === "action_requested",
|
verification?.status !== "in_review",
|
||||||
);
|
);
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
@@ -432,6 +433,8 @@
|
|||||||
<span class="text-sm opacity-70">
|
<span class="text-sm opacity-70">
|
||||||
{v.status === "completed"
|
{v.status === "completed"
|
||||||
? "This verification is completed and read-only."
|
? "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."}
|
: "This verification is waiting on the player to resubmit and is read-only."}
|
||||||
</span>
|
</span>
|
||||||
{:else}
|
{:else}
|
||||||
|
|||||||
@@ -43,8 +43,8 @@ export const ActivityPerformanceSchema = t.Object({
|
|||||||
});
|
});
|
||||||
export type ActivityPerformance = Static<typeof ActivityPerformanceSchema>;
|
export type ActivityPerformance = Static<typeof ActivityPerformanceSchema>;
|
||||||
|
|
||||||
export const ActivityVideosSchema = t.Partial(t.Record(t.Enum(Activity), t.String()));
|
export const ActivityMediaKeysSchema = t.Partial(t.Record(t.Enum(Activity), t.String({ minLength: 1 })));
|
||||||
export type ActivityVideoUrls = Static<typeof ActivityVideosSchema>;
|
export type ActivityMediaKeys = Static<typeof ActivityMediaKeysSchema>;
|
||||||
|
|
||||||
export const ActivityVerificationsSchema = t.Partial(t.Record(t.Enum(Activity), t.Boolean()));
|
export const ActivityVerificationsSchema = t.Partial(t.Record(t.Enum(Activity), t.Boolean()));
|
||||||
export type ActivityVerifications = Static<typeof ActivityVerificationsSchema>;
|
export type ActivityVerifications = Static<typeof ActivityVerificationsSchema>;
|
||||||
|
|||||||
Reference in New Issue
Block a user