diff --git a/README.md b/README.md index 45fe9b4..4a02fdc 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ Open [http://localhost:5173](http://localhost:5173) in your browser. > **Proxy Note**: Vite proxies `/api/*` and WebSocket connections to `BACKEND_ORIGIN`, preserving HttpOnly session cookies across same-origin calls. Local development defaults to `https://hezarfen-backend.dizey.sh`, so `bun run dev` works without a backend process on the laptop; use `BACKEND_ORIGIN=http://127.0.0.1:7656 bun run dev` to target one locally. The production Bun server gets its co-located loopback default from the image and can be overridden through `hezarfen_frontend.env` (see "Run in a container" below). -> **Dev auto sign-in**: for local testing, put `VITE_DEV_AUTOLOGIN_USERNAME` and `VITE_DEV_AUTOLOGIN_PASSWORD` (optionally `VITE_DEV_AUTOLOGIN_SCHOOL`, a school slug) in `.env.local`, which git ignores. `bun run dev` then signs in on the first `401`; logging out turns it off for that tab. It lives in `src/lib/dev-auto-login.ts` behind `import.meta.env.DEV`, so `vite build` drops it and the credentials never reach `dist/`. +> **Dev auto sign-in**: for local testing, put `VITE_DEV_AUTOLOGIN_USERNAME` and `VITE_DEV_AUTOLOGIN_PASSWORD` (optionally `VITE_DEV_AUTOLOGIN_SCHOOL`, a school uuid) in `.env.local`, which git ignores. `bun run dev` then signs in on the first `401`; logging out turns it off for that tab. It lives in `src/lib/dev-auto-login.ts` behind `import.meta.env.DEV`, so `vite build` drops it and the credentials never reach `dist/`. > **Demo sign-in**: set `VITE_DEMO_LOGIN_USERNAME` and `VITE_DEMO_LOGIN_PASSWORD` at build time and the login page opens filled with them, plus a one-click "Demo hesabıyla gir" button (`src/lib/demo-login.ts`). Unlike the dev auto sign-in these values are bundled into `dist/`, so set them only for a demo school's build. diff --git a/docs/auth/role-scope-matrix.md b/docs/auth/role-scope-matrix.md index 845acb5..bebf3a3 100644 --- a/docs/auth/role-scope-matrix.md +++ b/docs/auth/role-scope-matrix.md @@ -47,7 +47,7 @@ route and a school session is 401 here, so these pages carry their own |---|---| | `/builder/login` | Operator sign-in (linked from the school login footer) | | `/builder` | School list: create (with first admin + module set), suspend/activate, delete | -| `/builder/schools/:slug` | Rename/status, module switchboard (per module + per package), admin password reset, enter as admin | +| `/builder/schools/:id` | Rename/status, module switchboard (per module + per package), admin password reset, enter as admin | ## Primary Navigation per Role diff --git a/docs/ui/figma-migration-coverage.md b/docs/ui/figma-migration-coverage.md index ed22fb4..99cf62d 100644 --- a/docs/ui/figma-migration-coverage.md +++ b/docs/ui/figma-migration-coverage.md @@ -162,7 +162,7 @@ Rules the captures follow: | `/profile/:userId` | ADM-29 Kullanıcı Profili | Captured from the running app | | `/builder/login` | BLD-01 Operatör Girişi | Builder session only; linked from the SYS-01/login footer | | `/builder` | BLD-02 Okullar, BLD-02a Yeni Okul | Create, suspend/activate, delete | -| `/builder/schools/:slug` | BLD-03 Okul Detayı, BLD-03a Okula Gir | Module switchboard, password reset, enter as admin | +| `/builder/schools/:id` | BLD-03 Okul Detayı, BLD-03a Okula Gir | Module switchboard, password reset, enter as admin | ## Figma features blocked by product or backend scope diff --git a/e2e/auth-shell.spec.ts b/e2e/auth-shell.spec.ts index d43c742..8413dae 100644 --- a/e2e/auth-shell.spec.ts +++ b/e2e/auth-shell.spec.ts @@ -1,17 +1,24 @@ import { expect, test } from "@playwright/test"; -const school = process.env.E2E_SCHOOL_SLUG ?? "demo"; +const schoolId = process.env.E2E_SCHOOL_ID; const username = process.env.E2E_ADMIN_USERNAME ?? "admin"; const password = process.env.E2E_ADMIN_PASSWORD ?? "admin123"; test("sign-in reaches the authenticated shell with keyboard-accessible navigation", async ({ page }) => { await page.goto("/login"); await expect(page.locator("#login-username")).toBeVisible(); - await page.locator("#login-school").fill(school); await page.locator("#login-username").fill(username); await page.locator("#login-password").fill(password); await page.locator("form").getByRole("button", { name: /log in|sign in|giriş yap/i }).click(); + const chooser = page.getByRole("heading", { name: /choose your school|okulunu seç/i }); + const shell = page.getByRole("main"); + await expect(chooser.or(shell)).toBeVisible(); + if (await chooser.isVisible()) { + if (!schoolId) throw new Error("login returned a school chooser; set E2E_SCHOOL_ID to the school uuid"); + await page.getByRole("button", { name: schoolId }).click(); + } + await expect(page).toHaveURL(/\/$/); await expect(page.getByRole("main")).toBeVisible(); diff --git a/src/api/__tests__/auth/auth.test.ts b/src/api/__tests__/auth/auth.test.ts index bf880f4..7a51ced 100644 --- a/src/api/__tests__/auth/auth.test.ts +++ b/src/api/__tests__/auth/auth.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; +import { getRegisterSchools } from "../../auth"; import { postLogin } from "../../auth"; import { postLogout } from "../../auth"; import { postRegister } from "../../auth"; @@ -27,13 +28,14 @@ describe("auth API", () => { const mockUser = { id: "u1", username: "test" }; mockFetchSuccess(mockUser); - const result = await postSelectSchool({ school: "demo" }); + const school = "019732e3-7b00-7000-8000-00000000dead"; + const result = await postSelectSchool({ school }); expect(result).toEqual(mockUser); const [url, init] = lastFetchCall(); expect(url).toBe("/api/auth/school"); expect(init?.method).toBe("POST"); - expect(init?.body).toBe(JSON.stringify({ school: "demo" })); + expect(init?.body).toBe(JSON.stringify({ school })); }); it("postLogout calls /auth/logout", async () => { @@ -50,7 +52,7 @@ describe("auth API", () => { const mockResponse = { username: "newuser", role: "student" }; mockFetchSuccess(mockResponse); - const data = { school: "demo", username: "newuser", password: "password" }; + const data = { school: "019732e3-7b00-7000-8000-00000000dead", username: "newuser", password: "password" }; const result = await postRegister(data); expect(result).toEqual(mockResponse); @@ -59,4 +61,16 @@ describe("auth API", () => { expect(init?.method).toBe("POST"); expect(init?.body).toBe(JSON.stringify(data)); }); + + it("getRegisterSchools reads active schools for the register picker", async () => { + const schools = [{ id: "019732e3-7b00-7000-8000-00000000dead", name: "Hezarfen" }]; + mockFetchSuccess(schools); + + const result = await getRegisterSchools(); + expect(result).toEqual(schools); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/auth/schools"); + expect(init?.method).toBe("GET"); + }); }); diff --git a/src/api/__tests__/contract/helpers/live-client.ts b/src/api/__tests__/contract/helpers/live-client.ts index dadd91b..2b99a8c 100644 --- a/src/api/__tests__/contract/helpers/live-client.ts +++ b/src/api/__tests__/contract/helpers/live-client.ts @@ -21,6 +21,20 @@ const TIMEOUT_MS = 10_000; const MAX_RATE_LIMIT_RETRIES = 12; let cookie = ""; +const SCHOOL_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** School cookie is `session=.`; operator cookie stays `session=builder.`. */ +function sessionCookie(raw: string): string | null { + const pair = raw.split(";")[0] ?? ""; + if (!pair.startsWith("session=")) return null; + const value = pair.slice("session=".length); + const dot = value.indexOf("."); + if (dot <= 0 || dot === value.length - 1) return null; + const prefix = value.slice(0, dot); + if (prefix === "builder" || SCHOOL_UUID.test(prefix)) return pair; + return null; +} + type Init = { method?: string; body?: unknown; headers?: Record }; function retryDelayMs(response: Response, attempt: number): number { @@ -59,8 +73,8 @@ export async function api(path: string, init: Init = {}): Promise { const setCookies = res!.headers.getSetCookie?.() ?? []; for (const raw of setCookies) { - const pair = raw.split(";")[0]; - if (pair.startsWith("session=")) cookie = pair; + const pair = sessionCookie(raw); + if (pair) cookie = pair; } return res!; } @@ -77,7 +91,7 @@ export async function json(path: string, init: Init = {}): Promise { /** Log in as the seeded admin; the session cookie lands in the jar. */ export async function loginAdmin(): Promise { - const result = await json<{ id: string } | { schools: Array<{ slug: string }> }>("/auth/login", { + const result = await json<{ id: string } | { schools: Array<{ id: string }> }>("/auth/login", { method: "POST", body: { username: env.ADMIN_USERNAME ?? "admin", @@ -85,7 +99,7 @@ export async function loginAdmin(): Promise { }, }); if ("schools" in result) { - const school = env.SCHOOL_SLUG ?? result.schools[0]?.slug; + const school = env.SCHOOL_ID ?? result.schools[0]?.id; if (!school) throw new Error("POST /auth/login returned an empty school choice list"); await json("/auth/school", { method: "POST", body: { school } }); } diff --git a/src/api/__tests__/schools/schools.test.ts b/src/api/__tests__/schools/schools.test.ts index 4a72814..bcef13b 100644 --- a/src/api/__tests__/schools/schools.test.ts +++ b/src/api/__tests__/schools/schools.test.ts @@ -1,10 +1,10 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { deleteSchoolBySlug } from "../../schools"; +import { deleteSchool } from "../../schools"; import { deleteSchoolModule } from "../../schools"; -import { getSchoolBySlug } from "../../schools"; +import { getSchool } from "../../schools"; import { getSchoolModules } from "../../schools"; import { getSchools } from "../../schools"; -import { patchSchoolBySlug } from "../../schools"; +import { patchSchool } from "../../schools"; import { patchSchoolModules } from "../../schools"; import { postSchool } from "../../schools"; import { postSchoolAdminPassword } from "../../schools"; @@ -12,7 +12,8 @@ import { postSchoolEnter } from "../../schools"; import { postSchoolModule } from "../../schools"; import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; -const school = { slug: "ata-koleji", name: "Ata Koleji", status: "active", created_at: 1, modules: ["courses"] }; +const schoolId = "019732e3-7b00-7000-8000-00000000dead"; +const school = { id: schoolId, name: "Ata Koleji", status: "active", created_at: 1, modules: ["courses"] }; const modules = { enabled: ["courses"], disabled: ["exams"] }; describe("schools API", () => { @@ -31,19 +32,19 @@ describe("schools API", () => { expect(init?.method).toBe("GET"); }); - it("getSchoolBySlug reads /schools/{slug}", async () => { + it("getSchool reads /schools/{id}", async () => { mockFetchSuccess(school); - await getSchoolBySlug("ata-koleji"); + await getSchool(schoolId); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/schools/ata-koleji"); + expect(url).toBe(`/api/schools/${schoolId}`); expect(init?.method).toBe("GET"); }); it("postSchool posts the school and its first admin", async () => { mockFetchSuccess(school, 201); - const body = { slug: "ata-koleji", name: "Ata Koleji", admin_username: "admin", admin_password: "secret123", modules: ["courses"] }; + const body = { name: "Ata Koleji", admin_username: "admin", admin_password: "secret123", modules: ["courses"] }; await postSchool(body); @@ -53,34 +54,34 @@ describe("schools API", () => { expect(init?.body).toBe(JSON.stringify(body)); }); - it("patchSchoolBySlug patches name and status", async () => { + it("patchSchool patches name and status", async () => { mockFetchSuccess({ ...school, status: "suspended" }); - await patchSchoolBySlug("ata-koleji", { status: "suspended" }); + await patchSchool(schoolId, { status: "suspended" }); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/schools/ata-koleji"); + expect(url).toBe(`/api/schools/${schoolId}`); expect(init?.method).toBe("PATCH"); expect(init?.body).toBe(JSON.stringify({ status: "suspended" })); }); - it("deleteSchoolBySlug deletes /schools/{slug}", async () => { + it("deleteSchool deletes /schools/{id}", async () => { mockFetch204(); - await deleteSchoolBySlug("ata-koleji"); + await deleteSchool(schoolId); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/schools/ata-koleji"); + expect(url).toBe(`/api/schools/${schoolId}`); expect(init?.method).toBe("DELETE"); }); it("postSchoolAdminPassword re-keys an admin", async () => { mockFetch204(); - await postSchoolAdminPassword("ata-koleji", { username: "admin", password: "newsecret" }); + await postSchoolAdminPassword(schoolId, { username: "admin", password: "newsecret" }); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/schools/ata-koleji/admin-password"); + expect(url).toBe(`/api/schools/${schoolId}/admin-password`); expect(init?.method).toBe("POST"); expect(init?.body).toBe(JSON.stringify({ username: "admin", password: "newsecret" })); }); @@ -88,10 +89,10 @@ describe("schools API", () => { it("postSchoolEnter enters as a named admin", async () => { mockFetchSuccess({ id: "u1", username: "admin", role: "admin" }); - await postSchoolEnter("ata-koleji", { username: "admin" }); + await postSchoolEnter(schoolId, { username: "admin" }); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/schools/ata-koleji/enter"); + expect(url).toBe(`/api/schools/${schoolId}/enter`); expect(init?.method).toBe("POST"); expect(init?.body).toBe(JSON.stringify({ username: "admin" })); }); @@ -99,11 +100,11 @@ describe("schools API", () => { it("getSchoolModules reads both halves of the catalog", async () => { mockFetchSuccess(modules); - const result = await getSchoolModules("ata-koleji"); + const result = await getSchoolModules(schoolId); expect(result).toEqual(modules); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/schools/ata-koleji/modules"); + expect(url).toBe(`/api/schools/${schoolId}/modules`); expect(init?.method).toBe("GET"); }); @@ -111,10 +112,10 @@ describe("schools API", () => { mockFetchSuccess(modules); const body = { enable: ["exams"], disable_packages: ["ai"] }; - await patchSchoolModules("ata-koleji", body); + await patchSchoolModules(schoolId, body); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/schools/ata-koleji/modules"); + expect(url).toBe(`/api/schools/${schoolId}/modules`); expect(init?.method).toBe("PATCH"); expect(init?.body).toBe(JSON.stringify(body)); }); @@ -122,20 +123,20 @@ describe("schools API", () => { it("postSchoolModule enables one module", async () => { mockFetchSuccess(modules); - await postSchoolModule("ata-koleji", "exams"); + await postSchoolModule(schoolId, "exams"); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/schools/ata-koleji/modules/exams"); + expect(url).toBe(`/api/schools/${schoolId}/modules/exams`); expect(init?.method).toBe("POST"); }); it("deleteSchoolModule disables one module", async () => { mockFetchSuccess(modules); - await deleteSchoolModule("ata-koleji", "exams"); + await deleteSchoolModule(schoolId, "exams"); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/schools/ata-koleji/modules/exams"); + expect(url).toBe(`/api/schools/${schoolId}/modules/exams`); expect(init?.method).toBe("DELETE"); }); }); diff --git a/src/api/auth/getRegisterSchools.ts b/src/api/auth/getRegisterSchools.ts new file mode 100644 index 0000000..5a2dc58 --- /dev/null +++ b/src/api/auth/getRegisterSchools.ts @@ -0,0 +1,7 @@ +import { client } from "../client"; +import type { SchoolChoice } from "./postLogin"; + +/** Active schools a new account can join. Unauthenticated, same as register. */ +export function getRegisterSchools(signal?: AbortSignal): Promise { + return client("/auth/schools", { signal }); +} diff --git a/src/api/auth/index.ts b/src/api/auth/index.ts index 45582ff..7dea67b 100644 --- a/src/api/auth/index.ts +++ b/src/api/auth/index.ts @@ -2,3 +2,4 @@ export * from "./postLogin"; export * from "./postLogout"; export * from "./postRegister"; export * from "./postSelectSchool"; +export * from "./getRegisterSchools"; diff --git a/src/api/auth/postLogin.ts b/src/api/auth/postLogin.ts index 7ad07dc..fd491d8 100644 --- a/src/api/auth/postLogin.ts +++ b/src/api/auth/postLogin.ts @@ -7,7 +7,7 @@ export type LoginBody = { }; export type SchoolChoice = { - slug: string; + id: string; name: string; }; diff --git a/src/api/client/client.ts b/src/api/client/client.ts index bd7f47c..cc6716c 100644 --- a/src/api/client/client.ts +++ b/src/api/client/client.ts @@ -133,10 +133,6 @@ const API_ERROR_MESSAGES: Record> = { tr: "Tekrarlanan müsaitlikler birbiriyle çakışıyor.", }, // Builder surface (web/builder.rs, tenant.rs) — byte-exact. - "school slug already taken": { - en: "That school code is already taken.", - tr: "Bu okul kodu zaten kullanılıyor.", - }, "that account is not an admin of this school": { en: "That account exists but is not an admin of this school.", tr: "Bu hesap var ama bu okulun yöneticisi değil.", diff --git a/src/api/client/types.ts b/src/api/client/types.ts index 8716976..b688bd4 100644 --- a/src/api/client/types.ts +++ b/src/api/client/types.ts @@ -188,7 +188,7 @@ export type SchoolStatus = "active" | "suspended"; /** One school of the deployment, as the builder surface sees it. */ export type School = { - slug: string; + id: string; name: string; /** A suspended school refuses every one of its own users, login included. */ status: SchoolStatus; @@ -831,11 +831,8 @@ export type Limits = { max_username_len: number; username_separators: string[]; reserved_usernames: string[]; - reserved_slugs: string[]; min_password_len: number; max_password_len: number; - min_slug_len: number; - max_slug_len: number; max_school_name_len: number; max_name_len: number; max_display_name_len: number; diff --git a/src/api/schools/deleteSchool.ts b/src/api/schools/deleteSchool.ts new file mode 100644 index 0000000..8a5b8de --- /dev/null +++ b/src/api/schools/deleteSchool.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; + +// Destroys the school's data and uploaded files for good. +export function deleteSchool(id: string): Promise { + return client(`/schools/${encodeURIComponent(id)}`, { method: "DELETE" }); +} diff --git a/src/api/schools/deleteSchoolBySlug.ts b/src/api/schools/deleteSchoolBySlug.ts deleted file mode 100644 index bf463c7..0000000 --- a/src/api/schools/deleteSchoolBySlug.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { client } from "../client"; - -// Destroys the school's data and uploaded files for good. -export function deleteSchoolBySlug(slug: string): Promise { - return client(`/schools/${encodeURIComponent(slug)}`, { method: "DELETE" }); -} diff --git a/src/api/schools/deleteSchoolModule.ts b/src/api/schools/deleteSchoolModule.ts index 0dbec22..0d45ec6 100644 --- a/src/api/schools/deleteSchoolModule.ts +++ b/src/api/schools/deleteSchoolModule.ts @@ -1,8 +1,8 @@ import { client } from "../client"; import type { SchoolModules } from "../client"; -export function deleteSchoolModule(slug: string, module: string): Promise { - return client(`/schools/${encodeURIComponent(slug)}/modules/${encodeURIComponent(module)}`, { +export function deleteSchoolModule(id: string, module: string): Promise { + return client(`/schools/${encodeURIComponent(id)}/modules/${encodeURIComponent(module)}`, { method: "DELETE", }); } diff --git a/src/api/schools/getSchool.ts b/src/api/schools/getSchool.ts new file mode 100644 index 0000000..05718b6 --- /dev/null +++ b/src/api/schools/getSchool.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; +import type { School } from "../client"; + +export function getSchool(id: string, signal?: AbortSignal): Promise { + return client(`/schools/${encodeURIComponent(id)}`, { signal }); +} diff --git a/src/api/schools/getSchoolBySlug.ts b/src/api/schools/getSchoolBySlug.ts deleted file mode 100644 index 682401f..0000000 --- a/src/api/schools/getSchoolBySlug.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { client } from "../client"; -import type { School } from "../client"; - -export function getSchoolBySlug(slug: string, signal?: AbortSignal): Promise { - return client(`/schools/${encodeURIComponent(slug)}`, { signal }); -} diff --git a/src/api/schools/getSchoolModules.ts b/src/api/schools/getSchoolModules.ts index d5d2105..5953263 100644 --- a/src/api/schools/getSchoolModules.ts +++ b/src/api/schools/getSchoolModules.ts @@ -1,6 +1,6 @@ import { client } from "../client"; import type { SchoolModules } from "../client"; -export function getSchoolModules(slug: string, signal?: AbortSignal): Promise { - return client(`/schools/${encodeURIComponent(slug)}/modules`, { signal }); +export function getSchoolModules(id: string, signal?: AbortSignal): Promise { + return client(`/schools/${encodeURIComponent(id)}/modules`, { signal }); } diff --git a/src/api/schools/index.ts b/src/api/schools/index.ts index 3c730a5..1e12a1e 100644 --- a/src/api/schools/index.ts +++ b/src/api/schools/index.ts @@ -1,8 +1,8 @@ export * from "./getSchools"; -export * from "./getSchoolBySlug"; +export * from "./getSchool"; export * from "./postSchool"; -export * from "./patchSchoolBySlug"; -export * from "./deleteSchoolBySlug"; +export * from "./patchSchool"; +export * from "./deleteSchool"; export * from "./postSchoolAdminPassword"; export * from "./postSchoolEnter"; export * from "./getSchoolModules"; diff --git a/src/api/schools/patchSchool.ts b/src/api/schools/patchSchool.ts new file mode 100644 index 0000000..d7d8710 --- /dev/null +++ b/src/api/schools/patchSchool.ts @@ -0,0 +1,11 @@ +import { client } from "../client"; +import type { School, SchoolStatus } from "../client"; + +export type UpdateSchoolBody = { + name?: string; + status?: SchoolStatus; +}; + +export function patchSchool(id: string, body: UpdateSchoolBody): Promise { + return client(`/schools/${encodeURIComponent(id)}`, { method: "PATCH", body }); +} diff --git a/src/api/schools/patchSchoolBySlug.ts b/src/api/schools/patchSchoolBySlug.ts deleted file mode 100644 index 58cdd13..0000000 --- a/src/api/schools/patchSchoolBySlug.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { client } from "../client"; -import type { School, SchoolStatus } from "../client"; - -export type UpdateSchoolBody = { - name?: string; - status?: SchoolStatus; -}; - -export function patchSchoolBySlug(slug: string, body: UpdateSchoolBody): Promise { - return client(`/schools/${encodeURIComponent(slug)}`, { method: "PATCH", body }); -} diff --git a/src/api/schools/patchSchoolModules.ts b/src/api/schools/patchSchoolModules.ts index fbf7082..2dd65b2 100644 --- a/src/api/schools/patchSchoolModules.ts +++ b/src/api/schools/patchSchoolModules.ts @@ -9,6 +9,6 @@ export type PatchSchoolModulesBody = { }; // One atomic re-sell: a 409 names every broken dependency and nothing is written. -export function patchSchoolModules(slug: string, body: PatchSchoolModulesBody): Promise { - return client(`/schools/${encodeURIComponent(slug)}/modules`, { method: "PATCH", body }); +export function patchSchoolModules(id: string, body: PatchSchoolModulesBody): Promise { + return client(`/schools/${encodeURIComponent(id)}/modules`, { method: "PATCH", body }); } diff --git a/src/api/schools/postSchool.ts b/src/api/schools/postSchool.ts index dac59d4..8597409 100644 --- a/src/api/schools/postSchool.ts +++ b/src/api/schools/postSchool.ts @@ -2,8 +2,6 @@ import { client } from "../client"; import type { School } from "../client"; export type CreateSchoolBody = { - /** Immutable once taken: names the school's database, blobs and cookie prefix. */ - slug: string; name: string; admin_username: string; admin_password: string; diff --git a/src/api/schools/postSchoolAdminPassword.ts b/src/api/schools/postSchoolAdminPassword.ts index a6e3b17..b3e6449 100644 --- a/src/api/schools/postSchoolAdminPassword.ts +++ b/src/api/schools/postSchoolAdminPassword.ts @@ -6,6 +6,6 @@ export type SchoolAdminPasswordBody = { }; // Re-keys an admin of that school and revokes every session the account held. -export function postSchoolAdminPassword(slug: string, body: SchoolAdminPasswordBody): Promise { - return client(`/schools/${encodeURIComponent(slug)}/admin-password`, { method: "POST", body }); +export function postSchoolAdminPassword(id: string, body: SchoolAdminPasswordBody): Promise { + return client(`/schools/${encodeURIComponent(id)}/admin-password`, { method: "POST", body }); } diff --git a/src/api/schools/postSchoolEnter.ts b/src/api/schools/postSchoolEnter.ts index 59c0779..1a79fca 100644 --- a/src/api/schools/postSchoolEnter.ts +++ b/src/api/schools/postSchoolEnter.ts @@ -3,6 +3,6 @@ import type { User } from "../client"; // Support access: swaps the builder cookie for an ordinary session of one of // the school's admins. Refused (403) on a suspended school. -export function postSchoolEnter(slug: string, body: { username: string }): Promise { - return client(`/schools/${encodeURIComponent(slug)}/enter`, { method: "POST", body }); +export function postSchoolEnter(id: string, body: { username: string }): Promise { + return client(`/schools/${encodeURIComponent(id)}/enter`, { method: "POST", body }); } diff --git a/src/api/schools/postSchoolModule.ts b/src/api/schools/postSchoolModule.ts index 53c199a..5b360ad 100644 --- a/src/api/schools/postSchoolModule.ts +++ b/src/api/schools/postSchoolModule.ts @@ -1,8 +1,8 @@ import { client } from "../client"; import type { SchoolModules } from "../client"; -export function postSchoolModule(slug: string, module: string): Promise { - return client(`/schools/${encodeURIComponent(slug)}/modules/${encodeURIComponent(module)}`, { +export function postSchoolModule(id: string, module: string): Promise { + return client(`/schools/${encodeURIComponent(id)}/modules/${encodeURIComponent(module)}`, { method: "POST", }); } diff --git a/src/components/builder/create-school-panel.tsx b/src/components/builder/create-school-panel.tsx index 6c9176d..1c3da33 100644 --- a/src/components/builder/create-school-panel.tsx +++ b/src/components/builder/create-school-panel.tsx @@ -13,8 +13,6 @@ import { Label } from "@/components/ui/label"; import { SidePanel } from "@/components/ui/side-panel"; import { useT } from "@/stores/preferences-context"; -const SLUG_PATTERN = "[a-z0-9][a-z0-9-]+"; - /** Creates a school with its first admin and, optionally, a hand-picked module set. */ export function CreateSchoolPanel(props: { open: boolean; onOpenChange: (open: boolean) => void; onCreated: (school: School) => void }) { const t = useT(); @@ -23,7 +21,6 @@ export function CreateSchoolPanel(props: { open: boolean; onOpenChange: (open: b () => props.open || undefined, () => getLimits().catch(() => null), ); - const [slug, setSlug] = createSignal(""); const [name, setName] = createSignal(""); const [adminUsername, setAdminUsername] = createSignal(""); const [adminPassword, setAdminPassword] = createSignal(""); @@ -33,7 +30,6 @@ export function CreateSchoolPanel(props: { open: boolean; onOpenChange: (open: b const [pending, setPending] = createSignal(false); const reset = () => { - setSlug(""); setName(""); setAdminUsername(""); setAdminPassword(""); @@ -50,7 +46,6 @@ export function CreateSchoolPanel(props: { open: boolean; onOpenChange: (open: b setPending(true); try { const school = await postSchool({ - slug: slug().trim(), name: name().trim(), admin_username: adminUsername().trim(), admin_password: adminPassword(), @@ -83,11 +78,6 @@ export function CreateSchoolPanel(props: { open: boolean; onOpenChange: (open: b {error()}
-
- - setSlug(e.currentTarget.value.toLowerCase())} /> -

{t("builder.slugHint")}

-
setName(e.currentTarget.value)} /> diff --git a/src/components/builder/school-admin-access-panel.tsx b/src/components/builder/school-admin-access-panel.tsx index fb073ca..a834b9a 100644 --- a/src/components/builder/school-admin-access-panel.tsx +++ b/src/components/builder/school-admin-access-panel.tsx @@ -16,7 +16,7 @@ export type AdminAccessMode = "enter" | "password"; * re-keys the admin and revokes every session it held. */ export function SchoolAdminAccessPanel(props: { - slug: string; + id: string; mode: AdminAccessMode | null; onClose: () => void; onEntered: () => void; @@ -40,11 +40,11 @@ export function SchoolAdminAccessPanel(props: { setPending(true); try { if (props.mode === "enter") { - await postSchoolEnter(props.slug, { username: username().trim() }); + await postSchoolEnter(props.id, { username: username().trim() }); reset(); props.onEntered(); } else { - await postSchoolAdminPassword(props.slug, { username: username().trim(), password: password() }); + await postSchoolAdminPassword(props.id, { username: username().trim(), password: password() }); reset(); props.onPasswordReset(); } diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index bc2fc63..5c27f1b 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -524,8 +524,6 @@ export const en: Dict = { "builder.statusSuspended": "Suspended", "builder.createSchool": "New school", "builder.createSchoolHint": "Creates the school's database and its first admin in one step.", - "builder.slug": "School code", - "builder.slugHint": "Lowercase letters, digits and hyphens. Cannot be changed later.", "builder.schoolName": "School name", "builder.adminUsername": "Admin username", "builder.adminPassword": "Admin password", @@ -784,7 +782,7 @@ export const en: Dict = { "auth.register": "Create account", "auth.username": "Username", "auth.school": "School", - "auth.schoolHint": "{min}–{max} characters", + "auth.noSchoolOpen": "No school is open for registration.", "auth.password": "Password", "auth.noAccount": "New here?", "auth.hasAccount": "Already registered?", @@ -803,7 +801,6 @@ export const en: Dict = { "auth.hidePassword": "Hide password", "auth.showConfirmPassword": "Show password confirmation", "auth.hideConfirmPassword": "Hide password confirmation", - "auth.schoolCodeHint": "The school code your school gave you (not the school's name): lowercase letters, digits and hyphens, {min}–{max} characters.", "auth.passwordMinHint": "At least {min} characters.", "auth.passwordTooShort": "The password needs at least {min} characters.", "auth.welcomeBack": "Good to see you again", diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts index 01d7db4..44aa023 100644 --- a/src/i18n/locales/tr.ts +++ b/src/i18n/locales/tr.ts @@ -520,8 +520,6 @@ export const tr: Dict = { "builder.statusSuspended": "Askıda", "builder.createSchool": "Yeni okul", "builder.createSchoolHint": "Okulun veritabanını ve ilk yöneticisini tek adımda oluşturur.", - "builder.slug": "Okul kodu", - "builder.slugHint": "Küçük harf, rakam ve tire. Sonradan değiştirilemez.", "builder.schoolName": "Okul adı", "builder.adminUsername": "Yönetici kullanıcı adı", "builder.adminPassword": "Yönetici şifresi", @@ -780,7 +778,7 @@ export const tr: Dict = { "auth.register": "Hesap oluştur", "auth.username": "Kullanıcı adı", "auth.school": "Okul", - "auth.schoolHint": "{min}–{max} karakter", + "auth.noSchoolOpen": "Kayıta açık bir okul yok.", "auth.password": "Şifre", "auth.noAccount": "Yeni misin?", "auth.hasAccount": "Zaten kayıtlı mısın?", @@ -799,7 +797,6 @@ export const tr: Dict = { "auth.hidePassword": "Şifreyi gizle", "auth.showConfirmPassword": "Şifre onayını göster", "auth.hideConfirmPassword": "Şifre onayını gizle", - "auth.schoolCodeHint": "Okulunun sana ilettiği okul kodu (okul adı değil): küçük harf, rakam ve tire, {min}–{max} karakter.", "auth.passwordMinHint": "En az {min} karakter.", "auth.passwordTooShort": "Şifre en az {min} karakter olmalı.", "auth.welcomeBack": "Seni yeniden görmek güzel", diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index d5cf92a..e876885 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -487,8 +487,6 @@ export type MessageKey = | "builder.statusSuspended" | "builder.createSchool" | "builder.createSchoolHint" - | "builder.slug" - | "builder.slugHint" | "builder.schoolName" | "builder.adminUsername" | "builder.adminPassword" @@ -771,7 +769,7 @@ export type MessageKey = | "auth.register" | "auth.username" | "auth.school" - | "auth.schoolHint" + | "auth.noSchoolOpen" | "auth.password" | "auth.noAccount" | "auth.hasAccount" @@ -790,7 +788,6 @@ export type MessageKey = | "auth.hidePassword" | "auth.showConfirmPassword" | "auth.hideConfirmPassword" - | "auth.schoolCodeHint" | "auth.passwordMinHint" | "auth.passwordTooShort" | "auth.welcomeBack" diff --git a/src/lib/dev-auto-login.ts b/src/lib/dev-auto-login.ts index a6a3329..86e8ee1 100644 --- a/src/lib/dev-auto-login.ts +++ b/src/lib/dev-auto-login.ts @@ -6,7 +6,7 @@ const SKIP_KEY = "hezarfen:dev-auto-login-off"; /** * Development-only sign-in with credentials from `.env.local` * (`VITE_DEV_AUTOLOGIN_USERNAME`, `VITE_DEV_AUTOLOGIN_PASSWORD`, optional - * `VITE_DEV_AUTOLOGIN_SCHOOL`). `import.meta.env.DEV` is a build-time false in + * `VITE_DEV_AUTOLOGIN_SCHOOL`, a school uuid). `import.meta.env.DEV` is a build-time false in * `vite build`, so the whole body is dropped from production bundles. * An explicit logout turns it off for the rest of the tab. */ @@ -18,7 +18,7 @@ export async function devAutoLogin(): Promise { try { const result = await postLogin({ username, password }); if (!("schools" in result)) return result; - const school = import.meta.env.VITE_DEV_AUTOLOGIN_SCHOOL || result.schools[0]?.slug; + const school = import.meta.env.VITE_DEV_AUTOLOGIN_SCHOOL || result.schools[0]?.id; return school ? await postSelectSchool({ school }) : null; } catch (err) { console.warn("Dev auto-login failed:", err); diff --git a/src/pages/builder-school-detail-page.tsx b/src/pages/builder-school-detail-page.tsx index 269278d..3c41e47 100644 --- a/src/pages/builder-school-detail-page.tsx +++ b/src/pages/builder-school-detail-page.tsx @@ -3,11 +3,11 @@ import { createResource } from "@/lib/create-resource"; import { useNavigate, useParams } from "@tanstack/solid-router"; import { getModulesCatalog } from "@/api/modules"; import { - deleteSchoolBySlug, + deleteSchool, deleteSchoolModule, - getSchoolBySlug, + getSchool, getSchoolModules, - patchSchoolBySlug, + patchSchool, patchSchoolModules, postSchoolModule, } from "@/api/schools"; @@ -51,12 +51,12 @@ function BuilderSchoolDetailContent() { const { locale } = usePreferences(); const auth = useAuth(); const navigate = useNavigate(); - const params = useParams({ from: "/builder/schools/$slug" }); - const slug = () => params().slug; + const params = useParams({ from: "/builder/schools/$id" }); + const id = () => params().id; - const [school, { refetch: refetchSchool }] = createResource(slug, (value) => getSchoolBySlug(value)); + const [school, { refetch: refetchSchool }] = createResource(id, (value) => getSchool(value)); const [catalog] = createResource(() => getModulesCatalog()); - const [modules] = createResource(slug, (value) => getSchoolModules(value)); + const [modules] = createResource(id, (value) => getSchoolModules(value)); // The switchboard owns a local copy: each switch is one write whose response // is the school's whole new set, so there is nothing to refetch. @@ -105,7 +105,7 @@ function BuilderSchoolDetailContent() { event.preventDefault(); setEditError(""); try { - await patchSchoolBySlug(slug(), { name: name().trim(), status: status() }); + await patchSchool(id(), { name: name().trim(), status: status() }); setEditOpen(false); await refetchSchool(); setFlash(t("common.saved")); @@ -127,7 +127,7 @@ function BuilderSchoolDetailContent() { @@ -180,10 +180,10 @@ function BuilderSchoolDetailContent() { enabled={enabled()} disabled={modulesSaving()} onToggle={(module, next) => - void writeModules(() => (next ? postSchoolModule(slug(), module) : deleteSchoolModule(slug(), module))) + void writeModules(() => (next ? postSchoolModule(id(), module) : deleteSchoolModule(id(), module))) } onTogglePackage={(pkg, next) => - void writeModules(() => patchSchoolModules(slug(), next ? { enable_packages: [pkg] } : { disable_packages: [pkg] })) + void writeModules(() => patchSchoolModules(id(), next ? { enable_packages: [pkg] } : { disable_packages: [pkg] })) } /> )} @@ -223,7 +223,7 @@ function BuilderSchoolDetailContent() { setAccessMode(null)} onPasswordReset={() => { @@ -244,10 +244,10 @@ function BuilderSchoolDetailContent() { title={t("builder.deleteSchool")} description={t("builder.deleteSchoolWarning")} variant="destructive" - summary={school() ? `${school()!.name} · ${school()!.slug}` : ""} + summary={school() ? `${school()!.name} · ${school()!.id}` : ""} onConfirm={async () => { try { - await deleteSchoolBySlug(slug()); + await deleteSchool(id()); void navigate({ to: "/builder" }); } catch (err) { setError(formatApiError(err)); diff --git a/src/pages/builder-schools-page.tsx b/src/pages/builder-schools-page.tsx index 9e83ef5..23ef897 100644 --- a/src/pages/builder-schools-page.tsx +++ b/src/pages/builder-schools-page.tsx @@ -2,7 +2,7 @@ import { Show, Suspense, createMemo, createSignal } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { useNavigate } from "@tanstack/solid-router"; import type { ColumnDef } from "@tanstack/solid-table"; -import { deleteSchoolBySlug, getSchools, patchSchoolBySlug } from "@/api/schools"; +import { deleteSchool, getSchools, patchSchool } from "@/api/schools"; import { formatApiError, type School } from "@/api/client"; import { BuilderGuard } from "@/components/builder/builder-guard"; import { BuilderHeader } from "@/components/builder/builder-header"; @@ -42,12 +42,12 @@ function BuilderSchoolsContent() { const [error, setError] = createSignal(""); const [flash, setFlash] = createFlash(); - const open = (school: School) => void navigate({ to: "/builder/schools/$slug", params: { slug: school.slug } }); + const open = (school: School) => void navigate({ to: "/builder/schools/$id", params: { id: school.id } }); const setStatus = async (school: School, status: School["status"]) => { setError(""); try { - await patchSchoolBySlug(school.slug, { status }); + await patchSchool(school.id, { status }); await refetch(); setFlash(t("common.saved")); } catch (err) { @@ -59,12 +59,14 @@ function BuilderSchoolsContent() { { accessorKey: "name", header: t("builder.schoolName"), - cell: (cell) => {cell.row.original.name}, - }, - { - accessorKey: "slug", - header: t("builder.slug"), - cell: (cell) => {cell.row.original.slug}, + cell: (cell) => ( + + {cell.row.original.name} + + {cell.row.original.id.slice(0, 8)} + + + ), }, { accessorKey: "status", @@ -157,12 +159,12 @@ function BuilderSchoolsContent() { title={t("builder.deleteSchool")} description={t("builder.deleteSchoolWarning")} variant="destructive" - summary={deleteTarget() ? `${deleteTarget()!.name} · ${deleteTarget()!.slug}` : ""} + summary={deleteTarget() ? `${deleteTarget()!.name} · ${deleteTarget()!.id}` : ""} onConfirm={async () => { const school = deleteTarget(); if (!school) return; try { - await deleteSchoolBySlug(school.slug); + await deleteSchool(school.id); await refetch(); setFlash(t("common.deleted")); } catch (err) { diff --git a/src/pages/login-page.test.tsx b/src/pages/login-page.test.tsx index 7bc9124..9f624f4 100644 --- a/src/pages/login-page.test.tsx +++ b/src/pages/login-page.test.tsx @@ -54,8 +54,8 @@ test("logs in without a school and completes the multi-school selection", async postLogin.mockResolvedValue({ username: "ada", schools: [ - { slug: "alpha", name: "Alpha School" }, - { slug: "beta", name: "Beta School" }, + { id: "019732e3-7b00-7000-8000-00000000dead", name: "Alpha School" }, + { id: "019732e3-7b00-7000-8000-00000000beef", name: "Beta School" }, ], }); postSelectSchool.mockResolvedValue({ id: "u1", username: "ada", role: "student" }); @@ -74,7 +74,7 @@ test("logs in without a school and completes the multi-school selection", async fireEvent.click(screen.getByText("Alpha School").closest("button")!); await waitFor(() => { - expect(postSelectSchool).toHaveBeenCalledWith({ school: "alpha" }); + expect(postSelectSchool).toHaveBeenCalledWith({ school: "019732e3-7b00-7000-8000-00000000dead" }); expect(refresh).toHaveBeenCalledOnce(); expect(navigate).toHaveBeenCalledWith({ to: "/" }); }); diff --git a/src/pages/login-page.tsx b/src/pages/login-page.tsx index b8fc22e..24a78c2 100644 --- a/src/pages/login-page.tsx +++ b/src/pages/login-page.tsx @@ -205,14 +205,14 @@ function LoginForm() { variant="outline" class="h-auto w-full justify-start px-4 py-3 text-left" disabled={pending()} - onClick={() => void handleSchoolSelect(school.slug)} + onClick={() => void handleSchoolSelect(school.id)} > {school.name} - {school.slug} + {school.id} - + {t("common.loading")} diff --git a/src/pages/register-page.tsx b/src/pages/register-page.tsx index 2e8742d..7ab779c 100644 --- a/src/pages/register-page.tsx +++ b/src/pages/register-page.tsx @@ -1,13 +1,14 @@ import { Link, useNavigate } from "@tanstack/solid-router"; -import { createSignal, Show } from "solid-js"; +import { For, Show, createSignal } from "solid-js"; import { createResource } from "@/lib/create-resource"; -import { postRegister } from "@/api/auth"; +import { getRegisterSchools, postRegister } from "@/api/auth"; import { getLimits } from "@/api/limits"; import { formatApiError } from "@/api/client"; import { AuthPageShell } from "@/components/auth/auth-page-shell"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; +import { Select } from "@/components/ui/select"; import { GuestGuard } from "@/components/layout/guest-guard"; import { IconEye, IconEyeOff } from "@/components/ui/icons"; import { useT } from "@/stores/preferences-context"; @@ -34,8 +35,8 @@ function RegisterForm() { const [error, setError] = createSignal(""); const [pending, setPending] = createSignal(false); const [limits] = createResource(() => getLimits().catch(() => null)); - const minSchoolSlugLength = () => limits()?.user.min_slug_len ?? 2; - const maxSchoolSlugLength = () => limits()?.user.max_slug_len ?? 32; + const [schools] = createResource(() => getRegisterSchools()); + const noSchoolOpen = () => schools.state === "ready" && !schools.error && (schools() ?? []).length === 0; const minPasswordLength = () => limits()?.user.min_password_len ?? 6; // Inline checks wait until the reader has left the field (or, for the // confirmation, typed as many characters as the password) so they never @@ -53,13 +54,10 @@ function RegisterForm() { const handleSubmit = async (e: SubmitEvent) => { e.preventDefault(); const s = school().trim(); + if (!s) return; const u = username().trim(); const p = password(); const cp = confirmPassword(); - if (s.length < minSchoolSlugLength() || s.length > maxSchoolSlugLength()) { - setError(t("auth.schoolHint", { min: minSchoolSlugLength(), max: maxSchoolSlugLength() })); - return; - } const userLimits = limits()?.user; if (userLimits && (u.length < userLimits.min_username_len || u.length > userLimits.max_username_len)) { setError(t("auth.usernameHint")); @@ -97,24 +95,23 @@ function RegisterForm() {
- setSchool(e.currentTarget.value.toLowerCase())} - /> -

- {t("auth.schoolCodeHint", { min: minSchoolSlugLength(), max: maxSchoolSlugLength() })} -

+ onChange={(e) => setSchool(e.currentTarget.value)} + > + + {(item) => } + + +

{t("auth.noSchoolOpen")}

+
+ +

{formatApiError(schools.error)}

+
@@ -206,7 +203,7 @@ function RegisterForm() {

{error()}

)} - diff --git a/src/routes/router.tsx b/src/routes/router.tsx index 4a3e02d..61efefd 100644 --- a/src/routes/router.tsx +++ b/src/routes/router.tsx @@ -542,7 +542,7 @@ const builderSchoolsRoute = createRoute({ const builderSchoolDetailRoute = createRoute({ getParentRoute: () => rootRoute, - path: "/builder/schools/$slug", + path: "/builder/schools/$id", component: BuilderSchoolDetailPage, }); diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts index 4885d16..4577bf8 100644 --- a/src/vite-env.d.ts +++ b/src/vite-env.d.ts @@ -4,6 +4,7 @@ interface ImportMetaEnv { /** Dev-only auto sign-in (see src/lib/dev-auto-login.ts); set in .env.local, never committed. */ readonly VITE_DEV_AUTOLOGIN_USERNAME?: string; readonly VITE_DEV_AUTOLOGIN_PASSWORD?: string; + /** Optional school uuid when login returns a choice list. */ readonly VITE_DEV_AUTOLOGIN_SCHOOL?: string; /** Demo account prefilled on the login page (see src/lib/demo-login.ts); bundled when set. */ readonly VITE_DEMO_LOGIN_USERNAME?: string;