From faaf9bcc70dd6d92ab08a5c864609f49cbc8d082 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Boduro=C4=9Flu?= <80620802+burakboduroglu@users.noreply.github.com> Date: Tue, 4 Aug 2026 14:23:06 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=8E=93=20grade=20blueprints,=20pu?= =?UTF-8?q?blic=20profiles,=20badges,=20and=20board=20group=20invites=20-?= =?UTF-8?q?=20cover=20the=20four=20surfaces=20the=20backend=20opened=20in?= =?UTF-8?q?=20b15ef98..6ddc914,=20one=20API=20=20=20file=20per=20endpoint?= =?UTF-8?q?=20with=20the=20domain's=20mandatory=20vitest=20cases=20-=20gra?= =?UTF-8?q?de=20blueprints:=20a=20manager-only=20tab=20on=20/management/cl?= =?UTF-8?q?asses=20plus=20an=20=20=20"apply=20blueprint"=20action=20on=20a?= =?UTF-8?q?=20class.=20The=20grade=20label=20is=20the=20record=20key=20=20?= =?UTF-8?q?=20and=20is=20free=20text,=20so=20it=20is=20percent-encoded=20e?= =?UTF-8?q?verywhere=20-=20a=20blueprint's=20skipped[]=20is=20an=20outcome?= =?UTF-8?q?=20report,=20not=20an=20error:=20the=20save=20=20=20still=20toa?= =?UTF-8?q?sts=20and=20the=20shortfall=20opens=20a=20separate=20table.=20B?= =?UTF-8?q?ackend=20English=20=20=20reasons=20are=20normalized=20and=20loc?= =?UTF-8?q?alized=20in=20lib/blueprint-skip,=20never=20=20=20rendered=20ra?= =?UTF-8?q?w,=20and=20a=20409=20re-reads=20the=20blueprint=20and=20reseeds?= =?UTF-8?q?=20the=20form=20=20=20since=20there=20is=20no=20version=20token?= =?UTF-8?q?=20to=20retry=20with=20-=20public=20profiles=20at=20/profile/me?= =?UTF-8?q?=20and=20/profile/$userId,=20with=20bio=20and=20=20=20display?= =?UTF-8?q?=20name=20on=20the=20existing=20PATCH=20/users/me.=20The=20pare?= =?UTF-8?q?nt=20restriction=20is=20=20=20left=20to=20the=20backend's=20403?= =?UTF-8?q?=20=E2=80=94=20a=20parent=20may=20read=20their=20linked=20stude?= =?UTF-8?q?nts,=20so=20=20=20a=20client=20role=20gate=20would=20wrongly=20?= =?UTF-8?q?close=20that=20-=20avatars=20ride=20a=20plain=20=20against?= =?UTF-8?q?=20the=20same-origin=20/api=20path=20rather=20than=20=20=20fetc?= =?UTF-8?q?h+objectURL;=20a=20shared=20revision=20counter=20busts=20the=20?= =?UTF-8?q?browser's=20image=20=20=20cache=20after=20an=20upload=20or=20de?= =?UTF-8?q?lete=20and=20refreshes=20the=20sidebar=20chip=20-=20badges=20re?= =?UTF-8?q?nder=20from=20the=20/limits=20catalogue:=20unearned=20tiles=20c?= =?UTF-8?q?arry=20a=20padlock=20=20=20and=20a=20progress=20bar,=20and=20a?= =?UTF-8?q?=20tooltip=20repeats=20what=20the=20tile=20already=20shows,=20?= =?UTF-8?q?=20=20since=20a=20tooltip=20can=20never=20be=20opened=20by=20to?= =?UTF-8?q?uch=20-=20boards=20gain=20POST=20/boards/{id}/invite=20behind?= =?UTF-8?q?=20a=20source=20picker=20in=20the=20=20=20settings=20panel,=20c?= =?UTF-8?q?reator-only,=20keyed=20per=20source=20kind=20so=20a=20non-creat?= =?UTF-8?q?or=20=20=20never=20fires=20the=20list=20requests=20-=20profile?= =?UTF-8?q?=20links=20added=20where=20people=20are=20listed:=20the=20user?= =?UTF-8?q?=20table=20and=20detail,=20=20=20class=20members,=20linked=20st?= =?UTF-8?q?udents,=20and=20a=20parent's=20own=20children.=20A=20router=20?= =?UTF-8?q?=20=20=20inside=20a=20modal=20panel=20never=20navigates,?= =?UTF-8?q?=20so=20those=20close=20the=20panel=20=20=20first=20and=20then?= =?UTF-8?q?=20navigate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/__tests__/boards/boards.test.ts | 26 + src/api/__tests__/classes/classes.test.ts | 57 ++ src/api/__tests__/users/users.test.ts | 61 +- src/api/boards/index.ts | 1 + src/api/boards/postBoardInvite.ts | 12 + src/api/boards/types.ts | 7 + .../classes/deleteClassBlueprintByGrade.ts | 7 + src/api/classes/getClassBlueprintByGrade.ts | 8 + src/api/classes/getClassBlueprints.ts | 11 + src/api/classes/index.ts | 6 + src/api/classes/patchClassBlueprintByGrade.ts | 19 + src/api/classes/postClassBlueprint.ts | 11 + src/api/classes/postClassBlueprintApply.ts | 10 + src/api/client/types.ts | 102 ++ src/api/users/deleteMyAvatar.ts | 5 + src/api/users/deleteUserAvatar.ts | 6 + src/api/users/getMyProfile.ts | 6 + src/api/users/getUserAvatarUrl.ts | 9 + src/api/users/getUserProfile.ts | 8 + src/api/users/index.ts | 6 + src/api/users/postMyAvatar.ts | 10 + src/components/classes/blueprint-panel.tsx | 179 ++++ .../classes/blueprint-skipped-report.tsx | 52 ++ src/components/classes/blueprints-tab.tsx | 199 ++++ src/components/ui/tooltip.tsx | 31 + src/components/users/avatar-upload.tsx | 130 +++ src/components/users/badge-grid.test.tsx | 67 ++ src/components/users/badge-grid.tsx | 220 +++++ .../users/parent-students-panel.tsx | 85 +- src/components/users/profile-form.tsx | 54 +- src/components/users/profile-memberships.tsx | 146 +++ src/components/users/user-avatar.tsx | 62 ++ src/components/users/user-table.tsx | 11 +- .../whiteboard/board-bulk-invite.tsx | 157 ++++ .../whiteboard/board-settings-panel.tsx | 65 +- src/i18n/messages.ts | 880 +++++++++++++++--- src/lib/avatar.ts | 27 + src/lib/badges.test.ts | 80 ++ src/lib/badges.ts | 76 ++ src/lib/blueprint-skip.test.ts | 33 + src/lib/blueprint-skip.ts | 50 + src/pages/admin-user-detail-page.tsx | 17 +- src/pages/admin-users-page.tsx | 2 +- src/pages/class-detail-page.tsx | 64 +- src/pages/classes-page.tsx | 62 +- src/pages/my-students-page.tsx | 25 +- src/pages/profile-page.tsx | 220 +++++ src/pages/whiteboard-page.tsx | 59 +- src/routes/router.tsx | 17 + 49 files changed, 3245 insertions(+), 213 deletions(-) create mode 100644 src/api/boards/postBoardInvite.ts create mode 100644 src/api/classes/deleteClassBlueprintByGrade.ts create mode 100644 src/api/classes/getClassBlueprintByGrade.ts create mode 100644 src/api/classes/getClassBlueprints.ts create mode 100644 src/api/classes/patchClassBlueprintByGrade.ts create mode 100644 src/api/classes/postClassBlueprint.ts create mode 100644 src/api/classes/postClassBlueprintApply.ts create mode 100644 src/api/users/deleteMyAvatar.ts create mode 100644 src/api/users/deleteUserAvatar.ts create mode 100644 src/api/users/getMyProfile.ts create mode 100644 src/api/users/getUserAvatarUrl.ts create mode 100644 src/api/users/getUserProfile.ts create mode 100644 src/api/users/postMyAvatar.ts create mode 100644 src/components/classes/blueprint-panel.tsx create mode 100644 src/components/classes/blueprint-skipped-report.tsx create mode 100644 src/components/classes/blueprints-tab.tsx create mode 100644 src/components/ui/tooltip.tsx create mode 100644 src/components/users/avatar-upload.tsx create mode 100644 src/components/users/badge-grid.test.tsx create mode 100644 src/components/users/badge-grid.tsx create mode 100644 src/components/users/profile-memberships.tsx create mode 100644 src/components/users/user-avatar.tsx create mode 100644 src/components/whiteboard/board-bulk-invite.tsx create mode 100644 src/lib/avatar.ts create mode 100644 src/lib/badges.test.ts create mode 100644 src/lib/badges.ts create mode 100644 src/lib/blueprint-skip.test.ts create mode 100644 src/lib/blueprint-skip.ts create mode 100644 src/pages/profile-page.tsx diff --git a/src/api/__tests__/boards/boards.test.ts b/src/api/__tests__/boards/boards.test.ts index 4bd7edc..9f6f570 100644 --- a/src/api/__tests__/boards/boards.test.ts +++ b/src/api/__tests__/boards/boards.test.ts @@ -10,6 +10,7 @@ import { postBoard, postBoardClear, postBoardClose, + postBoardInvite, } from "../../boards"; import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; @@ -121,4 +122,29 @@ describe("boards API", () => { expect(url).toBe("/api/boards/b1"); expect(init?.method).toBe("DELETE"); }); + + it("postBoardInvite POSTs a class invite to /boards/:id/invite", async () => { + mockFetchSuccess({ id: "b1", participants: ["u1", "u2"] }); + const body = { kind: "class", class: "cl1" } as const; + await postBoardInvite("b1", body); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/boards/b1/invite"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("postBoardInvite POSTs a course invite", async () => { + mockFetchSuccess({ id: "b1", participants: [] }); + const body = { kind: "course", course: "co1" } as const; + await postBoardInvite("b1", body); + expect(lastFetchCall()[1]?.body).toBe(JSON.stringify(body)); + }); + + it("postBoardInvite POSTs an event invite", async () => { + mockFetchSuccess({ id: "b1", participants: [] }); + const body = { kind: "event", event: "e1" } as const; + await postBoardInvite("b1", body); + expect(lastFetchCall()[1]?.body).toBe(JSON.stringify(body)); + }); }); diff --git a/src/api/__tests__/classes/classes.test.ts b/src/api/__tests__/classes/classes.test.ts index cb8e993..7a790fe 100644 --- a/src/api/__tests__/classes/classes.test.ts +++ b/src/api/__tests__/classes/classes.test.ts @@ -13,6 +13,12 @@ import { postClassCourse, getClassCourses, deleteClassCourse, + postClassBlueprint, + getClassBlueprints, + getClassBlueprintByGrade, + patchClassBlueprintByGrade, + deleteClassBlueprintByGrade, + postClassBlueprintApply, } from "../../classes"; import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; @@ -128,4 +134,55 @@ describe("classes API", () => { expect(url).toBe("/api/classes/c1/courses/co1"); expect(init?.method).toBe("DELETE"); }); + + it("postClassBlueprint POSTs /classes/blueprints with the body", async () => { + mockFetchSuccess({ blueprint: { grade: "9", courses: [], creator: {} }, skipped: [] }); + const body = { grade: "9", course_ids: ["co1", "co2"] }; + await postClassBlueprint(body); + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/classes/blueprints"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("getClassBlueprints GETs /classes/blueprints with pagination", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getClassBlueprints({ limit: 20, offset: 40 }); + const [url] = lastFetchCall(); + expect(url).toBe("/api/classes/blueprints?limit=20&offset=40"); + }); + + it("getClassBlueprintByGrade encodes the grade, which is the record key", async () => { + mockFetchSuccess({ grade: "9/A", courses: [], creator: {} }); + await getClassBlueprintByGrade("9/A"); + const [url] = lastFetchCall(); + expect(url).toBe("/api/classes/blueprints/9%2FA"); + }); + + it("patchClassBlueprintByGrade PATCHes the whole course set", async () => { + mockFetchSuccess({ blueprint: { grade: "9", courses: [], creator: {} }, skipped: [] }); + const body = { course_ids: ["co1"] }; + await patchClassBlueprintByGrade("9", body); + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/classes/blueprints/9"); + expect(init?.method).toBe("PATCH"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("deleteClassBlueprintByGrade DELETEs /classes/blueprints/:grade", async () => { + mockFetch204(); + await deleteClassBlueprintByGrade("9/A"); + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/classes/blueprints/9%2FA"); + expect(init?.method).toBe("DELETE"); + }); + + it("postClassBlueprintApply POSTs /classes/:id/blueprint with no body", async () => { + mockFetchSuccess({ skipped: [] }); + await postClassBlueprintApply("c1"); + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/classes/c1/blueprint"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBeUndefined(); + }); }); diff --git a/src/api/__tests__/users/users.test.ts b/src/api/__tests__/users/users.test.ts index d7b9c38..a847091 100644 --- a/src/api/__tests__/users/users.test.ts +++ b/src/api/__tests__/users/users.test.ts @@ -8,7 +8,13 @@ import { patchUserProfile } from "../../users"; import { patchUserRole } from "../../users"; import { patchMyPreferences } from "../../users"; import { patchUserPreferences } from "../../users"; -import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch"; +import { getMyProfile } from "../../users"; +import { getUserProfile } from "../../users"; +import { postMyAvatar } from "../../users"; +import { deleteMyAvatar } from "../../users"; +import { deleteUserAvatar } from "../../users"; +import { getUserAvatarUrl } from "../../users"; +import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; describe("users API", () => { afterEach(() => { @@ -155,4 +161,57 @@ describe("users API", () => { expect(init?.method).toBe("PATCH"); expect(init?.body).toBe(JSON.stringify(updates)); }); + + it("getMyProfile calls /users/me/profile", async () => { + const profile = { id: "u1", username: "test", badges: [] }; + mockFetchSuccess(profile); + + const result = await getMyProfile(); + expect(result).toEqual(profile); + const [url] = lastFetchCall(); + expect(url).toBe("/api/users/me/profile"); + }); + + it("getUserProfile calls /users/:id/profile", async () => { + mockFetchSuccess({ id: "u2", username: "other", badges: [] }); + await getUserProfile("u2"); + const [url] = lastFetchCall(); + expect(url).toBe("/api/users/u2/profile"); + }); + + it("postMyAvatar POSTs the file as multipart under the `file` field", async () => { + mockFetchSuccess({ content_type: "image/png", size: 1024 }, 201); + + const file = new File(["x"], "me.png", { type: "image/png" }); + const result = await postMyAvatar(file); + expect(result).toEqual({ content_type: "image/png", size: 1024 }); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/users/me/avatar"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBeInstanceOf(FormData); + expect((init?.body as FormData).get("file")).toBe(file); + }); + + it("deleteMyAvatar calls DELETE /users/me/avatar", async () => { + mockFetch204(); + await deleteMyAvatar(); + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/users/me/avatar"); + expect(init?.method).toBe("DELETE"); + }); + + it("deleteUserAvatar calls DELETE /users/:id/avatar", async () => { + mockFetch204(); + await deleteUserAvatar("u2"); + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/users/u2/avatar"); + expect(init?.method).toBe("DELETE"); + }); + + it("getUserAvatarUrl builds a same-origin URL, with the cache-buster only when versioned", () => { + expect(getUserAvatarUrl("u1")).toBe("/api/users/u1/avatar"); + expect(getUserAvatarUrl("u1", 3)).toBe("/api/users/u1/avatar?v=3"); + expect(getUserAvatarUrl("u/1")).toBe("/api/users/u%2F1/avatar"); + }); }); diff --git a/src/api/boards/index.ts b/src/api/boards/index.ts index ae3c659..f1d3991 100644 --- a/src/api/boards/index.ts +++ b/src/api/boards/index.ts @@ -6,6 +6,7 @@ export * from "./getBoardStrokes"; export * from "./getBoardHistory"; export * from "./getBoardEpochs"; export * from "./patchBoardById"; +export * from "./postBoardInvite"; export * from "./postBoardClear"; export * from "./postBoardClose"; export * from "./deleteBoardById"; diff --git a/src/api/boards/postBoardInvite.ts b/src/api/boards/postBoardInvite.ts new file mode 100644 index 0000000..9558b1f --- /dev/null +++ b/src/api/boards/postBoardInvite.ts @@ -0,0 +1,12 @@ +import { client } from "../client"; +import type { Board, BoardInviteBody } from "./types"; + +// Adds every member of a class, course/club or event to the roster in one +// pass. Creator only. Additive and idempotent — it never removes anyone, and +// members already on the board are skipped. Parents and ids that no longer +// resolve are dropped silently, but going over max_participants refuses the +// whole invite with a 409 and adds nobody. A named id that does not exist is a +// 400, not a 404 — a 404 here would mean the board itself. +export function postBoardInvite(id: string, body: BoardInviteBody): Promise { + return client(`/boards/${encodeURIComponent(id)}/invite`, { method: "POST", body }); +} diff --git a/src/api/boards/types.ts b/src/api/boards/types.ts index 2cc5f08..010b8be 100644 --- a/src/api/boards/types.ts +++ b/src/api/boards/types.ts @@ -45,5 +45,12 @@ export type UpdateBoardBody = { locked?: boolean; }; +// POST /boards/{id}/invite, tagged by `kind` — send exactly one id key. +// A club is just a course whose kind is "club", so it rides the "course" arm. +export type BoardInviteBody = + | { kind: "class"; class: string } + | { kind: "course"; course: string } + | { kind: "event"; event: string }; + // GET /boards/{id}/history: `epoch` narrows to one epoch; omit for whole life. export type BoardHistoryParams = PageParams & { epoch?: number }; diff --git a/src/api/classes/deleteClassBlueprintByGrade.ts b/src/api/classes/deleteClassBlueprintByGrade.ts new file mode 100644 index 0000000..3f7f3b2 --- /dev/null +++ b/src/api/classes/deleteClassBlueprintByGrade.ts @@ -0,0 +1,7 @@ +import { client } from "../client"; + +// Detaches every course this blueprint attached, across every class at the +// grade, then drops the template. Hand-attached courses stay. +export function deleteClassBlueprintByGrade(grade: string): Promise { + return client(`/classes/blueprints/${encodeURIComponent(grade)}`, { method: "DELETE" }); +} diff --git a/src/api/classes/getClassBlueprintByGrade.ts b/src/api/classes/getClassBlueprintByGrade.ts new file mode 100644 index 0000000..f86444c --- /dev/null +++ b/src/api/classes/getClassBlueprintByGrade.ts @@ -0,0 +1,8 @@ +import { client } from "../client"; +import type { ClassBlueprint } from "../client"; + +// The grade label is the record key and is free text, so it must be encoded — +// a grade like "9/A" would otherwise read as a second path segment. +export function getClassBlueprintByGrade(grade: string, signal?: AbortSignal): Promise { + return client(`/classes/blueprints/${encodeURIComponent(grade)}`, { signal }); +} diff --git a/src/api/classes/getClassBlueprints.ts b/src/api/classes/getClassBlueprints.ts new file mode 100644 index 0000000..2f6e09c --- /dev/null +++ b/src/api/classes/getClassBlueprints.ts @@ -0,0 +1,11 @@ +import { client } from "../client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { ClassBlueprint } from "../client"; + +export async function getClassBlueprints( + params?: PageParams, + signal?: AbortSignal, +): Promise> { + const data = await client(`/classes/blueprints${pageQuery(params)}`, { signal }); + return normalizePage(data); +} diff --git a/src/api/classes/index.ts b/src/api/classes/index.ts index 0027331..6ed4cf3 100644 --- a/src/api/classes/index.ts +++ b/src/api/classes/index.ts @@ -11,3 +11,9 @@ export * from "./deleteClassMember"; export * from "./postClassCourse"; export * from "./getClassCourses"; export * from "./deleteClassCourse"; +export * from "./postClassBlueprint"; +export * from "./getClassBlueprints"; +export * from "./getClassBlueprintByGrade"; +export * from "./patchClassBlueprintByGrade"; +export * from "./deleteClassBlueprintByGrade"; +export * from "./postClassBlueprintApply"; diff --git a/src/api/classes/patchClassBlueprintByGrade.ts b/src/api/classes/patchClassBlueprintByGrade.ts new file mode 100644 index 0000000..af17af0 --- /dev/null +++ b/src/api/classes/patchClassBlueprintByGrade.ts @@ -0,0 +1,19 @@ +import { client } from "../client"; +import type { BlueprintResult } from "../client"; + +// `course_ids` is the whole set, not a delta: a course dropped from it is +// detached from every class at this grade that the blueprint attached it to. +// Hand-attached courses are never touched. +export type UpdateBlueprintBody = { course_ids: string[] }; + +// A 409 means the blueprint changed since it was read — there is no version to +// echo back, so re-read it and let the user resubmit from the fresh list. +export function patchClassBlueprintByGrade( + grade: string, + body: UpdateBlueprintBody, +): Promise { + return client(`/classes/blueprints/${encodeURIComponent(grade)}`, { + method: "PATCH", + body, + }); +} diff --git a/src/api/classes/postClassBlueprint.ts b/src/api/classes/postClassBlueprint.ts new file mode 100644 index 0000000..f9114a1 --- /dev/null +++ b/src/api/classes/postClassBlueprint.ts @@ -0,0 +1,11 @@ +import { client } from "../client"; +import type { BlueprintResult } from "../client"; + +export type CreateBlueprintBody = { grade: string; course_ids: string[] }; + +// Manager+. Creates the blueprint and immediately applies it to every existing +// class at that grade; pairs that could not land come back in `skipped`. +// A grade that already holds a blueprint is a 409. +export function postClassBlueprint(body: CreateBlueprintBody): Promise { + return client("/classes/blueprints", { method: "POST", body }); +} diff --git a/src/api/classes/postClassBlueprintApply.ts b/src/api/classes/postClassBlueprintApply.ts new file mode 100644 index 0000000..34b337e --- /dev/null +++ b/src/api/classes/postClassBlueprintApply.ts @@ -0,0 +1,10 @@ +import { client } from "../client"; +import type { BlueprintApplyResult } from "../client"; + +// Applies this class's grade blueprint to this one class. A 404 means either +// the class is gone or no blueprint covers its grade. +export function postClassBlueprintApply(classId: string): Promise { + return client(`/classes/${encodeURIComponent(classId)}/blueprint`, { + method: "POST", + }); +} diff --git a/src/api/client/types.ts b/src/api/client/types.ts index 1fcd60f..dd550d2 100644 --- a/src/api/client/types.ts +++ b/src/api/client/types.ts @@ -26,12 +26,16 @@ export type User = { palette_color: string | null; }; +// PATCH /users/me and PATCH /users/{id}/profile take the same body: an omitted +// (or null) field is left alone, an empty string clears it. export type ProfileUpdate = { name?: string | null; surname?: string | null; email?: string | null; phone?: string | null; birth_date?: string | null; + display_name?: string | null; + bio?: string | null; }; export type PersonRef = { @@ -40,6 +44,61 @@ export type PersonRef = { display_name: string | null; }; +// The lifetime counter a badge reads. Badges sharing a stat form a ladder. +export type BadgeStat = + | "homework_submitted" + | "homework_on_time" + | "exam_sat" + | "pomodoro_finished" + | "pomodoro_focus_ms"; + +// One entry of the badge catalogue, served by GET /limits. The label and icon +// behind an id live in the client, exactly as they do for a role. +export type BadgeCatalogEntry = { id: string; stat: BadgeStat | string; threshold: number }; + +// A badge a person has earned. Awards are permanent and `earned_at` is the +// moment of first crossing, unix ms. +export type EarnedBadge = { id: string; earned_at: number }; + +export type AvatarMeta = { content_type: string; size: number }; + +export type ProfileClassRef = { id: string; name: string; grade: string | null }; + +export type ProfileCourseRef = { id: string; title: string; kind: CourseKind }; + +// Lifetime counters behind the badge ladders, plus the two live totals the +// capped `classes`/`courses` lists would otherwise hide. +export type ProfileStats = { + pomodoro_sessions: number; + pomodoro_focus_ms: number; + courses: number; + classes: number; + homework_submitted_total: number; + homework_on_time_total: number; + exam_sat_total: number; + pomodoro_finished_total: number; + pomodoro_focus_ms_total: number; +}; + +// A person's public profile. Readable by any authenticated account except a +// parent, who only reaches their own and their linked students'. Never carries +// email, phone or birth date at any role — those stay on GET /users/{id}. +export type Profile = { + id: string; + username: string; + display_name: string | null; + role: Role; + bio: string | null; + avatar: AvatarMeta | null; + // Capped at limits.user.max_profile_classes; stats.classes holds the true total. + classes: ProfileClassRef[]; + // Capped at limits.user.max_profile_courses, and filtered to what the reader + // may see; stats.courses holds the owner's true, unfiltered total. + courses: ProfileCourseRef[]; + badges: EarnedBadge[]; + stats: ProfileStats; +}; + export type Note = { id: string; title: string; @@ -195,6 +254,29 @@ export type ClassCourse = { attached_by: PersonRef; }; +// A grade blueprint: the set of courses every class at one grade takes. The +// grade label is the record's key, so there is at most one per grade. Creating +// or editing one applies it to every existing class at that grade right away. +export type ClassBlueprint = { + grade: string; + courses: string[]; + creator: PersonRef; +}; + +// One (class, course) pair a blueprint could not attach. Applying is +// best-effort: a pair that cannot land is reported here and the rest still go +// through. `reason` is backend English — localize it, never render it raw. +export type BlueprintSkip = { + class: string; + class_name: string; + course: string; + reason: string; +}; + +export type BlueprintResult = { blueprint: ClassBlueprint; skipped: BlueprintSkip[] }; + +export type BlueprintApplyResult = { skipped: BlueprintSkip[] }; + export type CourseSession = { id: string; course: string; @@ -499,6 +581,12 @@ export type Limits = { min_password_len: number; max_password_len: number; max_name_len: number; + max_display_name_len: number; + max_bio_len: number; + // Caps on what a profile read embeds, not on membership: the full lists + // stay at /courses/me and /classes/me. + max_profile_courses: number; + max_profile_classes: number; max_email_len: number; min_phone_digits: number; max_phone_digits: number; @@ -507,6 +595,7 @@ export type Limits = { languages: UserLanguage[]; session_duration_days: number; }; + badges: { catalog: BadgeCatalogEntry[] }; note: { max_title_len: number; max_content_len: number; max_files: number }; file: { max_name_len: number; @@ -601,6 +690,19 @@ export type Limits = { max_max_threads: number; default_max_threads: number; }; + board: { + max_title_len: number; + // People the creator may name onto one board. Every participant draws, so + // this also bounds a room's writer count. + max_participants: number; + max_stroke_payload_len: number; + max_epoch_strokes: number; + max_board_strokes: number; + max_boards_per_creator: number; + stroke_kinds: string[]; + ws_tick_secs: number; + ws_max_board_id_len: number; + }; settings: { max_list_len: number; max_item_len: number; diff --git a/src/api/users/deleteMyAvatar.ts b/src/api/users/deleteMyAvatar.ts new file mode 100644 index 0000000..ec4a2a8 --- /dev/null +++ b/src/api/users/deleteMyAvatar.ts @@ -0,0 +1,5 @@ +import { client } from "../client"; + +export function deleteMyAvatar(): Promise { + return client("/users/me/avatar", { method: "DELETE" }); +} diff --git a/src/api/users/deleteUserAvatar.ts b/src/api/users/deleteUserAvatar.ts new file mode 100644 index 0000000..b655781 --- /dev/null +++ b/src/api/users/deleteUserAvatar.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; + +// Admin-only moderation delete of someone else's avatar. +export function deleteUserAvatar(id: string): Promise { + return client(`/users/${encodeURIComponent(id)}/avatar`, { method: "DELETE" }); +} diff --git a/src/api/users/getMyProfile.ts b/src/api/users/getMyProfile.ts new file mode 100644 index 0000000..45283b3 --- /dev/null +++ b/src/api/users/getMyProfile.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; +import type { Profile } from "../client"; + +export function getMyProfile(signal?: AbortSignal): Promise { + return client("/users/me/profile", { signal }); +} diff --git a/src/api/users/getUserAvatarUrl.ts b/src/api/users/getUserAvatarUrl.ts new file mode 100644 index 0000000..5a80a9c --- /dev/null +++ b/src/api/users/getUserAvatarUrl.ts @@ -0,0 +1,9 @@ +// The avatar endpoint answers with raw image bytes, so it is read through a +// plain , not fetch: /api is same-origin, which carries the session +// cookie on its own. `version` is a cache-buster the caller bumps after an +// upload or delete — the URL is otherwise identical before and after, and the +// browser's in-memory image cache would keep serving the old bytes. +export function getUserAvatarUrl(userId: string, version?: number): string { + const bust = version ? `?v=${version}` : ""; + return `/api/users/${encodeURIComponent(userId)}/avatar${bust}`; +} diff --git a/src/api/users/getUserProfile.ts b/src/api/users/getUserProfile.ts new file mode 100644 index 0000000..693044c --- /dev/null +++ b/src/api/users/getUserProfile.ts @@ -0,0 +1,8 @@ +import { client } from "../client"; +import type { Profile } from "../client"; + +// Any authenticated account may read any profile, except a parent, who reaches +// only their own and their linked students' (403 otherwise). +export function getUserProfile(id: string, signal?: AbortSignal): Promise { + return client(`/users/${encodeURIComponent(id)}/profile`, { signal }); +} diff --git a/src/api/users/index.ts b/src/api/users/index.ts index 9e40afe..ac8f0c4 100644 --- a/src/api/users/index.ts +++ b/src/api/users/index.ts @@ -7,3 +7,9 @@ export * from "./patchUserProfile"; export * from "./patchUserRole"; export * from "./patchMyPreferences"; export * from "./patchUserPreferences"; +export * from "./getMyProfile"; +export * from "./getUserProfile"; +export * from "./postMyAvatar"; +export * from "./deleteMyAvatar"; +export * from "./deleteUserAvatar"; +export * from "./getUserAvatarUrl"; diff --git a/src/api/users/postMyAvatar.ts b/src/api/users/postMyAvatar.ts new file mode 100644 index 0000000..b8130c6 --- /dev/null +++ b/src/api/users/postMyAvatar.ts @@ -0,0 +1,10 @@ +import { formClient } from "../client"; +import type { AvatarMeta } from "../client"; + +// PNG, JPEG, WebP or GIF only — no SVG — under the school's max_file_bytes. +// Uploading over an existing avatar replaces it. +export function postMyAvatar(file: File, signal?: AbortSignal): Promise { + const body = new FormData(); + body.append("file", file); + return formClient("/users/me/avatar", body, signal); +} diff --git a/src/components/classes/blueprint-panel.tsx b/src/components/classes/blueprint-panel.tsx new file mode 100644 index 0000000..4511985 --- /dev/null +++ b/src/components/classes/blueprint-panel.tsx @@ -0,0 +1,179 @@ +import { For, Show, createEffect, createMemo, createSignal } from "solid-js"; +import { + getClassBlueprintByGrade, + patchClassBlueprintByGrade, + postClassBlueprint, +} from "@/api/classes"; +import { ApiError, formatApiError, type BlueprintResult, type ClassBlueprint, type Course } from "@/api/client"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { SidePanel } from "@/components/ui/side-panel"; +import { courseKindLabel } from "@/lib/course-kind"; +import { useT } from "@/stores/preferences-context"; + +export function BlueprintPanel(props: { + open: boolean; + onOpenChange: (open: boolean) => void; + /** null creates a new blueprint; set edits that grade's course set. */ + blueprint: ClassBlueprint | null; + courses: Course[]; + maxCourses: number; + maxGradeLen: number; + onSaved: (result: BlueprintResult) => void; +}) { + const t = useT(); + const [grade, setGrade] = createSignal(""); + const [selected, setSelected] = createSignal([]); + const [filter, setFilter] = createSignal(""); + const [error, setError] = createSignal(""); + const [warning, setWarning] = createSignal(""); + const [pending, setPending] = createSignal(false); + + const editing = () => props.blueprint !== null; + + // The panel instance is reused between "edit grade 9" and "edit grade 10", + // and props are not read at construction time in Solid — seeding these at + // the top of the component would freeze the first blueprint's course set. + createEffect(() => { + if (!props.open) return; + const bp = props.blueprint; + setGrade(bp?.grade ?? ""); + setSelected(bp?.courses ? [...bp.courses] : []); + setFilter(""); + setError(""); + setWarning(""); + }); + + const visibleCourses = createMemo(() => { + const q = filter().trim().toLocaleLowerCase("tr-TR"); + if (!q) return props.courses; + return props.courses.filter((c) => c.title.toLocaleLowerCase("tr-TR").includes(q)); + }); + + const isSelected = (id: string) => selected().includes(id); + const atCeiling = () => selected().length >= props.maxCourses; + + const toggle = (id: string) => { + setSelected((prev) => (prev.includes(id) ? prev.filter((c) => c !== id) : [...prev, id])); + }; + + // A losing race has no version token to retry with, so re-read the blueprint, + // reseed the checkboxes from the server's list, and let the user resubmit. + const reseedFromServer = async (g: string) => { + try { + const fresh = await getClassBlueprintByGrade(g); + setSelected([...fresh.courses]); + setWarning(t("classBlueprints.staleReload")); + setError(""); + } catch (err) { + setError(formatApiError(err)); + } + }; + + const submit = async (e: Event) => { + e.preventDefault(); + const g = grade().trim(); + if (!g) return; + setError(""); + setWarning(""); + setPending(true); + try { + const result = editing() + ? await patchClassBlueprintByGrade(g, { course_ids: selected() }) + : await postClassBlueprint({ grade: g, course_ids: selected() }); + props.onSaved(result); + } catch (err) { + if (err instanceof ApiError && err.status === 409) { + if (editing()) { + await reseedFromServer(g); + } else { + setError(t("classBlueprints.conflictExists")); + } + } else { + setError(formatApiError(err)); + } + } finally { + setPending(false); + } + }; + + return ( + +
+ + {warning()} + + +
+ + setGrade(e.currentTarget.value)} + /> +

{t("classBlueprints.gradeHint")}

+
+ +
+
+ + + {t("classBlueprints.selected", { count: selected().length, max: props.maxCourses })} + +
+

{t("classBlueprints.wholeSetHint")}

+ setFilter(e.currentTarget.value)} + /> +
+ 0} + fallback={

{t("classBlueprints.noCourseMatch")}

} + > + + {(course) => ( + + )} + +
+
+
+ + +

{error()}

+
+ +
+ +
+
+
+ ); +} diff --git a/src/components/classes/blueprint-skipped-report.tsx b/src/components/classes/blueprint-skipped-report.tsx new file mode 100644 index 0000000..7e76b6f --- /dev/null +++ b/src/components/classes/blueprint-skipped-report.tsx @@ -0,0 +1,52 @@ +import { createMemo } from "solid-js"; +import type { ColumnDef } from "@tanstack/solid-table"; +import type { BlueprintSkip } from "@/api/client"; +import { DataTable } from "@/components/ui/data-table"; +import { SidePanel } from "@/components/ui/side-panel"; +import { skipReasonCopy } from "@/lib/blueprint-skip"; +import { useT } from "@/stores/preferences-context"; + +export function BlueprintSkippedReport(props: { + open: boolean; + onOpenChange: (open: boolean) => void; + skipped: BlueprintSkip[]; + /** Resolves a course id to its title; falls back to the id when unknown. */ + courseTitle: (id: string) => string; +}) { + const t = useT(); + + const columns = createMemo[]>(() => [ + { + id: "class", + accessorFn: (row) => row.class_name || row.class, + header: t("classBlueprints.skippedClass"), + meta: { cellClass: "font-medium" }, + }, + { + id: "course", + accessorFn: (row) => props.courseTitle(row.course), + header: t("classBlueprints.skippedCourse"), + }, + { + id: "reason", + accessorFn: (row) => { + const copy = skipReasonCopy(row.reason, props.courseTitle(row.course)); + return t(copy.key, copy.vars); + }, + header: t("classBlueprints.skippedReason"), + meta: { cellClass: "text-muted-foreground" }, + }, + ]); + + return ( + + + + ); +} diff --git a/src/components/classes/blueprints-tab.tsx b/src/components/classes/blueprints-tab.tsx new file mode 100644 index 0000000..1b19d55 --- /dev/null +++ b/src/components/classes/blueprints-tab.tsx @@ -0,0 +1,199 @@ +import { Show, createMemo, createResource, createSignal } from "solid-js"; +import type { ColumnDef } from "@tanstack/solid-table"; +import { deleteClassBlueprintByGrade, getClassBlueprints } from "@/api/classes"; +import { getCourses } from "@/api/courses"; +import { getLimits } from "@/api/limits"; +import { formatApiError, type BlueprintSkip, type ClassBlueprint } from "@/api/client"; +import { BlueprintPanel } from "@/components/classes/blueprint-panel"; +import { BlueprintSkippedReport } from "@/components/classes/blueprint-skipped-report"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; +import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; +import { IconEdit, IconPlus, IconTrash } from "@/components/ui/icons"; +import { TableRowActions } from "@/components/ui/table-row-actions"; +import { createFlash } from "@/lib/flash"; +import { personLabel } from "@/lib/person"; +import { useT } from "@/stores/preferences-context"; + +export function BlueprintsTab(props: { + /** Every blueprint route is manager+; below that the tab is not rendered. */ + canManage: () => boolean; + /** Tabs keep both panels mounted, so the list is only fetched once opened. */ + active: () => boolean; +}) { + const t = useT(); + const [error, setError] = createSignal(""); + const [flash, setFlash] = createFlash(); + const [panelOpen, setPanelOpen] = createSignal(false); + const [editing, setEditing] = createSignal(null); + const [deleting, setDeleting] = createSignal(null); + const [skipped, setSkipped] = createSignal([]); + const [reportOpen, setReportOpen] = createSignal(false); + + const enabled = () => (props.active() && props.canManage() ? true : null); + const [list, { refetch }] = createResource(enabled, async () => + (await getClassBlueprints({ limit: 200 })).items, + ); + const [courses] = createResource(enabled, async () => (await getCourses({ limit: 200 })).items); + const [limits] = createResource(enabled, () => getLimits()); + + const courseTitle = (id: string) => courses.latest?.find((c) => c.id === id)?.title ?? id; + + const columns = createMemo[]>(() => [ + { + id: "grade", + accessorFn: (row) => row.grade, + header: t("classBlueprints.grade"), + meta: { cellClass: "font-medium" }, + }, + { + id: "count", + accessorFn: (row) => t("classBlueprints.courseCount", { count: row.courses.length }), + header: t("classBlueprints.courseCountColumn"), + }, + { + id: "titles", + accessorFn: (row) => { + const names = row.courses.slice(0, 3).map(courseTitle); + const rest = row.courses.length - names.length; + return rest > 0 ? `${names.join(", ")} +${rest}` : names.join(", ") || "—"; + }, + header: t("classBlueprints.courses"), + meta: { cellClass: "text-muted-foreground" }, + }, + { + id: "creator", + accessorFn: (row) => personLabel(row.creator), + header: t("common.creator"), + meta: { cellClass: "text-muted-foreground" }, + }, + { + id: "actions", + header: t("common.actions"), + meta: { headerClass: "w-14 text-center", cellClass: "px-1 text-center" }, + cell: (cell) => ( + , + onSelect: () => { + setEditing(cell.row.original); + setPanelOpen(true); + }, + }, + { + label: t("classBlueprints.delete"), + icon: , + destructive: true, + onSelect: () => setDeleting(cell.row.original), + }, + ]} + /> + ), + }, + ]); + + // A saved blueprint is not an error even when some pairs did not attach: the + // template was written either way, so the toast fires and the shortfall is a + // separate, dismissible report. + const handleSaved = async (rows: BlueprintSkip[]) => { + setPanelOpen(false); + setEditing(null); + await refetch(); + setSkipped(rows); + setFlash(t("classBlueprints.saved")); + }; + + const remove = async () => { + const bp = deleting(); + if (!bp) return; + setError(""); + try { + await deleteClassBlueprintByGrade(bp.grade); + setDeleting(null); + await refetch(); + setFlash(t("classBlueprints.deleted")); + } catch (err) { + setError(formatApiError(err)); + } + }; + + return ( +
+ + {flash()} + + + {error()} + + 0}> + + {t("classBlueprints.skippedSummary", { count: skipped().length })} + + + + + {/* The list is read through `.latest`, so a refetch after a save never + re-suspends the tab; the skeleton only covers the first load. */} + }> + { + setEditing(null); + setPanelOpen(true); + }} + > + + {t("classBlueprints.new")} + + } + /> + + + { + setPanelOpen(open); + if (!open) setEditing(null); + }} + blueprint={editing()} + courses={courses.latest ?? []} + maxCourses={limits.latest?.course.max_class_courses ?? 50} + maxGradeLen={limits.latest?.course.max_class_grade_len ?? 20} + onSaved={(result) => void handleSaved(result.skipped)} + /> + + + + !open && setDeleting(null)} + title={t("classBlueprints.delete")} + summary={t("classBlueprints.deleteConfirm", { grade: deleting()?.grade ?? "" })} + variant="destructive" + onConfirm={remove} + /> +
+ ); +} diff --git a/src/components/ui/tooltip.tsx b/src/components/ui/tooltip.tsx new file mode 100644 index 0000000..d7b7a59 --- /dev/null +++ b/src/components/ui/tooltip.tsx @@ -0,0 +1,31 @@ +import { Tooltip as TooltipPrimitive } from "@kobalte/core/tooltip"; +import type { ComponentProps, ValidComponent } from "solid-js"; +import { splitProps } from "solid-js"; +import { cn } from "@/lib/cn"; + +// Kobalte's tooltip opens on hover and on keyboard focus, so a focusable +// trigger reaches keyboard users too. It is deliberately not a touch surface: +// anything a tooltip says must also be readable without it, since a tap can +// never open one. +export const Tooltip = TooltipPrimitive; +export const TooltipTrigger = TooltipPrimitive.Trigger; + +export function TooltipContent( + props: ComponentProps>, +) { + const [local, rest] = splitProps(props as ComponentProps, [ + "class", + ]); + return ( + + + + ); +} diff --git a/src/components/users/avatar-upload.tsx b/src/components/users/avatar-upload.tsx new file mode 100644 index 0000000..ca39009 --- /dev/null +++ b/src/components/users/avatar-upload.tsx @@ -0,0 +1,130 @@ +import { Show, createResource, createSignal } from "solid-js"; +import { formatApiError } from "@/api/client"; +import { getLimits } from "@/api/limits"; +import { deleteMyAvatar, postMyAvatar } from "@/api/users"; +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { IconEdit, IconTrash, IconUploadCloud } from "@/components/ui/icons"; +import { UserAvatar } from "@/components/users/user-avatar"; +import { AVATAR_ACCEPT, AVATAR_CONTENT_TYPES, bumpAvatarRevision, formatBytes } from "@/lib/avatar"; +import { useT } from "@/stores/preferences-context"; + +export function AvatarUpload(props: { + userId: string; + name: string; + hasAvatar: boolean; + /** Re-read the profile so `avatar` reflects what was just written. */ + onChanged: () => void | Promise; +}) { + const t = useT(); + const [limits] = createResource(() => getLimits()); + const [busy, setBusy] = createSignal(false); + const [error, setError] = createSignal(""); + const [removeOpen, setRemoveOpen] = createSignal(false); + let input: HTMLInputElement | undefined; + + const maxBytes = () => limits.latest?.file.default_max_file_bytes ?? 5 * 1024 * 1024; + + const pick = async (file: File) => { + setError(""); + if (!AVATAR_CONTENT_TYPES.includes(file.type)) { + setError(t("avatar.typeInvalid")); + return; + } + if (file.size > maxBytes()) { + setError(t("avatar.tooLarge", { size: formatBytes(maxBytes()) })); + return; + } + setBusy(true); + try { + await postMyAvatar(file); + bumpAvatarRevision(); + await props.onChanged(); + } catch (err) { + setError(formatApiError(err)); + } finally { + setBusy(false); + } + }; + + const remove = async () => { + setError(""); + setBusy(true); + try { + await deleteMyAvatar(); + bumpAvatarRevision(); + await props.onChanged(); + } catch (err) { + setError(formatApiError(err)); + } finally { + setBusy(false); + } + }; + + return ( +
+ {/* The photo controls hang off the avatar itself rather than sitting + beside it as a row of buttons, so the header reads as a person, not + as a form. */} +
+ + + + + + + input?.click()}> + + {props.hasAvatar ? t("avatar.change") : t("avatar.upload")} + + + setRemoveOpen(true)}> + + {t("avatar.remove")} + + +

+ {t("avatar.hint", { size: formatBytes(maxBytes()) })} +

+
+
+
+ + +

{error()}

+
+ + { + const file = e.currentTarget.files?.[0]; + // Clear it before awaiting, so picking the same file twice in a row + // still fires a change event. + e.currentTarget.value = ""; + if (file) void pick(file); + }} + /> + + +
+ ); +} diff --git a/src/components/users/badge-grid.test.tsx b/src/components/users/badge-grid.test.tsx new file mode 100644 index 0000000..3a12359 --- /dev/null +++ b/src/components/users/badge-grid.test.tsx @@ -0,0 +1,67 @@ +import { render, screen } from "@solidjs/testing-library"; +import type { BadgeCatalogEntry, ProfileStats } from "@/api/client"; +import { BadgeGrid } from "@/components/users/badge-grid"; +import { PreferencesProvider } from "@/stores/preferences-context"; + +const catalog: BadgeCatalogEntry[] = [ + { id: "homework_submitted_1", stat: "homework_submitted", threshold: 1 }, + { id: "homework_submitted_10", stat: "homework_submitted", threshold: 10 }, + // An id this build has no copy for — it must render, not crash. + { id: "streak_1000", stat: "streak_days", threshold: 1000 }, +]; + +const stats: ProfileStats = { + pomodoro_sessions: 0, + pomodoro_focus_ms: 0, + courses: 0, + classes: 0, + homework_submitted_total: 7, + homework_on_time_total: 0, + exam_sat_total: 0, + pomodoro_finished_total: 0, + pomodoro_focus_ms_total: 0, +}; + +function renderGrid(earned: { id: string; earned_at: number }[]) { + return render(() => ( + + + + )); +} + +afterEach(() => vi.restoreAllMocks()); + +test("shows the whole catalogue, earned and locked alike", () => { + renderGrid([{ id: "homework_submitted_1", earned_at: 1_700_000_000_000 }]); + expect(screen.getAllByRole("generic", { hidden: true }).length).toBeGreaterThan(0); + // Both the earned and the unearned tier are present — the incomplete grid is + // the point, so an unearned badge is never hidden. + expect(screen.getByText("First Steps")).toBeTruthy(); + expect(screen.getByText("Steady Hand")).toBeTruthy(); +}); + +test("an unearned badge shows its progress inline, an earned one shows its date", () => { + renderGrid([{ id: "homework_submitted_1", earned_at: 1_700_000_000_000 }]); + // The tooltip is hover-only, so the tile itself must carry the numbers: + // 7 of 10 done on the second tier. + expect(screen.getAllByText("7 / 10").length).toBeGreaterThan(0); + expect(screen.getAllByText(/Earned/).length).toBeGreaterThan(0); + // The remaining count rides the accessible name, which is what the tooltip + // repeats — a keyboard or screen-reader user gets it without hovering. + expect(screen.getByLabelText(/Steady Hand — 3 to go/)).toBeTruthy(); +}); + +test("a badge whose stat this build does not know shows no progress bar", () => { + renderGrid([]); + // Falls back to the raw id for the label and to the generic locked line. + expect(screen.getByText("streak_1000")).toBeTruthy(); + expect(screen.getAllByText("Not earned yet").length).toBe(1); +}); + +test("every tile is focusable and labelled, so the tooltip is reachable by keyboard", () => { + renderGrid([]); + const tiles = screen.getAllByLabelText(/—/); + expect(tiles.length).toBe(catalog.length); + for (const tile of tiles) expect(tile.getAttribute("tabindex")).toBe("0"); +}); diff --git a/src/components/users/badge-grid.tsx b/src/components/users/badge-grid.tsx new file mode 100644 index 0000000..5370812 --- /dev/null +++ b/src/components/users/badge-grid.tsx @@ -0,0 +1,220 @@ +import { Collapsible } from "@kobalte/core/collapsible"; +import { For, Match, Show, Switch, createMemo } from "solid-js"; +import type { BadgeCatalogEntry, EarnedBadge, ProfileStats } from "@/api/client"; +import { + IconChevronDown, + IconClipboardCheck, + IconClock, + IconExam, + IconHomework, + IconLock, + IconSparkles, +} from "@/components/ui/icons"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { + badgeDescKey, + badgeNameKey, + badgeProgress, + badgeProgressLabel, + badgeProgressRatio, + badgeRemaining, + badgeThresholdLabel, +} from "@/lib/badges"; +import { cn } from "@/lib/cn"; +import { formatDate } from "@/lib/format"; +import { usePreferences, useT } from "@/stores/preferences-context"; + +function StatIcon(props: { stat: string; class?: string }) { + return ( + }> + + + + + + + + + + + + + + ); +} + +export function BadgeGrid(props: { + /** The whole catalogue, from limits.badges.catalog — unearned entries stay + * visible and locked, so the goal is legible before it is reached. */ + catalog: BadgeCatalogEntry[]; + earned: EarnedBadge[]; + stats: ProfileStats; +}) { + const t = useT(); + const prefs = usePreferences(); + + const earnedAt = createMemo(() => { + const map = new Map(); + for (const b of props.earned) map.set(b.id, b.earned_at); + return map; + }); + + // A badge the backend ships before this build has copy for it must still + // render, so both lookups fall back rather than throwing. + const label = (id: string) => { + const key = badgeNameKey(id); + return key ? t(key) : id; + }; + const description = (id: string) => { + const key = badgeDescKey(id); + return key ? t(key) : ""; + }; + + const earnedCount = createMemo( + () => props.catalog.filter((entry) => earnedAt().has(entry.id)).length, + ); + const overallRatio = () => + props.catalog.length === 0 ? 0 : earnedCount() / props.catalog.length; + + return ( + + + + + + + {t("badges.title")} + {t("badges.subtitle")} + + 0}> + + + + + +
+ 0} + fallback={

{t("badges.none")}

} + > + {/* A horizontal rail rather than a grid: thirteen tiles would otherwise + push the rest of the profile off the first screen. Snap points keep + a card from being cut in half mid-scroll, and the edge fade says + there is more to the right without spending a control on it. */} +
+
+ + {(entry) => { + const at = () => earnedAt().get(entry.id); + const current = () => badgeProgress(entry.stat, props.stats) ?? 0; + const tracked = () => badgeProgress(entry.stat, props.stats) !== null; + const ratio = () => badgeProgressRatio(current(), entry.threshold); + const left = () => badgeRemaining(entry.stat, current(), entry.threshold); + const isHours = entry.stat === "pomodoro_focus_ms"; + + // The tooltip enriches; it never carries the only copy of + // anything, since a touch device can never open one. + const hint = () => + at() + ? t("badges.earnedOn", { date: formatDate(at()!, prefs.locale()) }) + : tracked() + ? t(isHours ? "badges.remainingHours" : "badges.remaining", { count: left() }) + : t("badges.locked"); + + return ( + + + + + {/* A locked badge reads as locked, not as disabled: the + padlock says "not yet", dimming alone says "off". */} + + + + + + + +
+

+ {label(entry.id)} +

+

{description(entry.id)}

+ + {hint()}

+ } + > +
+ + + +

+ {badgeProgressLabel(entry.stat, current())} /{" "} + {badgeThresholdLabel(entry.stat, entry.threshold)} +

+
+
+
+
+ + +

{label(entry.id)}

+ +

{description(entry.id)}

+
+

{hint()}

+
+
+ ); + }} +
+
+
+
+
+
+
+ ); +} diff --git a/src/components/users/parent-students-panel.tsx b/src/components/users/parent-students-panel.tsx index 5d30f9f..2c8041e 100644 --- a/src/components/users/parent-students-panel.tsx +++ b/src/components/users/parent-students-panel.tsx @@ -1,4 +1,5 @@ import { For, Show, Suspense, createResource, createSignal } from "solid-js"; +import { useNavigate } from "@tanstack/solid-router"; import { getParentStudents } from "@/api/parents"; import { postParentStudent } from "@/api/parents"; import { deleteParentStudent } from "@/api/parents"; @@ -6,7 +7,8 @@ import { formatApiError } from "@/api/client"; import type { PersonRef } from "@/api/client"; import { SidePanel } from "@/components/ui/side-panel"; import { Button } from "@/components/ui/button"; -import { IconTrash, IconPlus } from "@/components/ui/icons"; +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; +import { IconChevronRight, IconPlus, IconTrash } from "@/components/ui/icons"; import { personLabel } from "@/lib/person"; import { useT } from "@/stores/preferences-context"; import { UserSearchSelect } from "@/components/users/user-search-select"; @@ -14,14 +16,19 @@ import { createFlash } from "@/lib/flash"; import { Alert } from "@/components/ui/alert"; import { PageSpinner } from "@/components/ui/page-spinner"; +// Admin-facing: the students one parent is the guardian of. This is somebody +// else's list, never the viewer's own children — the parent's own view of the +// same relation lives at /students. export function ParentStudentsPanel(props: { open: boolean; onOpenChange: (open: boolean) => void; parent: PersonRef | null; }) { const t = useT(); + const navigate = useNavigate(); const [error, setError] = createSignal(""); const [flash, setFlash] = createFlash(); + const [removing, setRemoving] = createSignal(null); const [students, { refetch }] = createResource( () => (props.open && props.parent ? props.parent.id : null), @@ -30,6 +37,8 @@ export function ParentStudentsPanel(props: { const [selectedStudentId, setSelectedStudentId] = createSignal(""); + const linkedIds = () => (students.latest ?? []).map((student) => student.id); + const handleAdd = async () => { if (!props.parent || !selectedStudentId()) return; setError(""); @@ -37,19 +46,21 @@ export function ParentStudentsPanel(props: { await postParentStudent(props.parent.id, selectedStudentId()); await refetch(); setSelectedStudentId(""); - setFlash(t("common.saved")); + setFlash(t("parentLink.linked")); } catch (err) { setError(formatApiError(err)); } }; - const handleRemove = async (studentId: string) => { - if (!props.parent) return; + const handleRemove = async () => { + const student = removing(); + if (!props.parent || !student) return; setError(""); try { - await deleteParentStudent(props.parent.id, studentId); + await deleteParentStudent(props.parent.id, student.id); + setRemoving(null); await refetch(); - setFlash(t("common.deleted")); + setFlash(t("parentLink.removed")); } catch (err) { setError(formatApiError(err)); } @@ -65,10 +76,10 @@ export function ParentStudentsPanel(props: { } props.onOpenChange(open); }} - title={t("nav.myStudents")} - description={props.parent ? personLabel(props.parent) : ""} + title={t("parentLink.title")} + description={props.parent ? t("parentLink.subtitle", { name: personLabel(props.parent) }) : ""} > -
+
{flash()} @@ -76,33 +87,59 @@ export function ParentStudentsPanel(props: {
+ {/* A guardian link only ever points at a student, so the picker + must not offer teachers or other parents. */}
}> - 0} fallback={
{t("common.noResults")}
}> + 0} + fallback={
{t("parentLink.empty")}
} + >
{(student) => ( -
-
-
{personLabel(student)}
+
+ {/* A router inside this modal panel never + navigates — the dialog's dismiss handling swallows + the click — so close the panel first, then go. */} +
- +
@@ -114,6 +151,18 @@ export function ParentStudentsPanel(props: {
+ + !open && setRemoving(null)} + title={t("parentLink.remove")} + summary={t("parentLink.removeConfirm", { + student: personLabel(removing()), + parent: personLabel(props.parent), + })} + variant="destructive" + onConfirm={handleRemove} + /> ); } diff --git a/src/components/users/profile-form.tsx b/src/components/users/profile-form.tsx index 9b40aaa..b50d14d 100644 --- a/src/components/users/profile-form.tsx +++ b/src/components/users/profile-form.tsx @@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button"; import { DatePicker } from "@/components/ui/date-picker"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; +import { Textarea } from "@/components/ui/textarea"; import { createFlash } from "@/lib/flash"; import { useT } from "@/stores/preferences-context"; @@ -38,13 +39,28 @@ function isoFromDateInput(value: string): string { return `${year}-${month}-${day}`; } -export function ProfileForm(props: { user: User; onSaved: () => void; onSave?: (body: ProfileUpdate) => Promise }) { +export function ProfileForm(props: { + user: User; + /** + * `display_name` and `bio` ride the same PATCH but do not live on `User` — + * GET /auth/me never returns them, only GET /users/{id}/profile does. Pass + * them where a profile is in hand; omit them and the fields stay hidden + * rather than silently offering to clear values they cannot see. + */ + profile?: { display_name: string | null; bio: string | null }; + maxDisplayNameLen?: number; + maxBioLen?: number; + onSaved: () => void; + onSave?: (body: ProfileUpdate) => Promise; +}) { const t = useT(); const [name, setName] = createSignal(props.user.name ?? ""); const [surname, setSurname] = createSignal(props.user.surname ?? ""); const [email, setEmail] = createSignal(props.user.email ?? ""); const [phone, setPhone] = createSignal(props.user.phone ?? ""); const [birthDate, setBirthDate] = createSignal(dateInputFromIso(props.user.birth_date)); + const [displayName, setDisplayName] = createSignal(props.profile?.display_name ?? ""); + const [bio, setBio] = createSignal(props.profile?.bio ?? ""); const [error, setError] = createSignal(""); const [flash, setFlash] = createFlash(); const [pending, setPending] = createSignal(false); @@ -71,6 +87,13 @@ export function ProfileForm(props: { user: User; onSaved: () => void; onSave?: ( if (e !== (props.user.email ?? "")) b.email = e; if (p !== (props.user.phone ?? "")) b.phone = p; if (d !== (props.user.birth_date ?? "")) b.birth_date = d; + if (props.profile) { + // An empty string clears the field server-side; an omitted key keeps it. + const dn = displayName().trim(); + const bi = bio().trim(); + if (dn !== (props.profile.display_name ?? "")) b.display_name = dn; + if (bi !== (props.profile.bio ?? "")) b.bio = bi; + } return b; }; @@ -108,6 +131,35 @@ export function ProfileForm(props: { user: User; onSaved: () => void; onSave?: ( setSurname(e.currentTarget.value)} />
+ +
+ + setDisplayName(e.currentTarget.value)} + /> +

{t("profile.displayNameHint")}

+
+
+ +