Spaces:
Running

Shoraky commited on
Commit
0ffa20c
·
1 Parent(s): c3bf82d

Harden admin and review workflows

Browse files
Files changed (3) hide show
  1. src/admin.ts +34 -10
  2. src/analysis.ts +6 -4
  3. src/server.ts +101 -6
src/admin.ts CHANGED
@@ -6,7 +6,10 @@ import { requireAdmin } from "./server.js";
6
  import { invalidateSubscriptionCache } from "./subscriptions.js";
7
 
8
  const uuid = z.uuid();
9
- const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
 
 
 
10
  const profileSchema = z.object({
11
  fname: z.string().trim().min(1).max(100), lname: z.string().trim().min(1).max(100),
12
  academy: z.string().trim().max(150).nullable(), role: z.string().trim().max(50).nullable(),
@@ -34,14 +37,16 @@ function ageDate(age?: number | null) {
34
  return birth.toISOString().slice(0, 10);
35
  }
36
 
37
- async function analysisRequest(path: string, userId: string, method: string, isAdmin = true) {
38
  const response = await fetch(`${env.ANALYSIS_API_URL}/api${path}`, {
39
  method,
40
  headers: {
41
  "x-sporalize-proxy-secret": env.ANALYSIS_PROXY_SECRET,
42
  "x-sporalize-user-id": userId,
43
  ...(isAdmin ? { "x-sporalize-admin": "true" } : {}),
 
44
  },
 
45
  });
46
  if (!response.ok) throw new Error(`Analysis storage request failed (${response.status}).`);
47
  return response;
@@ -63,12 +68,14 @@ export function registerAdminRoutes(app: Express) {
63
  const { data, error } = await query;
64
  if (error) throw new Error(`Unable to load user directory: ${error.message}`);
65
  const ids = (data ?? []).map((row) => row.user_id);
66
- const [subs, counts] = ids.length ? await Promise.all([
67
  supabaseAdmin.from("users_subscriptions").select("user_id,subscription_id,startdate,enddate,num_players,num_sessions").in("user_id", ids),
68
  supabaseAdmin.from("sessions").select("user_id").in("user_id", ids),
69
- ]) : [{ data: [], error: null }, { data: [], error: null }];
 
70
  if (subs.error) throw new Error(`Unable to load user plans: ${subs.error.message}`);
71
  if (counts.error) throw new Error(`Unable to load user session counts: ${counts.error.message}`);
 
72
  const planIds = [...new Set((subs.data ?? []).flatMap((row) => row.subscription_id ? [row.subscription_id] : []))];
73
  const { data: plans, error: plansError } = planIds.length
74
  ? await supabaseAdmin.from("subscriptions").select("subscription_id,plan,price,player_limit,session_limit").in("subscription_id", planIds)
@@ -77,7 +84,9 @@ export function registerAdminRoutes(app: Express) {
77
  const planMap = new Map((plans ?? []).map((plan) => [plan.subscription_id, plan]));
78
  const subMap = new Map((subs.data ?? []).map((row) => [row.user_id, row]));
79
  const sessionCounts = new Map<string, number>();
 
80
  for (const row of counts.data ?? []) if (row.user_id) sessionCounts.set(row.user_id, (sessionCounts.get(row.user_id) ?? 0) + 1);
 
81
  return res.json({ users: (data ?? []).map((row) => {
82
  const assignment = String(row.account_role).toLowerCase() === "admin" ? null : subMap.get(row.user_id);
83
  const plan = assignment?.subscription_id ? planMap.get(assignment.subscription_id) : null;
@@ -85,7 +94,11 @@ export function registerAdminRoutes(app: Express) {
85
  id: row.user_id, fname: row.fname, lname: row.lname, name: `${row.fname} ${row.lname}`.trim(),
86
  email: row.email, academy: row.academy, role: row.role, imagePath: row.image_path, accountRole: row.account_role,
87
  subscription: plan ? { id: plan.subscription_id, name: plan.plan, startDate: assignment?.startdate, endDate: assignment?.enddate, playerLimit: plan.player_limit, sessionLimit: plan.session_limit } : null,
88
- usage: { players: assignment?.num_players ?? 0, sessions: assignment?.num_sessions ?? 0, totalSessions: sessionCounts.get(row.user_id) ?? 0 },
 
 
 
 
89
  };
90
  }) });
91
  }));
@@ -176,10 +189,17 @@ export function registerAdminRoutes(app: Express) {
176
  if (!data) return fail(res, 404, "Player owner not found.");
177
  }
178
  const { fname, lname } = playerName(input.data.name);
179
- const { data, error } = await supabaseAdmin.from("players").insert({
180
- user_id: input.data.userId ?? null, fname, lname, bdate: ageDate(input.data.age), height: input.data.heightCm ?? null,
181
- weight: input.data.weightKg ?? null, club: input.data.club || null, position: input.data.position || null, gender: input.data.gender ?? null,
182
- }).select("player_id,user_id,fname,lname,position,club,gender,image_path").single();
 
 
 
 
 
 
 
183
  if (error) throw new Error(`Unable to add player: ${error.message}`);
184
  return res.status(201).json({ player: data });
185
  }));
@@ -293,7 +313,11 @@ export function registerAdminRoutes(app: Express) {
293
  const input = z.object({ startFrame: z.number().int().nonnegative(), endFrame: z.number().int().nonnegative(), type: z.string().trim().min(1).max(50), score: z.number().min(0).max(10).nullable(), notes: z.array(z.string().trim().min(1).max(2000)).max(30) }).strict().safeParse(req.body);
294
  if (!sessionId.success || !actionId.success || !input.success || input.data.endFrame < input.data.startFrame) return fail(res, 400, "Check the action review and frame interval.");
295
  const notes = [...new Set(input.data.notes)];
296
- const remote = await analysisRequest(`/sessions/${sessionId.data}/actions/${actionId.data}`, current.user.id, "PATCH");
 
 
 
 
297
  const remoteResult = await remote.json().catch(() => ({}));
298
  if (!remote.ok) return fail(res, remote.status, (remoteResult as { detail?: string }).detail ?? "Unable to update action data.");
299
  const { data: existing, error: readError } = await supabaseAdmin.from("annotations").select("user_id").eq("action_id", actionId.data).maybeSingle();
 
6
  import { invalidateSubscriptionCache } from "./subscriptions.js";
7
 
8
  const uuid = z.uuid();
9
+ const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => {
10
+ const parsed = new Date(`${value}T00:00:00.000Z`);
11
+ return !Number.isNaN(parsed.valueOf()) && parsed.toISOString().slice(0, 10) === value;
12
+ }, "Enter a valid calendar date.");
13
  const profileSchema = z.object({
14
  fname: z.string().trim().min(1).max(100), lname: z.string().trim().min(1).max(100),
15
  academy: z.string().trim().max(150).nullable(), role: z.string().trim().max(50).nullable(),
 
37
  return birth.toISOString().slice(0, 10);
38
  }
39
 
40
+ async function analysisRequest(path: string, userId: string, method: string, isAdmin = true, body?: unknown) {
41
  const response = await fetch(`${env.ANALYSIS_API_URL}/api${path}`, {
42
  method,
43
  headers: {
44
  "x-sporalize-proxy-secret": env.ANALYSIS_PROXY_SECRET,
45
  "x-sporalize-user-id": userId,
46
  ...(isAdmin ? { "x-sporalize-admin": "true" } : {}),
47
+ ...(body !== undefined ? { "content-type": "application/json" } : {}),
48
  },
49
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
50
  });
51
  if (!response.ok) throw new Error(`Analysis storage request failed (${response.status}).`);
52
  return response;
 
68
  const { data, error } = await query;
69
  if (error) throw new Error(`Unable to load user directory: ${error.message}`);
70
  const ids = (data ?? []).map((row) => row.user_id);
71
+ const [subs, counts, playerCounts] = ids.length ? await Promise.all([
72
  supabaseAdmin.from("users_subscriptions").select("user_id,subscription_id,startdate,enddate,num_players,num_sessions").in("user_id", ids),
73
  supabaseAdmin.from("sessions").select("user_id").in("user_id", ids),
74
+ supabaseAdmin.from("players").select("user_id").in("user_id", ids),
75
+ ]) : [{ data: [], error: null }, { data: [], error: null }, { data: [], error: null }];
76
  if (subs.error) throw new Error(`Unable to load user plans: ${subs.error.message}`);
77
  if (counts.error) throw new Error(`Unable to load user session counts: ${counts.error.message}`);
78
+ if (playerCounts.error) throw new Error(`Unable to load user player counts: ${playerCounts.error.message}`);
79
  const planIds = [...new Set((subs.data ?? []).flatMap((row) => row.subscription_id ? [row.subscription_id] : []))];
80
  const { data: plans, error: plansError } = planIds.length
81
  ? await supabaseAdmin.from("subscriptions").select("subscription_id,plan,price,player_limit,session_limit").in("subscription_id", planIds)
 
84
  const planMap = new Map((plans ?? []).map((plan) => [plan.subscription_id, plan]));
85
  const subMap = new Map((subs.data ?? []).map((row) => [row.user_id, row]));
86
  const sessionCounts = new Map<string, number>();
87
+ const playerCountByUser = new Map<string, number>();
88
  for (const row of counts.data ?? []) if (row.user_id) sessionCounts.set(row.user_id, (sessionCounts.get(row.user_id) ?? 0) + 1);
89
+ for (const row of playerCounts.data ?? []) if (row.user_id) playerCountByUser.set(row.user_id, (playerCountByUser.get(row.user_id) ?? 0) + 1);
90
  return res.json({ users: (data ?? []).map((row) => {
91
  const assignment = String(row.account_role).toLowerCase() === "admin" ? null : subMap.get(row.user_id);
92
  const plan = assignment?.subscription_id ? planMap.get(assignment.subscription_id) : null;
 
94
  id: row.user_id, fname: row.fname, lname: row.lname, name: `${row.fname} ${row.lname}`.trim(),
95
  email: row.email, academy: row.academy, role: row.role, imagePath: row.image_path, accountRole: row.account_role,
96
  subscription: plan ? { id: plan.subscription_id, name: plan.plan, startDate: assignment?.startdate, endDate: assignment?.enddate, playerLimit: plan.player_limit, sessionLimit: plan.session_limit } : null,
97
+ usage: {
98
+ players: String(row.account_role).toLowerCase() === "admin" ? playerCountByUser.get(row.user_id) ?? 0 : assignment?.num_players ?? 0,
99
+ sessions: String(row.account_role).toLowerCase() === "admin" ? sessionCounts.get(row.user_id) ?? 0 : assignment?.num_sessions ?? 0,
100
+ totalSessions: sessionCounts.get(row.user_id) ?? 0,
101
+ },
102
  };
103
  }) });
104
  }));
 
189
  if (!data) return fail(res, 404, "Player owner not found.");
190
  }
191
  const { fname, lname } = playerName(input.data.name);
192
+ const { data, error } = await supabaseAdmin.rpc("admin_create_player", {
193
+ p_user_id: input.data.userId ?? null,
194
+ p_fname: fname,
195
+ p_lname: lname,
196
+ p_bdate: ageDate(input.data.age),
197
+ p_height: input.data.heightCm ?? null,
198
+ p_weight: input.data.weightKg ?? null,
199
+ p_club: input.data.club || null,
200
+ p_position: input.data.position || null,
201
+ p_gender: input.data.gender ?? null,
202
+ });
203
  if (error) throw new Error(`Unable to add player: ${error.message}`);
204
  return res.status(201).json({ player: data });
205
  }));
 
313
  const input = z.object({ startFrame: z.number().int().nonnegative(), endFrame: z.number().int().nonnegative(), type: z.string().trim().min(1).max(50), score: z.number().min(0).max(10).nullable(), notes: z.array(z.string().trim().min(1).max(2000)).max(30) }).strict().safeParse(req.body);
314
  if (!sessionId.success || !actionId.success || !input.success || input.data.endFrame < input.data.startFrame) return fail(res, 400, "Check the action review and frame interval.");
315
  const notes = [...new Set(input.data.notes)];
316
+ const remote = await analysisRequest(`/sessions/${sessionId.data}/actions/${actionId.data}`, current.user.id, "PATCH", true, {
317
+ startFrame: input.data.startFrame,
318
+ endFrame: input.data.endFrame,
319
+ type: input.data.type,
320
+ });
321
  const remoteResult = await remote.json().catch(() => ({}));
322
  if (!remote.ok) return fail(res, remote.status, (remoteResult as { detail?: string }).detail ?? "Unable to update action data.");
323
  const { data: existing, error: readError } = await supabaseAdmin.from("annotations").select("user_id").eq("action_id", actionId.data).maybeSingle();
src/analysis.ts CHANGED
@@ -71,10 +71,12 @@ export function analysisRouter(db: SupabaseClient, secret: string) {
71
  if (playerError) return res.status(503).json({ error: "Unable to verify the selected player." });
72
  if (!player) return res.status(404).json({ error: "Choose a player from your own roster before starting analysis." });
73
  if (isAdmin) {
74
- const { error } = await db.from("sessions").insert({
75
- session_id: input.clientId, user_id: userId, player_id: input.playerId,
76
- name: input.name || `Session ${input.clientId.slice(0, 8)}`,
77
- path: `sessions/${input.clientId}`, status: "pending",
 
 
78
  });
79
  if (error) return res.status(503).json({ error: "Unable to prepare analysis session." });
80
  return res.json({ session_id: input.clientId, player_id: input.playerId });
 
71
  if (playerError) return res.status(503).json({ error: "Unable to verify the selected player." });
72
  if (!player) return res.status(404).json({ error: "Choose a player from your own roster before starting analysis." });
73
  if (isAdmin) {
74
+ const { error } = await db.rpc("admin_create_analysis_session", {
75
+ p_session_id: input.clientId,
76
+ p_user_id: userId,
77
+ p_player_id: input.playerId,
78
+ p_name: input.name || `Session ${input.clientId.slice(0, 8)}`,
79
+ p_path: `sessions/${input.clientId}`,
80
  });
81
  if (error) return res.status(503).json({ error: "Unable to prepare analysis session." });
82
  return res.json({ session_id: input.clientId, player_id: input.playerId });
src/server.ts CHANGED
@@ -235,10 +235,20 @@ app.get("/api/plan-billing", async (req, res, next) => {
235
  };
236
  }
237
  }
 
 
 
 
 
 
 
 
 
 
238
  res.set("Cache-Control", "no-store");
239
  return res.json({
240
  subscription: isAdmin ? null : subscription,
241
- usage: { players: assignment?.num_players ?? 0, sessions: Number(assignment?.num_sessions ?? 0) },
242
  billingHistoryAvailable: false,
243
  isAdmin,
244
  });
@@ -357,6 +367,57 @@ app.put("/api/players/:playerId", async (req, res, next) => {
357
  } catch (error) { next(error); }
358
  });
359
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
  // Roster overview is shared for viewing; player writes and analysis choices
361
  // remain limited to the signed-in player's own roster.
362
  app.get("/api/players-overview", async (req, res, next) => {
@@ -571,12 +632,16 @@ app.get("/api/sessions/:sessionId/reviews", async (req, res, next) => {
571
  if (session.user_id !== current.user.id && !await userIsAdmin(current.user.id) && !await activeSubscriptionFor(current.user.id, { refresh: true })) {
572
  return res.status(403).json({ error: "An active subscription is required to view shared sessions.", code: "subscription_required" });
573
  }
 
 
 
 
574
 
575
  const { data: actions, error: actionsError } = await supabaseAdmin.from("actions")
576
  .select("action_id").eq("session_id", sessionId.data);
577
  if (actionsError) throw new Error(`Unable to load review actions: ${actionsError.message}`);
578
  const actionIds = (actions ?? []).map((action) => action.action_id);
579
- if (!actionIds.length) return res.json({ reviews: {} });
580
 
581
  const [{ data: annotations, error: annotationsError }, { data: notes, error: notesError }] = await Promise.all([
582
  supabaseAdmin.from("annotations").select("action_id,score,user_id").in("action_id", actionIds),
@@ -604,7 +669,7 @@ app.get("/api/sessions/:sessionId/reviews", async (req, res, next) => {
604
  }
605
  }
606
  for (const note of notes ?? []) reviews[note.action_id]?.feedback.push(note.note);
607
- return res.json({ reviews });
608
  } catch (error) { next(error); }
609
  });
610
 
@@ -666,12 +731,16 @@ app.put("/api/sessions/:sessionId/actions/:actionId/review", async (req, res, ne
666
  return res.status(400).json({ error: "Check the action score and feedback points." });
667
  }
668
 
669
- // Active subscribers may review any session they can access, including
670
- // shared sessions owned by another user.
671
  const { data: session, error: sessionError } = await supabaseAdmin.from("sessions")
672
- .select("session_id").eq("session_id", sessionId.data).maybeSingle();
673
  if (sessionError) throw new Error(`Unable to verify review session: ${sessionError.message}`);
674
  if (!session) return res.sendStatus(404);
 
 
 
 
 
 
675
  const { data: action, error: actionError } = await supabaseAdmin.from("actions")
676
  .select("action_id").eq("action_id", actionId.data).eq("session_id", sessionId.data).maybeSingle();
677
  if (actionError) throw new Error(`Unable to verify review action: ${actionError.message}`);
@@ -913,6 +982,27 @@ app.delete("/api/auth/account", async (req, res, next) => {
913
  const { data: imageRow, error: imageReadError } = await supabaseAdmin.from("users")
914
  .select("image_path").eq("user_id", current.user.id).maybeSingle();
915
  if (imageReadError) throw new Error(`Unable to load account image: ${imageReadError.message}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
916
  const { error: authError } = await supabaseAdmin.auth.admin.deleteUser(current.user.id);
917
  if (authError) return res.status(500).json({ error: "Unable to delete your account. Please try again." });
918
  const { error: profileError } = await supabaseAdmin.from("users").delete().eq("user_id", current.user.id);
@@ -923,6 +1013,11 @@ app.delete("/api/auth/account", async (req, res, next) => {
923
  const { error: imageError } = await supabaseAdmin.storage.from("profile-images").remove([imageRow.image_path]);
924
  if (imageError) console.error("Account deleted but image cleanup failed", imageError);
925
  }
 
 
 
 
 
926
  return res.status(204).send();
927
  } catch (error) { next(error); }
928
  });
 
235
  };
236
  }
237
  }
238
+ let usage = { players: Number(assignment?.num_players ?? 0), sessions: Number(assignment?.num_sessions ?? 0) };
239
+ if (isAdmin) {
240
+ const [players, sessions] = await Promise.all([
241
+ supabaseAdmin.from("players").select("player_id", { count: "exact", head: true }).eq("user_id", userId),
242
+ supabaseAdmin.from("sessions").select("session_id", { count: "exact", head: true }).eq("user_id", userId),
243
+ ]);
244
+ if (players.error) throw new Error(`Unable to load administrator player usage: ${players.error.message}`);
245
+ if (sessions.error) throw new Error(`Unable to load administrator session usage: ${sessions.error.message}`);
246
+ usage = { players: players.count ?? 0, sessions: sessions.count ?? 0 };
247
+ }
248
  res.set("Cache-Control", "no-store");
249
  return res.json({
250
  subscription: isAdmin ? null : subscription,
251
+ usage,
252
  billingHistoryAvailable: false,
253
  isAdmin,
254
  });
 
367
  } catch (error) { next(error); }
368
  });
369
 
370
+ app.delete("/api/players/:playerId", async (req, res, next) => {
371
+ try {
372
+ const current = await authenticatedUser(req, res);
373
+ if (!current) return res.status(401).json({ error: "Authentication required." });
374
+ const playerId = z.string().uuid().safeParse(req.params.playerId);
375
+ if (!playerId.success) return res.status(404).json({ error: "Player not found." });
376
+
377
+ const isAdmin = await userIsAdmin(current.user.id);
378
+ let playerQuery = supabaseAdmin.from("players")
379
+ .select("player_id,user_id,image_path").eq("player_id", playerId.data);
380
+ if (!isAdmin) playerQuery = playerQuery.eq("user_id", current.user.id);
381
+ const { data: player, error: playerError } = await playerQuery.maybeSingle();
382
+ if (playerError) throw new Error(`Unable to load player for deletion: ${playerError.message}`);
383
+ if (!player) return res.status(404).json({ error: "Player not found." });
384
+
385
+ let sessionsQuery = supabaseAdmin.from("sessions").select("session_id,user_id")
386
+ .eq("player_id", playerId.data);
387
+ if (!isAdmin) sessionsQuery = sessionsQuery.eq("user_id", current.user.id);
388
+ const { data: sessions, error: sessionsError } = await sessionsQuery;
389
+ if (sessionsError) throw new Error(`Unable to load player sessions: ${sessionsError.message}`);
390
+
391
+ for (const session of sessions ?? []) {
392
+ const response = await fetch(new URL(`/api/sessions/${session.session_id}`, env.ANALYSIS_API_URL), {
393
+ method: "DELETE",
394
+ headers: {
395
+ "x-sporalize-proxy-secret": env.ANALYSIS_PROXY_SECRET,
396
+ "x-sporalize-user-id": current.user.id,
397
+ ...(isAdmin ? { "x-sporalize-admin": "true" } : {}),
398
+ },
399
+ });
400
+ if (!response.ok) {
401
+ const detail = await response.json().catch(() => ({})) as { detail?: string };
402
+ throw new Error(detail.detail || `Unable to delete linked session ${session.session_id}.`);
403
+ }
404
+ }
405
+
406
+ let deleteQuery = supabaseAdmin.from("players").delete().eq("player_id", playerId.data);
407
+ if (!isAdmin) deleteQuery = deleteQuery.eq("user_id", current.user.id);
408
+ const { data: deleted, error: deleteError } = await deleteQuery.select("player_id").maybeSingle();
409
+ if (deleteError) throw new Error(`Unable to delete player: ${deleteError.message}`);
410
+ if (!deleted) return res.status(404).json({ error: "Player not found." });
411
+
412
+ const imagePath = player.image_path;
413
+ if (imagePath?.startsWith(`players/${playerId.data}/`) && /^[0-9a-f-]{36}\.(jpg|png|webp)$/.test(imagePath.slice(`players/${playerId.data}/`.length))) {
414
+ const { error: imageError } = await supabaseAdmin.storage.from("profile-images").remove([imagePath]);
415
+ if (imageError) console.error("Player deleted but profile image cleanup failed", imageError);
416
+ }
417
+ return res.status(204).send();
418
+ } catch (error) { next(error); }
419
+ });
420
+
421
  // Roster overview is shared for viewing; player writes and analysis choices
422
  // remain limited to the signed-in player's own roster.
423
  app.get("/api/players-overview", async (req, res, next) => {
 
632
  if (session.user_id !== current.user.id && !await userIsAdmin(current.user.id) && !await activeSubscriptionFor(current.user.id, { refresh: true })) {
633
  return res.status(403).json({ error: "An active subscription is required to view shared sessions.", code: "subscription_required" });
634
  }
635
+ const ownsSession = session.user_id === current.user.id;
636
+ const isAdmin = await userIsAdmin(current.user.id);
637
+ const canReview = isAdmin || ownsSession && Boolean(await activeSubscriptionFor(current.user.id, { refresh: true }));
638
+ const reviewUnavailableReason = canReview ? null : ownsSession ? "subscription_required" : "owner_required";
639
 
640
  const { data: actions, error: actionsError } = await supabaseAdmin.from("actions")
641
  .select("action_id").eq("session_id", sessionId.data);
642
  if (actionsError) throw new Error(`Unable to load review actions: ${actionsError.message}`);
643
  const actionIds = (actions ?? []).map((action) => action.action_id);
644
+ if (!actionIds.length) return res.json({ reviews: {}, canReview, reviewUnavailableReason });
645
 
646
  const [{ data: annotations, error: annotationsError }, { data: notes, error: notesError }] = await Promise.all([
647
  supabaseAdmin.from("annotations").select("action_id,score,user_id").in("action_id", actionIds),
 
669
  }
670
  }
671
  for (const note of notes ?? []) reviews[note.action_id]?.feedback.push(note.note);
672
+ return res.json({ reviews, canReview, reviewUnavailableReason });
673
  } catch (error) { next(error); }
674
  });
675
 
 
731
  return res.status(400).json({ error: "Check the action score and feedback points." });
732
  }
733
 
 
 
734
  const { data: session, error: sessionError } = await supabaseAdmin.from("sessions")
735
+ .select("session_id,user_id").eq("session_id", sessionId.data).maybeSingle();
736
  if (sessionError) throw new Error(`Unable to verify review session: ${sessionError.message}`);
737
  if (!session) return res.sendStatus(404);
738
+ // An action has one annotation row and one notes collection. Its session
739
+ // owner or an administrator can replace that shared review.
740
+ const isAdmin = await userIsAdmin(current.user.id);
741
+ if (session.user_id !== current.user.id && !isAdmin) {
742
+ return res.status(403).json({ error: "Only the session owner or an administrator can save its action review." });
743
+ }
744
  const { data: action, error: actionError } = await supabaseAdmin.from("actions")
745
  .select("action_id").eq("action_id", actionId.data).eq("session_id", sessionId.data).maybeSingle();
746
  if (actionError) throw new Error(`Unable to verify review action: ${actionError.message}`);
 
982
  const { data: imageRow, error: imageReadError } = await supabaseAdmin.from("users")
983
  .select("image_path").eq("user_id", current.user.id).maybeSingle();
984
  if (imageReadError) throw new Error(`Unable to load account image: ${imageReadError.message}`);
985
+ const { data: sessions, error: sessionsError } = await supabaseAdmin.from("sessions")
986
+ .select("session_id").eq("user_id", current.user.id);
987
+ if (sessionsError) throw new Error(`Unable to load account sessions: ${sessionsError.message}`);
988
+ for (const session of sessions ?? []) {
989
+ const response = await fetch(new URL(`/api/sessions/${session.session_id}`, env.ANALYSIS_API_URL), {
990
+ method: "DELETE",
991
+ headers: {
992
+ "x-sporalize-proxy-secret": env.ANALYSIS_PROXY_SECRET,
993
+ "x-sporalize-user-id": current.user.id,
994
+ },
995
+ });
996
+ if (!response.ok) {
997
+ const detail = await response.json().catch(() => ({})) as { detail?: string; error?: string };
998
+ throw new Error(detail.detail || detail.error || `Unable to delete session ${session.session_id}.`);
999
+ }
1000
+ }
1001
+ const { data: players, error: playersError } = await supabaseAdmin.from("players")
1002
+ .select("player_id,image_path").eq("user_id", current.user.id);
1003
+ if (playersError) throw new Error(`Unable to load account players: ${playersError.message}`);
1004
+ const { error: playerDeleteError } = await supabaseAdmin.from("players").delete().eq("user_id", current.user.id);
1005
+ if (playerDeleteError) throw new Error(`Unable to remove account players: ${playerDeleteError.message}`);
1006
  const { error: authError } = await supabaseAdmin.auth.admin.deleteUser(current.user.id);
1007
  if (authError) return res.status(500).json({ error: "Unable to delete your account. Please try again." });
1008
  const { error: profileError } = await supabaseAdmin.from("users").delete().eq("user_id", current.user.id);
 
1013
  const { error: imageError } = await supabaseAdmin.storage.from("profile-images").remove([imageRow.image_path]);
1014
  if (imageError) console.error("Account deleted but image cleanup failed", imageError);
1015
  }
1016
+ const playerImagePaths = (players ?? []).flatMap((player) => player.image_path?.startsWith(`players/${player.player_id}/`) ? [player.image_path] : []);
1017
+ if (playerImagePaths.length) {
1018
+ const { error: imageError } = await supabaseAdmin.storage.from("profile-images").remove(playerImagePaths);
1019
+ if (imageError) console.error("Account deleted but player image cleanup failed", imageError);
1020
+ }
1021
  return res.status(204).send();
1022
  } catch (error) { next(error); }
1023
  });