diff --git a/docs/auth/role-scope-matrix.md b/docs/auth/role-scope-matrix.md index 485ca49..845acb5 100644 --- a/docs/auth/role-scope-matrix.md +++ b/docs/auth/role-scope-matrix.md @@ -29,6 +29,25 @@ | Settings `/management/settings` | ❌ | ❌ | ✅ | ✅ | | Terms `/management/terms` | ❌ | ❌ | ✅ | ✅ | | User management `/admin/users` | ❌ | ❌ | ❌ | ✅ | +| License & modules `/management/modules` (read-only) | ❌ | ❌ | ❌ | ✅ | +| Student pomodoro lookup `/management/pomodoros` | ❌ | ✅ | ✅ | ✅ | + +Parent pages: `/students` (progress report) plus `/students/attendance`, +`/students/exams`, `/students/study` — the same page opening a linked child on +that tab. Study reads `GET /pomodoro/{user}` (parent link), shown only when the +school has the `pomodoro` module. + +## Builder (Operator) Surface + +Not a school role. A builder session (`builder.` cookie) is 401 on every school +route and a school session is 401 here, so these pages carry their own +`BuilderProvider`/`BuilderGuard` instead of `RouteGuard`. + +| Page | Purpose | +|---|---| +| `/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 | ## Primary Navigation per Role @@ -44,8 +63,11 @@ | Meals `/meals` | ❌ | ❌ | ❌ | ❌ | ✅ | Primary destinations stay compact. Every role-valid list page is also exposed -in the grouped sidebar/mobile drawer; Education and Community are collapsible. -Appointments is directly available there for every role. Detail pages remain +in the grouped sidebar/mobile drawer, gated by the school's modules: +courses, notes, questions, events, meals, appointments and messages for every +role the backend serves them to; terms, student marks/pomodoro lookups and the +work log for staff; license modules for admin. Appointments is directly +available there for every role. Detail pages remain reachable from their parent lists, and Guide remains in the account menu. ## Dashboard Scope per Role diff --git a/docs/ui/figma-migration-coverage.md b/docs/ui/figma-migration-coverage.md index b547d43..742f5e9 100644 --- a/docs/ui/figma-migration-coverage.md +++ b/docs/ui/figma-migration-coverage.md @@ -20,6 +20,7 @@ must always be replaced with real application data. | Student | `3:7` | 11 screens plus 2 modal variants audited | | Parent | `3:8` | 8 screens audited | | System | `103:2` | 7 screens audited | +| Builder — Operatör | `205:23536` | BLD-01 login, BLD-02 schools, BLD-02a new school panel, BLD-03 school detail, BLD-03a enter-school panel | | Mobile Kit | `40:2` | Shared 393px mobile primitives audited | | Student Mobile | `40:3` | 9 screens audited | | Parent Mobile | `40:4` | 6 screens audited | @@ -29,6 +30,22 @@ The Cover manifest also names a Foundations page, but no Foundations node URL was supplied. Exact values already exposed by component and dark-mode contexts are used; unknown values are not inferred. +## Navigation sync (2026-09-13) + +The four `Web / Sidebar / *` components mirror `src/components/layout/nav-items.ts` +as an accordion, the way the app renders them: `Web / Nav Group` headers +(Collapsed/Open) over `Web / Nav Group Item` rows (Default/Active, "Yakında" +badge). Each screen overrides only its open group and active row. When the +nav tree changes in code, update the sidebar component, not individual +screens. `Web / Switch` (Off/On) backs module and review toggles. + +The shell matches the app too: `Web / Sidebar / *` is full height with the +`Brand / Logo Mark` row on top and the account row at the bottom, and +`Web / Top Bar` is the 1180px content header (back, route label, command +center, messages, notifications, Çelebi'ye sor) at x=260. Screens added from +the running app are `generate_figma_design` captures whose sidebar and top bar +were swapped for these component instances; their content is raw layers. + ## Implemented foundation - Figma semantic light/dark aliases with the landing page's `#00ADD8` brand @@ -71,9 +88,21 @@ are used; unknown values are not inferred. | `/management/payments` | Admin payments | Keep ledger and permission behavior | | `/management/staff-work` | Admin staff work | Keep existing read/update/delete contract | | `/admin/users`, `/admin/users/:id` | Admin users and roles | Keep admin guard and critical confirmations | +| `/management/students` | ADM-02 Öğrenciler | Real roster + class/term filters; mastery, attendance, plan and risk columns stay "yakında" | +| `/management/teachers` | ADM-08 Öğretmenler | Real roster + homeroom class count; branch, load, AI acceptance and status stay "yakında" | +| `/management/modules` | ADM-05 Lisans ve modüller | Real enabled/total modules per package; price, seats, renewal and invoices stay "yakında" | | `/students` | Parent development views | Keep linked-child authorization | | `/meals`, `/meals/:id` | Admin cafeteria | Keep menu, booking, balance, and attendance behavior | | `/payments` | Parent/student statement | Remain read-only until a payment-provider API exists | +| `/management/terms` | ADM-25 Dönemler | Captured from the running app | +| `/events`, `/events/:id` | ADM-26 Etkinlikler, ADM-26a Etkinlik Detayı | Captured from the running app | +| `/management/pomodoros` | ADM-27 Öğrenci Pomodoroları | Captured from the running app | +| `/questions`, `/questions/:id` | TCH-15 Soru Havuzu, STU-13 Soru Detayı | Captured from the running app | +| `/notes` | STU-12 Defter | Captured from the running app | +| `/guide`, `/profile/me`, `/register` | SYS-08 Rehber, SYS-09 Profilim, SYS-10 Kayıt Ol | 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 | ## Figma features blocked by product or backend scope @@ -99,17 +128,11 @@ false actions: Keep the current UI and behavior until a specific design is added: -- `/register` -- `/guide` -- `/profile/me`, `/profile/:userId` -- `/notes` -- `/questions`, `/questions/:id` -- `/events`, `/events/:id` +- `/profile/:userId` (another user's profile) - `/exam-room/:id` - `/exams/:id/live` -- `/management/pomodoros` -- `/management/terms` - `/whiteboards/:id` live canvas details beyond the list concept +- `/students/attendance`, `/students/exams`, `/students/study` parent tab routes - `/meals/:id` detailed account/service/management tabs - `/studies`, `/clubs`, and `/attendance` redirect aliases diff --git a/src/api/__tests__/builder/builder.test.ts b/src/api/__tests__/builder/builder.test.ts new file mode 100644 index 0000000..1ba03ea --- /dev/null +++ b/src/api/__tests__/builder/builder.test.ts @@ -0,0 +1,44 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { getBuilderMe } from "../../builder"; +import { postBuilderLogin } from "../../builder"; +import { postBuilderLogout } from "../../builder"; +import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; + +describe("builder API", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("postBuilderLogin posts credentials to /builder/login", async () => { + const builder = { id: "b1", username: "operator" }; + mockFetchSuccess(builder); + + const result = await postBuilderLogin({ username: "operator", password: "correct horse" }); + expect(result).toEqual(builder); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/builder/login"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify({ username: "operator", password: "correct horse" })); + }); + + it("postBuilderLogout posts to /builder/logout", async () => { + mockFetch204(); + + await postBuilderLogout(); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/builder/logout"); + expect(init?.method).toBe("POST"); + }); + + it("getBuilderMe reads /builder/me", async () => { + mockFetchSuccess({ id: "b1", username: "operator" }); + + await getBuilderMe(); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/builder/me"); + expect(init?.method).toBe("GET"); + }); +}); diff --git a/src/api/__tests__/schools/schools.test.ts b/src/api/__tests__/schools/schools.test.ts new file mode 100644 index 0000000..4a72814 --- /dev/null +++ b/src/api/__tests__/schools/schools.test.ts @@ -0,0 +1,141 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { deleteSchoolBySlug } from "../../schools"; +import { deleteSchoolModule } from "../../schools"; +import { getSchoolBySlug } from "../../schools"; +import { getSchoolModules } from "../../schools"; +import { getSchools } from "../../schools"; +import { patchSchoolBySlug } from "../../schools"; +import { patchSchoolModules } from "../../schools"; +import { postSchool } from "../../schools"; +import { postSchoolAdminPassword } from "../../schools"; +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 modules = { enabled: ["courses"], disabled: ["exams"] }; + +describe("schools API", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("getSchools pages /schools", async () => { + mockFetchSuccess({ items: [school], total: 1, limit: 20, offset: 0 }); + + const result = await getSchools({ limit: 20, offset: 0 }); + expect(result.items).toEqual([school]); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/schools?limit=20&offset=0"); + expect(init?.method).toBe("GET"); + }); + + it("getSchoolBySlug reads /schools/{slug}", async () => { + mockFetchSuccess(school); + + await getSchoolBySlug("ata-koleji"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/schools/ata-koleji"); + 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"] }; + + await postSchool(body); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/schools"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("patchSchoolBySlug patches name and status", async () => { + mockFetchSuccess({ ...school, status: "suspended" }); + + await patchSchoolBySlug("ata-koleji", { status: "suspended" }); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/schools/ata-koleji"); + expect(init?.method).toBe("PATCH"); + expect(init?.body).toBe(JSON.stringify({ status: "suspended" })); + }); + + it("deleteSchoolBySlug deletes /schools/{slug}", async () => { + mockFetch204(); + + await deleteSchoolBySlug("ata-koleji"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/schools/ata-koleji"); + expect(init?.method).toBe("DELETE"); + }); + + it("postSchoolAdminPassword re-keys an admin", async () => { + mockFetch204(); + + await postSchoolAdminPassword("ata-koleji", { username: "admin", password: "newsecret" }); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/schools/ata-koleji/admin-password"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify({ username: "admin", password: "newsecret" })); + }); + + it("postSchoolEnter enters as a named admin", async () => { + mockFetchSuccess({ id: "u1", username: "admin", role: "admin" }); + + await postSchoolEnter("ata-koleji", { username: "admin" }); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/schools/ata-koleji/enter"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify({ username: "admin" })); + }); + + it("getSchoolModules reads both halves of the catalog", async () => { + mockFetchSuccess(modules); + + const result = await getSchoolModules("ata-koleji"); + expect(result).toEqual(modules); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/schools/ata-koleji/modules"); + expect(init?.method).toBe("GET"); + }); + + it("patchSchoolModules re-sells the shelf in one write", async () => { + mockFetchSuccess(modules); + const body = { enable: ["exams"], disable_packages: ["ai"] }; + + await patchSchoolModules("ata-koleji", body); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/schools/ata-koleji/modules"); + expect(init?.method).toBe("PATCH"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("postSchoolModule enables one module", async () => { + mockFetchSuccess(modules); + + await postSchoolModule("ata-koleji", "exams"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/schools/ata-koleji/modules/exams"); + expect(init?.method).toBe("POST"); + }); + + it("deleteSchoolModule disables one module", async () => { + mockFetchSuccess(modules); + + await deleteSchoolModule("ata-koleji", "exams"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/schools/ata-koleji/modules/exams"); + expect(init?.method).toBe("DELETE"); + }); +}); diff --git a/src/api/builder/getBuilderMe.ts b/src/api/builder/getBuilderMe.ts new file mode 100644 index 0000000..40f1f52 --- /dev/null +++ b/src/api/builder/getBuilderMe.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; +import type { Builder } from "../client"; + +export function getBuilderMe(signal?: AbortSignal): Promise { + return client("/builder/me", { signal }); +} diff --git a/src/api/builder/index.ts b/src/api/builder/index.ts new file mode 100644 index 0000000..a45cd7b --- /dev/null +++ b/src/api/builder/index.ts @@ -0,0 +1,3 @@ +export * from "./getBuilderMe"; +export * from "./postBuilderLogin"; +export * from "./postBuilderLogout"; diff --git a/src/api/builder/postBuilderLogin.ts b/src/api/builder/postBuilderLogin.ts new file mode 100644 index 0000000..54911de --- /dev/null +++ b/src/api/builder/postBuilderLogin.ts @@ -0,0 +1,13 @@ +import { client } from "../client"; +import type { Builder } from "../client"; + +export type BuilderLoginBody = { + username: string; + password: string; +}; + +// Sets a `builder.`-prefixed session cookie, which replaces any school session +// in this browser: the two are mutually exclusive (each is 401 on the other side). +export function postBuilderLogin(body: BuilderLoginBody): Promise { + return client("/builder/login", { method: "POST", body }); +} diff --git a/src/api/builder/postBuilderLogout.ts b/src/api/builder/postBuilderLogout.ts new file mode 100644 index 0000000..b2e0393 --- /dev/null +++ b/src/api/builder/postBuilderLogout.ts @@ -0,0 +1,5 @@ +import { client } from "../client"; + +export function postBuilderLogout(): Promise { + return client("/builder/logout", { method: "POST" }); +} diff --git a/src/api/client/client.ts b/src/api/client/client.ts index d661db8..84dc2ea 100644 --- a/src/api/client/client.ts +++ b/src/api/client/client.ts @@ -105,6 +105,19 @@ const API_ERROR_MESSAGES: Record> = { en: "The repeated slots overlap each other.", 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.", + }, + "school is suspended": { + en: "This school is suspended.", + tr: "Bu okul askıya alınmış.", + }, // Booking/decision conflicts from domain/appointment.rs — byte-exact. "the slot is already booked": { en: "Someone else booked this time first.", diff --git a/src/api/client/types.ts b/src/api/client/types.ts index db03db5..eedec35 100644 --- a/src/api/client/types.ts +++ b/src/api/client/types.ts @@ -133,6 +133,32 @@ export type NoteFile = { size: number; }; +/** The deployment operator behind a `builder.` session cookie — no role, no school. */ +export type Builder = { + id: string; + username: string; +}; + +export type SchoolStatus = "active" | "suspended"; + +/** One school of the deployment, as the builder surface sees it. */ +export type School = { + slug: string; + name: string; + /** A suspended school refuses every one of its own users, login included. */ + status: SchoolStatus; + /** UTC unix-milliseconds. */ + created_at: number; + /** Bought modules, sorted by name. */ + modules: string[]; +}; + +/** One school's entitlements, both halves of the catalog. */ +export type SchoolModules = { + enabled: string[]; + disabled: string[]; +}; + /** The caller's school entitlements: every switched-on module, sorted by name. */ export type EnabledModules = { enabled: string[]; diff --git a/src/api/schools/deleteSchoolBySlug.ts b/src/api/schools/deleteSchoolBySlug.ts new file mode 100644 index 0000000..bf463c7 --- /dev/null +++ b/src/api/schools/deleteSchoolBySlug.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000..0dbec22 --- /dev/null +++ b/src/api/schools/deleteSchoolModule.ts @@ -0,0 +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)}`, { + method: "DELETE", + }); +} diff --git a/src/api/schools/getSchoolBySlug.ts b/src/api/schools/getSchoolBySlug.ts new file mode 100644 index 0000000..682401f --- /dev/null +++ b/src/api/schools/getSchoolBySlug.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000..d5d2105 --- /dev/null +++ b/src/api/schools/getSchoolModules.ts @@ -0,0 +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 }); +} diff --git a/src/api/schools/getSchools.ts b/src/api/schools/getSchools.ts new file mode 100644 index 0000000..147b579 --- /dev/null +++ b/src/api/schools/getSchools.ts @@ -0,0 +1,8 @@ +import { client } from "../client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { School } from "../client"; + +export async function getSchools(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/schools${pageQuery(params)}`, { signal }); + return normalizePage(data); +} diff --git a/src/api/schools/index.ts b/src/api/schools/index.ts new file mode 100644 index 0000000..3c730a5 --- /dev/null +++ b/src/api/schools/index.ts @@ -0,0 +1,11 @@ +export * from "./getSchools"; +export * from "./getSchoolBySlug"; +export * from "./postSchool"; +export * from "./patchSchoolBySlug"; +export * from "./deleteSchoolBySlug"; +export * from "./postSchoolAdminPassword"; +export * from "./postSchoolEnter"; +export * from "./getSchoolModules"; +export * from "./patchSchoolModules"; +export * from "./postSchoolModule"; +export * from "./deleteSchoolModule"; diff --git a/src/api/schools/patchSchoolBySlug.ts b/src/api/schools/patchSchoolBySlug.ts new file mode 100644 index 0000000..58cdd13 --- /dev/null +++ b/src/api/schools/patchSchoolBySlug.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 0000000..fbf7082 --- /dev/null +++ b/src/api/schools/patchSchoolModules.ts @@ -0,0 +1,14 @@ +import { client } from "../client"; +import type { SchoolModules } from "../client"; + +export type PatchSchoolModulesBody = { + enable?: string[]; + disable?: string[]; + enable_packages?: string[]; + disable_packages?: string[]; +}; + +// 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 }); +} diff --git a/src/api/schools/postSchool.ts b/src/api/schools/postSchool.ts new file mode 100644 index 0000000..dac59d4 --- /dev/null +++ b/src/api/schools/postSchool.ts @@ -0,0 +1,16 @@ +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; + /** Omitted sells the whole catalog. */ + modules?: string[]; +}; + +export function postSchool(body: CreateSchoolBody): Promise { + return client("/schools", { method: "POST", body }); +} diff --git a/src/api/schools/postSchoolAdminPassword.ts b/src/api/schools/postSchoolAdminPassword.ts new file mode 100644 index 0000000..a6e3b17 --- /dev/null +++ b/src/api/schools/postSchoolAdminPassword.ts @@ -0,0 +1,11 @@ +import { client } from "../client"; + +export type SchoolAdminPasswordBody = { + username: string; + password: string; +}; + +// 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 }); +} diff --git a/src/api/schools/postSchoolEnter.ts b/src/api/schools/postSchoolEnter.ts new file mode 100644 index 0000000..59c0779 --- /dev/null +++ b/src/api/schools/postSchoolEnter.ts @@ -0,0 +1,8 @@ +import { client } from "../client"; +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 }); +} diff --git a/src/api/schools/postSchoolModule.ts b/src/api/schools/postSchoolModule.ts new file mode 100644 index 0000000..53c199a --- /dev/null +++ b/src/api/schools/postSchoolModule.ts @@ -0,0 +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)}`, { + method: "POST", + }); +} diff --git a/src/components/builder/builder-guard.tsx b/src/components/builder/builder-guard.tsx new file mode 100644 index 0000000..c4628a0 --- /dev/null +++ b/src/components/builder/builder-guard.tsx @@ -0,0 +1,26 @@ +import { Navigate } from "@tanstack/solid-router"; +import { type ParentProps, Show } from "solid-js"; +import { formatApiError } from "@/api/client"; +import { ErrorAlert } from "@/components/ui/error-alert"; +import { PageSpinner } from "@/components/ui/page-spinner"; +import { useBuilder } from "@/stores/builder-context"; + +/** Renders its children only for a live builder session; otherwise sends the visitor to /builder/login. */ +export function BuilderGuard(props: ParentProps) { + const session = useBuilder(); + + return ( + }> + }> + + + } + > + {props.children} + + + ); +} diff --git a/src/components/builder/builder-header.tsx b/src/components/builder/builder-header.tsx new file mode 100644 index 0000000..157a739 --- /dev/null +++ b/src/components/builder/builder-header.tsx @@ -0,0 +1,33 @@ +import { Link, useNavigate } from "@tanstack/solid-router"; +import { Button } from "@/components/ui/button"; +import { IconLogout, IconShieldCheck } from "@/components/ui/icons"; +import { useBuilder } from "@/stores/builder-context"; +import { useT } from "@/stores/preferences-context"; + +/** The operator strip over every builder page: where you are, who you are, the way out. */ +export function BuilderHeader() { + const session = useBuilder(); + const navigate = useNavigate(); + const t = useT(); + + const logout = async () => { + await session.logout(); + void navigate({ to: "/builder/login" }); + }; + + return ( +
+ + + {t("builder.console")} + +
+ @{session.builder()?.username} + +
+
+ ); +} diff --git a/src/components/builder/create-school-panel.tsx b/src/components/builder/create-school-panel.tsx new file mode 100644 index 0000000..0f005e6 --- /dev/null +++ b/src/components/builder/create-school-panel.tsx @@ -0,0 +1,129 @@ +import { Show, createResource, createSignal } from "solid-js"; +import { getModulesCatalog } from "@/api/modules"; +import { postSchool } from "@/api/schools"; +import type { School } from "@/api/client"; +import { ModuleCatalogGrid } from "@/components/modules/module-catalog-grid"; +import { formatModuleError } from "@/lib/module-labels"; +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 { useT } from "@/stores/preferences-context"; + +const SLUG_PATTERN = "[a-z0-9][a-z0-9-]{1,31}"; + +/** 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(); + const [catalog] = createResource(() => props.open || undefined, () => getModulesCatalog()); + const [slug, setSlug] = createSignal(""); + const [name, setName] = createSignal(""); + const [adminUsername, setAdminUsername] = createSignal(""); + const [adminPassword, setAdminPassword] = createSignal(""); + const [everything, setEverything] = createSignal(true); + const [picked, setPicked] = createSignal([]); + const [error, setError] = createSignal(""); + const [pending, setPending] = createSignal(false); + + const reset = () => { + setSlug(""); + setName(""); + setAdminUsername(""); + setAdminPassword(""); + setEverything(true); + setPicked([]); + setError(""); + }; + + const packageModules = (pkg: string) => catalog()?.packages.find((entry) => entry.package === pkg)?.modules ?? []; + + const submit = async (event: SubmitEvent) => { + event.preventDefault(); + setError(""); + setPending(true); + try { + const school = await postSchool({ + slug: slug().trim(), + name: name().trim(), + admin_username: adminUsername().trim(), + admin_password: adminPassword(), + // Omitted sells the whole catalog; an explicit list is checked for + // missing dependencies before anything is created (409). + modules: everything() ? undefined : picked(), + }); + reset(); + props.onCreated(school); + } catch (err) { + setError(formatModuleError(err, t)); + } finally { + setPending(false); + } + }; + + return ( + { + props.onOpenChange(open); + if (!open) reset(); + }} + title={t("builder.createSchool")} + description={t("builder.createSchoolHint")} + > +
+ + {error()} + +
+
+ + setSlug(e.currentTarget.value.toLowerCase())} /> +

{t("builder.slugHint")}

+
+
+ + setName(e.currentTarget.value)} /> +
+
+ + setAdminUsername(e.currentTarget.value)} /> +
+
+ + setAdminPassword(e.currentTarget.value)} /> +
+
+ + + {(value) => ( + setPicked((current) => (next ? [...current, module] : current.filter((name) => name !== module)))} + onTogglePackage={(pkg, next) => + setPicked((current) => { + const modules = packageModules(pkg); + return next ? [...new Set([...current, ...modules])] : current.filter((name) => !modules.includes(name)); + }) + } + /> + )} + +
+ + +
+
+
+ ); +} diff --git a/src/components/builder/school-admin-access-panel.tsx b/src/components/builder/school-admin-access-panel.tsx new file mode 100644 index 0000000..9d004c4 --- /dev/null +++ b/src/components/builder/school-admin-access-panel.tsx @@ -0,0 +1,95 @@ +import { Show, createSignal } from "solid-js"; +import { formatApiError } from "@/api/client"; +import { postSchoolAdminPassword, postSchoolEnter } from "@/api/schools"; +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 { useT } from "@/stores/preferences-context"; + +export type AdminAccessMode = "enter" | "password"; + +/** + * The two support doors into a school, both naming one of its admins: + * `enter` swaps the builder cookie for that admin's session, `password` + * re-keys the admin and revokes every session it held. + */ +export function SchoolAdminAccessPanel(props: { + slug: string; + mode: AdminAccessMode | null; + onClose: () => void; + onEntered: () => void; + onPasswordReset: () => void; +}) { + const t = useT(); + const [username, setUsername] = createSignal(""); + const [password, setPassword] = createSignal(""); + const [error, setError] = createSignal(""); + const [pending, setPending] = createSignal(false); + + const reset = () => { + setUsername(""); + setPassword(""); + setError(""); + }; + + const submit = async (event: SubmitEvent) => { + event.preventDefault(); + setError(""); + setPending(true); + try { + if (props.mode === "enter") { + await postSchoolEnter(props.slug, { username: username().trim() }); + reset(); + props.onEntered(); + } else { + await postSchoolAdminPassword(props.slug, { username: username().trim(), password: password() }); + reset(); + props.onPasswordReset(); + } + } catch (err) { + setError(formatApiError(err)); + } finally { + setPending(false); + } + }; + + return ( + { + if (!open) { + reset(); + props.onClose(); + } + }} + title={props.mode === "enter" ? t("builder.enterSchool") : t("builder.resetAdminPassword")} + description={props.mode === "enter" ? t("builder.enterSchoolHint") : t("builder.resetAdminPasswordHint")} + > +
+ + {error()} + +
+ + setUsername(e.currentTarget.value)} /> +
+ +
+ + setPassword(e.currentTarget.value)} /> +
+
+
+ + +
+
+
+ ); +} diff --git a/src/components/builder/school-status-badge.tsx b/src/components/builder/school-status-badge.tsx new file mode 100644 index 0000000..2b179bb --- /dev/null +++ b/src/components/builder/school-status-badge.tsx @@ -0,0 +1,12 @@ +import type { SchoolStatus } from "@/api/client"; +import { Badge } from "@/components/ui/badge"; +import { useT } from "@/stores/preferences-context"; + +export function SchoolStatusBadge(props: { status: SchoolStatus }) { + const t = useT(); + return ( + + {props.status === "active" ? t("builder.statusActive") : t("builder.statusSuspended")} + + ); +} diff --git a/src/components/layout/nav-items.test.ts b/src/components/layout/nav-items.test.ts index 4e5fa3b..dbf44ac 100644 --- a/src/components/layout/nav-items.test.ts +++ b/src/components/layout/nav-items.test.ts @@ -16,7 +16,7 @@ test("invalid role destinations stay hidden", () => { expect(visibleNavItems("parent").map((item) => item.to)).not.toContain("/management/staff-work"); }); -test("admin's sidebar mirrors the Figma Operasyon / Yapay zekâ / Kurum tree", () => { +test("admin's sidebar keeps the Figma Operasyon / Yapay zekâ / Kurum tree plus every backed page", () => { expect( visibleNavGroups("admin").map((group) => ({ id: group.id, @@ -29,10 +29,20 @@ test("admin's sidebar mirrors the Figma Operasyon / Yapay zekâ / Kurum tree", ( "students-roster", "teachers-roster", "class-groups", + "courses", + "terms", "schedule", + "events", "student-attendance", + "student-marks", + "student-pomodoros", + "homework", "exams", "question-bank", + "questions", + "notes", + "whiteboards", + "appointments", "mock-exams", "optical-reading", "payments-collection", @@ -41,46 +51,62 @@ test("admin's sidebar mirrors the Figma Operasyon / Yapay zekâ / Kurum tree", ( { id: "ai", items: ["hezarfen-zeka", "celebi", "sound-studio"] }, { id: "institution", - items: ["reports", "license-modules", "users", "data-protection", "school-meals", "staff-work", "settings"], + items: ["reports", "license-modules", "users", "data-protection", "school-meals", "staff-work", "work", "settings"], }, ]); }); test("manager sees the same admin tree minus the admin-only entries", () => { const institution = visibleNavGroups("manager").find((group) => group.id === "institution"); - expect(institution?.items.map((item) => item.id)).toEqual(["reports", "school-meals", "staff-work", "settings"]); + expect(institution?.items.map((item) => item.id)).toEqual(["reports", "school-meals", "staff-work", "work", "settings"]); expect(institution?.items.map((item) => item.id)).not.toContain("license-modules"); expect(institution?.items.map((item) => item.id)).not.toContain("users"); expect(institution?.items.map((item) => item.id)).not.toContain("data-protection"); }); -test("teacher's sidebar mirrors the Figma Sınıfım / Yapay zekâ / Diğer tree", () => { +test("teacher's sidebar keeps the Figma Sınıfım / Yapay zekâ / Diğer tree plus every backed page", () => { expect( visibleNavGroups("teacher").map((group) => ({ id: group.id, items: group.items.map((item) => item.id), })), ).toEqual([ - { id: "my-classroom", items: ["my-classes", "my-schedule", "student-attendance", "homework", "exams", "whiteboards"] }, + { + id: "my-classroom", + items: [ + "my-classes", + "my-schedule", + "courses", + "student-attendance", + "student-marks", + "student-pomodoros", + "homework", + "exams", + "question-bank", + "questions", + "notes", + "whiteboards", + ], + }, { id: "ai", items: ["student-analysis", "pending-approvals", "question-generation", "sound-studio"] }, - { id: "other", items: ["parent-communication", "work", "settings-teacher"] }, + { id: "other", items: ["parent-communication", "appointments", "events", "meals", "work", "settings-teacher"] }, ]); }); -test("student's sidebar mirrors the Figma Çalışma / Yapay zekâ / Diğer tree", () => { +test("student's sidebar keeps the Figma Çalışma / Yapay zekâ / Diğer tree plus every backed page", () => { expect( visibleNavGroups("student").map((group) => ({ id: group.id, items: group.items.map((item) => item.id), })), ).toEqual([ - { id: "study", items: ["study-plan", "topic-mastery", "exam-results", "my-homework", "whiteboards", "pomodoro"] }, + { id: "study", items: ["study-plan", "topic-mastery", "exam-results", "my-homework", "courses", "notes", "questions", "whiteboards", "pomodoro"] }, { id: "ai", items: ["celebi", "sound-studio"] }, - { id: "other", items: ["calendar", "settings-student"] }, + { id: "other", items: ["calendar", "events", "messages", "appointments", "meals", "settings-student"] }, ]); }); -test("parent's sidebar mirrors the Figma Öğrencim / Kurum tree", () => { +test("parent's sidebar keeps the Figma Öğrencim / Kurum tree plus every backed page", () => { expect( visibleNavGroups("parent").map((group) => ({ id: group.id, @@ -88,18 +114,40 @@ test("parent's sidebar mirrors the Figma Öğrencim / Kurum tree", () => { })), ).toEqual([ { id: "my-student", items: ["progress-report", "absence", "child-exam-results", "child-study-plan"] }, - { id: "institution", items: ["payment-statement", "appointments", "settings-parent"] }, + { id: "institution", items: ["payment-statement", "appointments", "messages", "calendar", "events", "meals", "settings-parent"] }, ]); }); -test("appointments is a parent-only sidebar entry, matching the Figma parent screen", () => { - expect(visibleNavGroups("parent").flatMap((g) => g.items).map((i) => i.to)).toContain("/appointments"); - for (const role of ["student", "teacher", "manager", "admin"] as const) { - const paths = [...primaryNavItems(role).map((i) => i.to), ...visibleNavGroups(role).flatMap((g) => g.items.map((i) => i.to))]; - expect(paths).not.toContain("/appointments"); +test("appointments and meals are reachable from every role's sidebar", () => { + for (const role of ["student", "parent", "teacher", "manager", "admin"] as const) { + const paths = visibleNavGroups(role).flatMap((g) => g.items.map((i) => i.to)); + expect(paths).toContain("/appointments"); + expect(paths).toContain("/meals"); } }); +test("parent's child entries open the progress page on their own tab, not a placeholder", () => { + const items = visibleNavGroups("parent").flatMap((g) => g.items); + expect(items.filter((i) => i.soon).map((i) => i.id)).toEqual([]); + expect(routeNavItem("/students/attendance", "parent")?.id).toBe("absence"); + expect(routeNavItem("/students/exams", "parent")?.id).toBe("child-exam-results"); + expect(routeNavItem("/students/study", "parent")?.id).toBe("child-study-plan"); + expect(routeNavItem("/students", "parent")?.id).toBe("progress-report"); +}); + +test("license modules is a real admin page and the work log includes admin", () => { + const admin = visibleNavGroups("admin").flatMap((g) => g.items); + const licenseModules = admin.find((i) => i.id === "license-modules"); + expect(licenseModules?.to).toBe("/management/modules"); + expect(licenseModules?.soon).toBeFalsy(); + expect(admin.map((i) => i.to)).toContain("/work"); + expect(admin.filter((i) => i.id.endsWith("-roster")).map((i) => [i.to, i.soon ?? false])).toEqual([ + ["/management/students", false], + ["/management/teachers", false], + ]); + expect(visibleNavGroups("manager").flatMap((g) => g.items).map((i) => i.id)).not.toContain("license-modules"); +}); + test("entries with no backend yet are flagged soon and route to the shared placeholder", () => { const hezarfenZeka = visibleNavGroups("admin") .flatMap((g) => g.items) diff --git a/src/components/layout/nav-items.ts b/src/components/layout/nav-items.ts index ba3199e..329b19c 100644 --- a/src/components/layout/nav-items.ts +++ b/src/components/layout/nav-items.ts @@ -2,8 +2,10 @@ import type { Component } from "solid-js"; import type { Role } from "@/api/client"; import { IconArchive, + IconBook, IconBotSquare, IconBriefcase, + IconCalendar, IconCalendarDays, IconChalkboardTeacher, IconChart, @@ -16,6 +18,7 @@ import { IconHomework, IconHome, IconMessage, + IconNote, IconPackage, IconReportAnalytics, IconScan, @@ -94,13 +97,23 @@ const ADMIN_GROUPS: NavGroup[] = [ labelKey: "nav.group.operations", Icon: IconSchool, items: [ - { id: "students-roster", to: "/coming-soon/ogrenciler", labelKey: "nav.studentsRoster", Icon: IconUsers, soon: true, minRole: "manager" }, - { id: "teachers-roster", to: "/coming-soon/ogretmenler", labelKey: "nav.teachersRoster", Icon: IconChalkboardTeacher, soon: true, minRole: "manager" }, + { id: "students-roster", to: "/management/students", labelKey: "nav.studentsRoster", Icon: IconUsers, minRole: "manager" }, + { id: "teachers-roster", to: "/management/teachers", labelKey: "nav.teachersRoster", Icon: IconChalkboardTeacher, minRole: "manager" }, { id: "class-groups", to: "/management/classes", labelKey: "nav.classGroups", Icon: IconSchool, minRole: "teacher" }, + { id: "courses", to: "/courses", labelKey: "nav.courses", Icon: IconBook, module: "courses" }, + { id: "terms", to: "/management/terms", labelKey: "nav.terms", Icon: IconCalendar, minRole: "manager" }, { id: "schedule", to: "/calendar", labelKey: "nav.schedule", Icon: IconCalendarDays, minRole: "manager" }, + { id: "events", to: "/events", labelKey: "nav.events", Icon: IconCalendarDays, module: "events" }, { id: "student-attendance", to: "/management/student-attendance", labelKey: "nav.attendance", Icon: IconClipboardCheck, minRole: "teacher", module: "attendance" }, + { id: "student-marks", to: "/management/student-marks", labelKey: "nav.studentMarks", Icon: IconChart, minRole: "teacher", module: "marks" }, + { id: "student-pomodoros", to: "/management/pomodoros", labelKey: "nav.studentPomodoro", Icon: IconClock, minRole: "teacher", module: "pomodoro" }, + { id: "homework", to: "/homework", labelKey: "nav.homework", Icon: IconHomework, module: "homework" }, { id: "exams", to: "/exams", labelKey: "nav.exams", Icon: IconExam, minRole: "teacher", module: "exams" }, { id: "question-bank", to: "/question-bank", labelKey: "nav.questionBank", Icon: IconArchive, minRole: "teacher", module: "bank_questions" }, + { id: "questions", to: "/questions", labelKey: "nav.questions", Icon: IconHelpCircle, module: "questions" }, + { id: "notes", to: "/notes", labelKey: "nav.notes", Icon: IconNote, module: "notes" }, + { id: "whiteboards", to: "/whiteboards", labelKey: "nav.whiteboards", Icon: IconEdit, module: "boards" }, + { id: "appointments", to: "/appointments", labelKey: "nav.appointments", Icon: IconClock, module: "appointments" }, { id: "mock-exams", to: "/coming-soon/deneme-sinavlari", labelKey: "nav.mockExams", Icon: IconTarget, soon: true, minRole: "manager" }, { id: "optical-reading", to: "/coming-soon/optik-okuma", labelKey: "nav.opticalReading", Icon: IconScan, soon: true, minRole: "manager" }, { id: "payments-collection", to: "/management/payments", labelKey: "nav.payments", Icon: IconReportAnalytics, minRole: "manager", module: "payments" }, @@ -122,11 +135,12 @@ const ADMIN_GROUPS: NavGroup[] = [ Icon: IconUserCog, items: [ { id: "reports", to: "/coming-soon/raporlar", labelKey: "nav.reports", Icon: IconChartPie, soon: true, minRole: "manager" }, - { id: "license-modules", to: "/coming-soon/lisans-modulleri", labelKey: "nav.licenseModules", Icon: IconPackage, soon: true, minRole: "admin" }, + { id: "license-modules", to: "/management/modules", labelKey: "nav.licenseModules", Icon: IconPackage, minRole: "admin" }, { id: "users", to: "/admin/users", labelKey: "nav.users", Icon: IconUserCog, minRole: "admin" }, { id: "data-protection", to: "/coming-soon/kvkk-denetim", labelKey: "nav.dataProtection", Icon: IconShieldCheck, soon: true, minRole: "admin" }, { id: "school-meals", to: "/meals", labelKey: "nav.schoolMeals", Icon: IconUtensils, minRole: "manager", module: "meals" }, { id: "staff-work", to: "/management/staff-work", labelKey: "nav.staffWork", Icon: IconBriefcase, minRole: "manager", module: "work" }, + { id: "work", to: "/work", labelKey: "nav.work", Icon: IconClock, minRole: "teacher", module: "work" }, { id: "settings", to: "/management/settings", labelKey: "nav.settings", Icon: IconSettings, minRole: "manager" }, ], }, @@ -140,9 +154,15 @@ const TEACHER_GROUPS: NavGroup[] = [ items: [ { id: "my-classes", to: "/management/classes", labelKey: "nav.myClasses", Icon: IconSchool }, { id: "my-schedule", to: "/calendar", labelKey: "nav.mySchedule", Icon: IconCalendarDays }, + { id: "courses", to: "/courses", labelKey: "nav.courses", Icon: IconBook, module: "courses" }, { id: "student-attendance", to: "/management/student-attendance", labelKey: "nav.attendance", Icon: IconClipboardCheck, module: "attendance" }, + { id: "student-marks", to: "/management/student-marks", labelKey: "nav.studentMarks", Icon: IconChart, module: "marks" }, + { id: "student-pomodoros", to: "/management/pomodoros", labelKey: "nav.studentPomodoro", Icon: IconClock, module: "pomodoro" }, { id: "homework", to: "/homework", labelKey: "nav.homework", Icon: IconHomework, module: "homework" }, { id: "exams", to: "/exams", labelKey: "nav.exams", Icon: IconExam, module: "exams" }, + { id: "question-bank", to: "/question-bank", labelKey: "nav.questionBank", Icon: IconArchive, module: "bank_questions" }, + { id: "questions", to: "/questions", labelKey: "nav.questions", Icon: IconHelpCircle, module: "questions" }, + { id: "notes", to: "/notes", labelKey: "nav.notes", Icon: IconNote, module: "notes" }, { id: "whiteboards", to: "/whiteboards", labelKey: "nav.whiteboards", Icon: IconEdit, module: "boards" }, ], }, @@ -163,7 +183,10 @@ const TEACHER_GROUPS: NavGroup[] = [ Icon: IconMessage, items: [ { id: "parent-communication", to: "/messages", labelKey: "nav.parentCommunication", Icon: IconMessage, module: "messages" }, - { id: "work", to: "/work", labelKey: "nav.work", Icon: IconClock, minRole: "teacher", maxRole: "manager", module: "work" }, + { id: "appointments", to: "/appointments", labelKey: "nav.appointments", Icon: IconClock, module: "appointments" }, + { id: "events", to: "/events", labelKey: "nav.events", Icon: IconCalendarDays, module: "events" }, + { id: "meals", to: "/meals", labelKey: "nav.meals", Icon: IconUtensils, module: "meals" }, + { id: "work", to: "/work", labelKey: "nav.work", Icon: IconBriefcase, minRole: "teacher", module: "work" }, settingsAction("settings-teacher"), ], }, @@ -179,6 +202,9 @@ const STUDENT_GROUPS: NavGroup[] = [ { id: "topic-mastery", to: "/marks", labelKey: "nav.topicMastery", Icon: IconChart, exactRole: "student", module: "marks" }, { id: "exam-results", to: "/exams", labelKey: "nav.examResults", Icon: IconExam, module: "exams" }, { id: "my-homework", to: "/homework", labelKey: "nav.myHomework", Icon: IconHomework, module: "homework" }, + { id: "courses", to: "/courses", labelKey: "nav.courses", Icon: IconBook, module: "courses" }, + { id: "notes", to: "/notes", labelKey: "nav.notes", Icon: IconNote, module: "notes" }, + { id: "questions", to: "/questions", labelKey: "nav.questions", Icon: IconHelpCircle, module: "questions" }, { id: "whiteboards", to: "/whiteboards", labelKey: "nav.whiteboards", Icon: IconEdit, module: "boards" }, { id: "pomodoro", to: "/pomodoro", labelKey: "nav.pomodoro", Icon: IconClock, exactRole: "student", module: "pomodoro" }, ], @@ -195,6 +221,10 @@ const STUDENT_GROUPS: NavGroup[] = [ Icon: IconCalendarDays, items: [ { id: "calendar", to: "/calendar", labelKey: "nav.mySchedule", Icon: IconCalendarDays }, + { id: "events", to: "/events", labelKey: "nav.events", Icon: IconCalendarDays, module: "events" }, + { id: "messages", to: "/messages", labelKey: "nav.messages", Icon: IconMessage, module: "messages" }, + { id: "appointments", to: "/appointments", labelKey: "nav.appointments", Icon: IconClock, module: "appointments" }, + { id: "meals", to: "/meals", labelKey: "nav.meals", Icon: IconUtensils, module: "meals" }, settingsAction("settings-student"), ], }, @@ -207,9 +237,9 @@ const PARENT_GROUPS: NavGroup[] = [ Icon: IconUsers, items: [ { id: "progress-report", to: "/students", labelKey: "nav.progressReport", Icon: IconReportAnalytics, exactRole: "parent" }, - { id: "absence", to: "/coming-soon/devamsizlik", labelKey: "nav.absence", Icon: IconClipboardCheck, soon: true }, - { id: "child-exam-results", to: "/coming-soon/sinav-sonuclari-veli", labelKey: "nav.childExamResults", Icon: IconExam, soon: true }, - { id: "child-study-plan", to: "/coming-soon/calisma-plani", labelKey: "nav.childStudyPlan", Icon: IconClock, soon: true }, + { id: "absence", to: "/students/attendance", labelKey: "nav.absence", Icon: IconClipboardCheck, exactRole: "parent", module: "attendance" }, + { id: "child-exam-results", to: "/students/exams", labelKey: "nav.childExamResults", Icon: IconExam, exactRole: "parent", module: "marks" }, + { id: "child-study-plan", to: "/students/study", labelKey: "nav.childStudyPlan", Icon: IconClock, exactRole: "parent", module: "pomodoro" }, ], }, { @@ -219,6 +249,10 @@ const PARENT_GROUPS: NavGroup[] = [ items: [ { id: "payment-statement", to: "/payments", labelKey: "nav.payments", Icon: IconReportAnalytics, exactRole: "parent", module: "payments" }, { id: "appointments", to: "/appointments", labelKey: "nav.appointmentsAndCommunication", Icon: IconClock, exactRole: "parent", module: "appointments" }, + { id: "messages", to: "/messages", labelKey: "nav.messages", Icon: IconMessage, module: "messages" }, + { id: "calendar", to: "/calendar", labelKey: "nav.mySchedule", Icon: IconCalendarDays }, + { id: "events", to: "/events", labelKey: "nav.events", Icon: IconCalendarDays, module: "events" }, + { id: "meals", to: "/meals", labelKey: "nav.meals", Icon: IconUtensils, module: "meals" }, settingsAction("settings-parent"), ], }, diff --git a/src/components/modules/module-catalog-grid.tsx b/src/components/modules/module-catalog-grid.tsx new file mode 100644 index 0000000..fb3c959 --- /dev/null +++ b/src/components/modules/module-catalog-grid.tsx @@ -0,0 +1,112 @@ +import { For, Show } from "solid-js"; +import type { ModuleCatalog } from "@/api/client"; +import { Badge } from "@/components/ui/badge"; +import { moduleLabel, packageLabel } from "@/lib/module-labels"; +import { useT } from "@/stores/preferences-context"; + +/** + * The deployment catalog grouped by package, each module marked on/off for one + * school. Read-only without `onToggle` (a school admin's view); with it, every + * module row becomes a switch (the builder's switchboard). + */ +export function ModuleCatalogGrid(props: { + catalog: ModuleCatalog; + enabled: readonly string[]; + onToggle?: (module: string, next: boolean) => void; + onTogglePackage?: (pkg: string, next: boolean) => void; + disabled?: boolean; + /** One column regardless of viewport — for narrow hosts like a SidePanel. */ + stacked?: boolean; +}) { + const t = useT(); + const isOn = (module: string) => props.enabled.includes(module); + const requiresOf = (module: string) => props.catalog.modules.find((entry) => entry.module === module)?.requires ?? []; + + return ( +
+ + {(pkg) => { + const onCount = () => pkg.modules.filter(isOn).length; + return ( +
+
+
+

{packageLabel(pkg.package, t)}

+

{t("modules.enabledCount", { on: String(onCount()), total: String(pkg.modules.length) })}

+
+ + {(toggle) => ( +
+ + +
+ )} +
+
+
    + + {(module) => ( +
  • +
    +

    {moduleLabel(module, t)}

    + 0}> +

    + {t("modules.requires")}: {requiresOf(module).map((name) => moduleLabel(name, t)).join(", ")} +

    +
    +
    + + {isOn(module) ? t("modules.on") : t("modules.off")} + + } + > + {(toggle) => ( + + )} + +
  • + )} +
    +
+
+ ); + }} +
+
+ ); +} diff --git a/src/components/pomodoro/pomodoro-log-view.tsx b/src/components/pomodoro/pomodoro-log-view.tsx new file mode 100644 index 0000000..3cf9f68 --- /dev/null +++ b/src/components/pomodoro/pomodoro-log-view.tsx @@ -0,0 +1,39 @@ +import { createMemo } from "solid-js"; +import type { ColumnDef } from "@tanstack/solid-table"; +import type { PomodoroLog, PomodoroSession } from "@/api/client"; +import { DataTable } from "@/components/ui/data-table"; +import { formatDateTime, formatDurationClock } from "@/lib/format"; +import { usePreferences, useT } from "@/stores/preferences-context"; + +/** A student's pomodoro log: lifetime focus total over the paged stint list. */ +export function PomodoroLogView(props: { log: PomodoroLog }) { + const t = useT(); + const { locale } = usePreferences(); + const columns = createMemo[]>(() => [ + { + accessorKey: "started_at", + header: t("pomodoro.startedAt"), + cell: (cell) => {formatDateTime(cell.row.original.started_at, locale())}, + }, + { + accessorKey: "finished_at", + header: t("pomodoro.finishedAt"), + cell: (cell) => {formatDateTime(cell.row.original.finished_at, locale())}, + }, + { + accessorKey: "duration_ms", + header: t("pomodoro.duration"), + cell: (cell) => {formatDurationClock(cell.row.original.duration_ms)}, + }, + ]); + + return ( +
+
+

{t("pomodoro.total")}

+

{formatDurationClock(props.log.total_focus_ms)}

+
+ +
+ ); +} diff --git a/src/components/users/roster-person-cell.tsx b/src/components/users/roster-person-cell.tsx new file mode 100644 index 0000000..05c3daf --- /dev/null +++ b/src/components/users/roster-person-cell.tsx @@ -0,0 +1,16 @@ +import type { PersonRef } from "@/api/client"; +import { UserAvatar } from "@/components/users/user-avatar"; +import { personLabel } from "@/lib/person"; + +/** Avatar initials, display name and @username — the first column of the ADM-02/ADM-08 rosters. */ +export function RosterPersonCell(props: { person: PersonRef }) { + return ( +
+ +
+

{personLabel(props.person)}

+

@{props.person.username}

+
+
+ ); +} diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index ad06053..eff215f 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -305,6 +305,123 @@ export type MessageKey = | "comingSoon.description" | "comingSoon.emptyTitle" | "comingSoon.emptyDescription" + | "roster.student" + | "roster.teacher" + | "roster.class" + | "roster.classAll" + | "roster.term" + | "roster.termAll" + | "roster.mastery" + | "roster.attendance" + | "roster.planAdherence" + | "roster.status" + | "roster.branch" + | "roster.weeklyLessons" + | "roster.suggestionAcceptance" + | "roster.tabAll" + | "roster.tabActive" + | "roster.tabNew" + | "roster.tabAtRisk" + | "roster.tabLeft" + | "roster.tabPermanent" + | "roster.tabContract" + | "roster.tabAdvisor" + | "roster.import" + | "roster.addStudent" + | "roster.addTeacher" + | "roster.studentsSubtitle" + | "roster.teachersSubtitle" + | "roster.searchStudents" + | "roster.searchTeachers" + | "roster.noTeachers" + | "builder.console" + | "builder.logout" + | "builder.loginTitle" + | "builder.loginSubtitle" + | "builder.backToSchoolLogin" + | "builder.operatorLogin" + | "builder.statusActive" + | "builder.statusSuspended" + | "builder.createSchool" + | "builder.createSchoolHint" + | "builder.slug" + | "builder.slugHint" + | "builder.schoolName" + | "builder.adminUsername" + | "builder.adminPassword" + | "builder.sellEverything" + | "builder.schools" + | "builder.schoolsSubtitle" + | "builder.status" + | "builder.modules" + | "builder.createdAt" + | "builder.suspend" + | "builder.activate" + | "builder.noSchools" + | "builder.deleteSchool" + | "builder.deleteSchoolWarning" + | "builder.enterSchool" + | "builder.enterSchoolHint" + | "builder.enterSuspendedHint" + | "builder.resetAdminPassword" + | "builder.resetAdminPasswordHint" + | "builder.newPassword" + | "builder.passwordResetDone" + | "builder.modulesHint" + | "builder.editSchool" + | "builder.editSchoolHint" + | "builder.suspendHint" + | "modules.subtitle" + | "modules.readOnlyHint" + | "modules.enabledCount" + | "modules.enableAll" + | "modules.disableAll" + | "modules.requires" + | "modules.on" + | "modules.off" + | "modules.module" + | "modules.active" + | "modules.unitPrice" + | "modules.activeSeats" + | "modules.annualAmount" + | "modules.annualTotal" + | "modules.tabOverview" + | "modules.tabUsage" + | "modules.tabInvoices" + | "modules.tabContract" + | "modules.downloadInvoices" + | "modules.addLicense" + | "modules.fullPackage" + | "modules.customPackage" + | "modules.renewal" + | "modules.recentInvoices" + | "modules.conflictRequires" + | "modules.conflictRequiredBy" + | "module.appointments" + | "module.attendance" + | "module.bank_questions" + | "module.boards" + | "module.chatbot" + | "module.classes" + | "module.course_notes" + | "module.courses" + | "module.events" + | "module.exams" + | "module.homework" + | "module.marks" + | "module.meals" + | "module.messages" + | "module.notes" + | "module.payments" + | "module.pomodoro" + | "module.questions" + | "module.sessions" + | "module.subjects" + | "module.work" + | "package.academics" + | "package.ai" + | "package.communication" + | "package.operations" | "nav.darkMode" | "rightPanel.messagesTitle" | "rightPanel.calendarTitle" @@ -2015,6 +2132,123 @@ const en: Dict = { "comingSoon.description": "This module is on its way — there is nothing to show here yet.", "comingSoon.emptyTitle": "Not available yet", "comingSoon.emptyDescription": "This part of Hezarfen is still being built. Check back soon.", + "roster.student": "Student", + "roster.teacher": "Teacher", + "roster.class": "Class", + "roster.classAll": "Class: All", + "roster.term": "Term", + "roster.termAll": "Term: All", + "roster.mastery": "Topic mastery", + "roster.attendance": "Attendance", + "roster.planAdherence": "Plan adherence", + "roster.status": "Status", + "roster.branch": "Branch", + "roster.weeklyLessons": "Weekly lessons", + "roster.suggestionAcceptance": "Suggestion acceptance", + "roster.tabAll": "All", + "roster.tabActive": "Active", + "roster.tabNew": "New enrolment", + "roster.tabAtRisk": "At risk", + "roster.tabLeft": "Left", + "roster.tabPermanent": "Permanent", + "roster.tabContract": "Contract", + "roster.tabAdvisor": "Advisor", + "roster.import": "Import", + "roster.addStudent": "Add student", + "roster.addTeacher": "Add teacher", + "roster.studentsSubtitle": "Every student in the school, with their class.", + "roster.teachersSubtitle": "Every teacher in the school and the classes they lead.", + "roster.searchStudents": "Search student name or username…", + "roster.searchTeachers": "Search teacher name or username…", + "roster.noTeachers": "No teachers yet.", + "builder.console": "Operator console", + "builder.logout": "Sign out", + "builder.loginTitle": "Operator sign-in", + "builder.loginSubtitle": "Manage the schools on this deployment.", + "builder.backToSchoolLogin": "Back to school sign-in", + "builder.operatorLogin": "Operator sign-in", + "builder.statusActive": "Active", + "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", + "builder.sellEverything": "Enable every module in the catalog", + "builder.schools": "Schools", + "builder.schoolsSubtitle": "Every school on this deployment", + "builder.status": "Status", + "builder.modules": "Modules", + "builder.createdAt": "Created", + "builder.suspend": "Suspend", + "builder.activate": "Activate", + "builder.noSchools": "No schools yet.", + "builder.deleteSchool": "Delete school", + "builder.deleteSchoolWarning": "All of this school's data and uploaded files are destroyed for good. This cannot be undone.", + "builder.enterSchool": "Enter school", + "builder.enterSchoolHint": "Signs this browser in as one of the school's admins for support. Your operator session ends.", + "builder.enterSuspendedHint": "A suspended school cannot be entered.", + "builder.resetAdminPassword": "Reset admin password", + "builder.resetAdminPasswordHint": "Sets a new password for an admin of this school and signs that account out everywhere.", + "builder.newPassword": "New password", + "builder.passwordResetDone": "Password reset. That admin's sessions were revoked.", + "builder.modulesHint": "Changes apply on the school's very next request.", + "builder.editSchool": "Edit school", + "builder.editSchoolHint": "Rename the school or change its status.", + "builder.suspendHint": "Suspension is immediate: every user of the school is refused, login included.", + "modules.subtitle": "Modular by design: the school has only the components it needs.", + "modules.readOnlyHint": "Modules are enabled or disabled by your Hezarfen provider.", + "modules.enabledCount": "{on} of {total} enabled", + "modules.enableAll": "Enable all", + "modules.disableAll": "Disable all", + "modules.requires": "Requires", + "modules.on": "On", + "modules.conflictRequires": "{module} needs {needed}, which is not enabled.", + "modules.conflictRequiredBy": "{module} cannot be turned off: {dependents} depend on it.", + "modules.module": "Module", + "modules.active": "Active", + "modules.unitPrice": "Unit price", + "modules.activeSeats": "Active seats", + "modules.annualAmount": "Annual amount", + "modules.annualTotal": "annual total", + "modules.tabOverview": "Overview", + "modules.tabUsage": "Usage", + "modules.tabInvoices": "Invoices", + "modules.tabContract": "Contract", + "modules.downloadInvoices": "Download invoices", + "modules.addLicense": "Add license", + "modules.fullPackage": "Full package", + "modules.customPackage": "Custom package", + "modules.renewal": "Renewal", + "modules.recentInvoices": "Recent invoices", + "modules.off": "Off", + "module.appointments": "Appointments", + "module.attendance": "Attendance", + "module.bank_questions": "Question bank", + "module.boards": "Board", + "module.chatbot": "Çelebi assistant", + "module.classes": "Classes", + "module.course_notes": "Course notes", + "module.courses": "Courses", + "module.events": "Events", + "module.exams": "Exams", + "module.homework": "Homework", + "module.marks": "Marks", + "module.meals": "Meals", + "module.messages": "Messages", + "module.notes": "Notebook", + "module.payments": "Payments", + "module.pomodoro": "Pomodoro", + "module.questions": "Question pool", + "module.sessions": "Lesson sessions", + "module.subjects": "Subjects", + "module.work": "Shift", + "package.academics": "Academics", + "package.ai": "AI", + "package.communication": "Communication", + "package.operations": "Operations", "nav.darkMode": "Dark mode", "parents.title": "My Students", "parents.subtitle": "Review academic records for the students linked to your account.", @@ -3713,6 +3947,123 @@ const tr: Dict = { "comingSoon.description": "Bu modül hazırlanıyor — henüz gösterecek bir şey yok.", "comingSoon.emptyTitle": "Henüz kullanıma açık değil", "comingSoon.emptyDescription": "Hezarfen'in bu bölümü hâlâ hazırlanıyor. Yakında tekrar bakın.", + "roster.student": "Öğrenci", + "roster.teacher": "Öğretmen", + "roster.class": "Sınıf", + "roster.classAll": "Sınıf: Tümü", + "roster.term": "Dönem", + "roster.termAll": "Dönem: Tümü", + "roster.mastery": "Konu yetkinliği", + "roster.attendance": "Devam", + "roster.planAdherence": "Plan uyumu", + "roster.status": "Durum", + "roster.branch": "Branş", + "roster.weeklyLessons": "Haftalık ders", + "roster.suggestionAcceptance": "Öneri kabulü", + "roster.tabAll": "Tümü", + "roster.tabActive": "Aktif", + "roster.tabNew": "Yeni kayıt", + "roster.tabAtRisk": "Risk altında", + "roster.tabLeft": "Ayrılan", + "roster.tabPermanent": "Kadrolu", + "roster.tabContract": "Ücretli", + "roster.tabAdvisor": "Danışman", + "roster.import": "İçe aktar", + "roster.addStudent": "Öğrenci ekle", + "roster.addTeacher": "Öğretmen ekle", + "roster.studentsSubtitle": "Kurumdaki tüm öğrenciler, sınıflarıyla birlikte.", + "roster.teachersSubtitle": "Kurumdaki öğretmenler ve sınıf öğretmenliği yaptıkları sınıflar.", + "roster.searchStudents": "Öğrenci adı veya kullanıcı adı ara…", + "roster.searchTeachers": "Öğretmen adı veya kullanıcı adı ara…", + "roster.noTeachers": "Henüz öğretmen yok.", + "builder.console": "Operatör konsolu", + "builder.logout": "Çıkış yap", + "builder.loginTitle": "Operatör girişi", + "builder.loginSubtitle": "Bu kurulumdaki okulları yönet.", + "builder.backToSchoolLogin": "Okul girişine dön", + "builder.operatorLogin": "Operatör girişi", + "builder.statusActive": "Aktif", + "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", + "builder.sellEverything": "Katalogdaki tüm modülleri aç", + "builder.schools": "Okullar", + "builder.schoolsSubtitle": "Bu kurulumdaki tüm okullar", + "builder.status": "Durum", + "builder.modules": "Modüller", + "builder.createdAt": "Oluşturulma", + "builder.suspend": "Askıya al", + "builder.activate": "Aktifleştir", + "builder.noSchools": "Henüz okul yok.", + "builder.deleteSchool": "Okulu sil", + "builder.deleteSchoolWarning": "Bu okulun tüm verileri ve yüklenen dosyaları kalıcı olarak silinir. Geri alınamaz.", + "builder.enterSchool": "Okula gir", + "builder.enterSchoolHint": "Destek için bu tarayıcıda okulun bir yöneticisi olarak oturum açar. Operatör oturumun kapanır.", + "builder.enterSuspendedHint": "Askıdaki bir okula girilemez.", + "builder.resetAdminPassword": "Yönetici şifresini sıfırla", + "builder.resetAdminPasswordHint": "Bu okulun bir yöneticisine yeni şifre verir ve o hesabın tüm oturumlarını kapatır.", + "builder.newPassword": "Yeni şifre", + "builder.passwordResetDone": "Şifre sıfırlandı. O yöneticinin oturumları kapatıldı.", + "builder.modulesHint": "Değişiklikler okulun bir sonraki isteğinde geçerli olur.", + "builder.editSchool": "Okulu düzenle", + "builder.editSchoolHint": "Okulun adını veya durumunu değiştir.", + "builder.suspendHint": "Askıya alma anında geçerlidir: okulun tüm kullanıcıları, giriş dahil, reddedilir.", + "modules.subtitle": "Modüler yapı: okulun yalnızca ihtiyaç duyduğu bileşenlere sahip olur.", + "modules.readOnlyHint": "Modüller Hezarfen sağlayıcın tarafından açılır veya kapatılır.", + "modules.enabledCount": "{total} modülden {on} açık", + "modules.enableAll": "Hepsini aç", + "modules.disableAll": "Hepsini kapat", + "modules.requires": "Gerektirir", + "modules.on": "Açık", + "modules.conflictRequires": "{module} için {needed} açık olmalı.", + "modules.conflictRequiredBy": "{module} kapatılamaz: {dependents} buna bağlı.", + "modules.module": "Modül", + "modules.active": "Etkin", + "modules.unitPrice": "Birim fiyat", + "modules.activeSeats": "Aktif lisans", + "modules.annualAmount": "Yıllık tutar", + "modules.annualTotal": "yıllık toplam", + "modules.tabOverview": "Genel bakış", + "modules.tabUsage": "Kullanım", + "modules.tabInvoices": "Faturalar", + "modules.tabContract": "Sözleşme", + "modules.downloadInvoices": "Faturaları indir", + "modules.addLicense": "Lisans ekle", + "modules.fullPackage": "Tam paket", + "modules.customPackage": "Özel paket", + "modules.renewal": "Yenileme", + "modules.recentInvoices": "Son faturalar", + "modules.off": "Kapalı", + "module.appointments": "Randevular", + "module.attendance": "Yoklama", + "module.bank_questions": "Soru bankası", + "module.boards": "Tahta", + "module.chatbot": "Çelebi asistanı", + "module.classes": "Sınıflar", + "module.course_notes": "Ders notları", + "module.courses": "Dersler", + "module.events": "Etkinlikler", + "module.exams": "Sınavlar", + "module.homework": "Ödevler", + "module.marks": "Notlar", + "module.meals": "Yemekler", + "module.messages": "Mesajlar", + "module.notes": "Defter", + "module.payments": "Ödemeler", + "module.pomodoro": "Pomodoro", + "module.questions": "Soru havuzu", + "module.sessions": "Ders oturumları", + "module.subjects": "Konular", + "module.work": "Mesai", + "package.academics": "Akademik", + "package.ai": "Yapay zekâ", + "package.communication": "İletişim", + "package.operations": "Operasyon", "nav.darkMode": "Karanlık mod", "parents.title": "Öğrencilerim", "parents.subtitle": "Size bağlı öğrencilerin akademik kayıtlarını inceleyin.", diff --git a/src/lib/module-labels.test.ts b/src/lib/module-labels.test.ts new file mode 100644 index 0000000..c0583b1 --- /dev/null +++ b/src/lib/module-labels.test.ts @@ -0,0 +1,22 @@ +import { ApiError } from "@/api/client"; +import { formatModuleError, moduleLabel } from "@/lib/module-labels"; + +const t = (key: string, params?: Record) => + params ? `${key}(${Object.entries(params).map(([k, v]) => `${k}=${v}`).join(",")})` : key; + +test("unknown modules fall back to their wire name", () => { + expect(moduleLabel("kantin", t)).toBe("kantin"); + expect(moduleLabel("exams", t)).toBe("module.exams"); +}); + +test("a missing-requirement 409 names every violation with localized modules", () => { + const err = new ApiError(409, "conflict: exams requires courses, which is not enabled; exams requires subjects, which is not enabled"); + expect(formatModuleError(err, t)).toBe( + "modules.conflictRequires(module=module.exams,needed=module.courses) modules.conflictRequires(module=module.exams,needed=module.subjects)", + ); +}); + +test("a required-by 409 lists the dependents", () => { + const err = new ApiError(409, "courses is required by exams, subjects"); + expect(formatModuleError(err, t)).toBe("modules.conflictRequiredBy(module=module.courses,dependents=module.exams, module.subjects)"); +}); diff --git a/src/lib/module-labels.ts b/src/lib/module-labels.ts new file mode 100644 index 0000000..be66c02 --- /dev/null +++ b/src/lib/module-labels.ts @@ -0,0 +1,69 @@ +import { ApiError, formatApiError } from "@/api/client"; +import type { MessageKey } from "@/i18n/messages"; + +type Translate = (key: MessageKey, params?: Record) => string; + +const MODULE_KEYS: Record = { + appointments: "module.appointments", + attendance: "module.attendance", + bank_questions: "module.bank_questions", + boards: "module.boards", + chatbot: "module.chatbot", + classes: "module.classes", + course_notes: "module.course_notes", + courses: "module.courses", + events: "module.events", + exams: "module.exams", + homework: "module.homework", + marks: "module.marks", + meals: "module.meals", + messages: "module.messages", + notes: "module.notes", + payments: "module.payments", + pomodoro: "module.pomodoro", + questions: "module.questions", + sessions: "module.sessions", + subjects: "module.subjects", + work: "module.work", +}; + +const PACKAGE_KEYS: Record = { + academics: "package.academics", + ai: "package.ai", + communication: "package.communication", + operations: "package.operations", +}; + +/** Localized module name; a module newer than this table falls back to its wire name. */ +export function moduleLabel(module: string, t: Translate): string { + const key = MODULE_KEYS[module]; + return key ? t(key) : module; +} + +export function packageLabel(pkg: string, t: Translate): string { + const key = PACKAGE_KEYS[pkg]; + return key ? t(key) : pkg; +} + +/** + * A module write refused with 409 names its broken dependencies in fixed + * English (module.rs `validate`, builder.rs `refuse_if_needed`); render them + * with localized module names instead of the generic error line. + */ +export function formatModuleError(err: unknown, t: Translate): string { + if (err instanceof ApiError && err.status === 409) { + const text = err.message.replace(/^conflict:\s*/i, ""); + const missing = [...text.matchAll(/([a-z_]+) requires ([a-z_]+), which is not enabled/g)]; + if (missing.length > 0) { + return missing + .map((match) => t("modules.conflictRequires", { module: moduleLabel(match[1], t), needed: moduleLabel(match[2], t) })) + .join(" "); + } + const requiredBy = text.match(/^([a-z_]+) is required by ([a-z_, ]+)$/); + if (requiredBy) { + const dependents = requiredBy[2].split(",").map((name) => moduleLabel(name.trim(), t)).join(", "); + return t("modules.conflictRequiredBy", { module: moduleLabel(requiredBy[1], t), dependents }); + } + } + return formatApiError(err); +} diff --git a/src/pages/builder-login-page.tsx b/src/pages/builder-login-page.tsx new file mode 100644 index 0000000..5b47b95 --- /dev/null +++ b/src/pages/builder-login-page.tsx @@ -0,0 +1,123 @@ +import { Link, Navigate, useNavigate } from "@tanstack/solid-router"; +import { Show, createSignal } from "solid-js"; +import { postBuilderLogin } from "@/api/builder"; +import { ApiError, formatApiError, formatApiErrorMessage } from "@/api/client"; +import { LogoMark } from "@/components/brand/logo-mark"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { PageSpinner } from "@/components/ui/page-spinner"; +import { useAuth } from "@/stores/auth-context"; +import { BuilderProvider, useBuilder } from "@/stores/builder-context"; +import { useT } from "@/stores/preferences-context"; + +// Backend BuilderCredentials bounds (hezarfen_backend src/web/builder.rs). +const MIN_USERNAME_LEN = 3; +const MAX_USERNAME_LEN = 32; +const MIN_PASSWORD_LEN = 6; +const MAX_PASSWORD_LEN = 128; + +export default function BuilderLoginPage() { + return ( + + + + ); +} + +function BuilderLoginGate() { + const session = useBuilder(); + return ( + }> + }> + + + + ); +} + +function BuilderLoginForm() { + const auth = useAuth(); + const session = useBuilder(); + const navigate = useNavigate(); + const t = useT(); + const [username, setUsername] = createSignal(""); + const [password, setPassword] = createSignal(""); + const [error, setError] = createSignal(""); + const [pending, setPending] = createSignal(false); + + const submit = async (event: SubmitEvent) => { + event.preventDefault(); + setError(""); + setPending(true); + try { + await postBuilderLogin({ username: username().trim(), password: password() }); + // The builder cookie replaced any school session this browser held. + await auth.refresh(); + session.refresh(); + void navigate({ to: "/builder" }); + } catch (err) { + setError( + err instanceof ApiError && err.status === 401 + ? formatApiErrorMessage("invalid credentials") + : formatApiError(err), + ); + } finally { + setPending(false); + } + }; + + return ( +
+
+
+
+ +
+

{t("builder.loginTitle")}

+

{t("builder.loginSubtitle")}

+
+
+
+ + setUsername(e.currentTarget.value)} + /> +
+
+ + setPassword(e.currentTarget.value)} + /> +
+ +

{error()}

+
+ +
+

+ + {t("builder.backToSchoolLogin")} + +

+
+
+ ); +} diff --git a/src/pages/builder-school-detail-page.tsx b/src/pages/builder-school-detail-page.tsx new file mode 100644 index 0000000..d466369 --- /dev/null +++ b/src/pages/builder-school-detail-page.tsx @@ -0,0 +1,254 @@ +import { Show, Suspense, createEffect, createResource, createSignal } from "solid-js"; +import { useNavigate, useParams } from "@tanstack/solid-router"; +import { getModulesCatalog } from "@/api/modules"; +import { + deleteSchoolBySlug, + deleteSchoolModule, + getSchoolBySlug, + getSchoolModules, + patchSchoolBySlug, + patchSchoolModules, + postSchoolModule, +} from "@/api/schools"; +import { formatApiError, type SchoolStatus } from "@/api/client"; +import { PageHeader } from "@/components/layout/page-header"; +import { BuilderGuard } from "@/components/builder/builder-guard"; +import { BuilderHeader } from "@/components/builder/builder-header"; +import { SchoolAdminAccessPanel, type AdminAccessMode } from "@/components/builder/school-admin-access-panel"; +import { SchoolStatusBadge } from "@/components/builder/school-status-badge"; +import { ModuleCatalogGrid } from "@/components/modules/module-catalog-grid"; +import { formatModuleError } from "@/lib/module-labels"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; +import { ErrorAlert } from "@/components/ui/error-alert"; +import { IconEdit, IconExternalLink, IconLock, IconTrash } from "@/components/ui/icons"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { PageSpinner } from "@/components/ui/page-spinner"; +import { Select } from "@/components/ui/select"; +import { SidePanel } from "@/components/ui/side-panel"; +import { createFlash } from "@/lib/flash"; +import { formatDateTime } from "@/lib/format"; +import { useAuth } from "@/stores/auth-context"; +import { BuilderProvider } from "@/stores/builder-context"; +import { usePreferences, useT } from "@/stores/preferences-context"; + +export default function BuilderSchoolDetailPage() { + return ( + + + + + + ); +} + +function BuilderSchoolDetailContent() { + const t = useT(); + const { locale } = usePreferences(); + const auth = useAuth(); + const navigate = useNavigate(); + const params = useParams({ from: "/builder/schools/$slug" }); + const slug = () => params().slug; + + const [school, { refetch: refetchSchool }] = createResource(slug, (value) => getSchoolBySlug(value)); + const [catalog] = createResource(() => getModulesCatalog()); + const [modules] = createResource(slug, (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. + const [enabled, setEnabled] = createSignal([]); + createEffect(() => { + const value = modules(); + if (value) setEnabled(value.enabled); + }); + const [modulesSaving, setModulesSaving] = createSignal(false); + const [modulesError, setModulesError] = createSignal(""); + + const [editOpen, setEditOpen] = createSignal(false); + const [name, setName] = createSignal(""); + const [status, setStatus] = createSignal("active"); + const [editError, setEditError] = createSignal(""); + const [accessMode, setAccessMode] = createSignal(null); + const [deleteOpen, setDeleteOpen] = createSignal(false); + const [error, setError] = createSignal(""); + const [flash, setFlash] = createFlash(); + + const writeModules = async (write: () => Promise<{ enabled: string[] }>) => { + if (modulesSaving()) return; + setModulesSaving(true); + setModulesError(""); + try { + const next = await write(); + setEnabled(next.enabled); + } catch (err) { + // A 409 names the broken dependency; the switch stays where it was. + setModulesError(formatModuleError(err, t)); + } finally { + setModulesSaving(false); + } + }; + + const openEdit = () => { + const current = school(); + if (!current) return; + setName(current.name); + setStatus(current.status); + setEditError(""); + setEditOpen(true); + }; + + const saveEdit = async (event: SubmitEvent) => { + event.preventDefault(); + setEditError(""); + try { + await patchSchoolBySlug(slug(), { name: name().trim(), status: status() }); + setEditOpen(false); + await refetchSchool(); + setFlash(t("common.saved")); + } catch (err) { + setEditError(formatApiError(err)); + } + }; + + return ( +
+ + }> + + void refetchSchool()} /> + + + {(current) => ( + <> + + + + + + +
+ } + /> + + {flash()} + + + {error()} + + +
+
+

{t("builder.modules")}

+

{t("builder.modulesHint")}

+
+ + {modulesError()} + + + + + + {(value) => ( + + void writeModules(() => (next ? postSchoolModule(slug(), module) : deleteSchoolModule(slug(), module))) + } + onTogglePackage={(pkg, next) => + void writeModules(() => patchSchoolModules(slug(), next ? { enable_packages: [pkg] } : { disable_packages: [pkg] })) + } + /> + )} + +
+ + )} + + + + +
+ + {editError()} + +
+ + setName(e.currentTarget.value)} /> +
+
+ + +

{t("builder.suspendHint")}

+
+
+ + +
+
+
+ + setAccessMode(null)} + onPasswordReset={() => { + setAccessMode(null); + setFlash(t("builder.passwordResetDone")); + }} + onEntered={async () => { + setAccessMode(null); + // The builder cookie is gone; this browser is now that admin. + await auth.refresh(); + void navigate({ to: "/" }); + }} + /> + + { + try { + await deleteSchoolBySlug(slug()); + void navigate({ to: "/builder" }); + } catch (err) { + setError(formatApiError(err)); + } finally { + setDeleteOpen(false); + } + }} + /> + + ); +} diff --git a/src/pages/builder-schools-page.tsx b/src/pages/builder-schools-page.tsx new file mode 100644 index 0000000..38d82f0 --- /dev/null +++ b/src/pages/builder-schools-page.tsx @@ -0,0 +1,175 @@ +import { Show, Suspense, createMemo, createResource, createSignal } from "solid-js"; +import { useNavigate } from "@tanstack/solid-router"; +import type { ColumnDef } from "@tanstack/solid-table"; +import { deleteSchoolBySlug, getSchools, patchSchoolBySlug } from "@/api/schools"; +import { formatApiError, type School } from "@/api/client"; +import { BuilderGuard } from "@/components/builder/builder-guard"; +import { BuilderHeader } from "@/components/builder/builder-header"; +import { CreateSchoolPanel } from "@/components/builder/create-school-panel"; +import { SchoolStatusBadge } from "@/components/builder/school-status-badge"; +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 { ErrorAlert } from "@/components/ui/error-alert"; +import { IconEye, IconLock, IconPlus, IconRotateCcw, IconTrash } from "@/components/ui/icons"; +import { TableRowActions } from "@/components/ui/table-row-actions"; +import { createFlash } from "@/lib/flash"; +import { formatDateTime } from "@/lib/format"; +import { BuilderProvider } from "@/stores/builder-context"; +import { usePreferences, useT } from "@/stores/preferences-context"; + +const SCHOOL_PAGE_SIZE = 15; + +export default function BuilderSchoolsPage() { + return ( + + + + + + ); +} + +function BuilderSchoolsContent() { + const t = useT(); + const { locale } = usePreferences(); + const navigate = useNavigate(); + const [list, { refetch }] = createResource(async () => (await getSchools()).items); + const [createOpen, setCreateOpen] = createSignal(false); + const [deleteTarget, setDeleteTarget] = createSignal(null); + const [error, setError] = createSignal(""); + const [flash, setFlash] = createFlash(); + + const open = (school: School) => void navigate({ to: "/builder/schools/$slug", params: { slug: school.slug } }); + + const setStatus = async (school: School, status: School["status"]) => { + setError(""); + try { + await patchSchoolBySlug(school.slug, { status }); + await refetch(); + setFlash(t("common.saved")); + } catch (err) { + setError(formatApiError(err)); + } + }; + + const columns = createMemo[]>(() => [ + { + accessorKey: "name", + header: t("builder.schoolName"), + cell: (cell) => {cell.row.original.name}, + }, + { + accessorKey: "slug", + header: t("builder.slug"), + cell: (cell) => {cell.row.original.slug}, + }, + { + accessorKey: "status", + header: t("builder.status"), + cell: (cell) => , + }, + { + id: "modules", + header: t("builder.modules"), + meta: { align: "right", cellClass: "mono tabular-nums" }, + cell: (cell) => cell.row.original.modules.length, + }, + { + accessorKey: "created_at", + header: t("builder.createdAt"), + cell: (cell) => {formatDateTime(cell.row.original.created_at, locale())}, + }, + { + id: "actions", + header: t("common.actions"), + meta: { headerClass: "w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap" }, + cell: (cell) => ( + , onSelect: () => open(cell.row.original) }, + cell.row.original.status === "active" + ? { label: t("builder.suspend"), icon: , onSelect: () => void setStatus(cell.row.original, "suspended") } + : { label: t("builder.activate"), icon: , onSelect: () => void setStatus(cell.row.original, "active") }, + { label: t("common.delete"), icon: , destructive: true, onSelect: () => setDeleteTarget(cell.row.original) }, + ]} + /> + ), + }, + ]); + + return ( +
+ + + {flash()} + + + {error()} + + +
+ }> + + void refetch()} /> + + + setCreateOpen(true)}> + + {t("builder.createSchool")} + + } + columns={columns()} + data={list() ?? []} + tableClass="min-w-176" + empty={t("builder.noSchools")} + filterColumn="name" + enablePagination + pageSize={SCHOOL_PAGE_SIZE} + onRowClick={open} + /> + + +
+ + { + setCreateOpen(false); + setFlash(t("common.created")); + void refetch(); + open(school); + }} + /> + + !value && setDeleteTarget(null)} + title={t("builder.deleteSchool")} + description={t("builder.deleteSchoolWarning")} + variant="destructive" + summary={deleteTarget() ? `${deleteTarget()!.name} · ${deleteTarget()!.slug}` : ""} + onConfirm={async () => { + const school = deleteTarget(); + if (!school) return; + try { + await deleteSchoolBySlug(school.slug); + await refetch(); + setFlash(t("common.deleted")); + } catch (err) { + setError(formatApiError(err)); + } finally { + setDeleteTarget(null); + } + }} + /> +
+ ); +} diff --git a/src/pages/coming-soon-page.tsx b/src/pages/coming-soon-page.tsx index 331d134..84da871 100644 --- a/src/pages/coming-soon-page.tsx +++ b/src/pages/coming-soon-page.tsx @@ -18,17 +18,11 @@ const COMING_SOON_LABELS: Record = { "deneme-sinavlari": "nav.mockExams", "optik-okuma": "nav.opticalReading", raporlar: "nav.reports", - "lisans-modulleri": "nav.licenseModules", "kvkk-denetim": "nav.dataProtection", - ogrenciler: "nav.studentsRoster", - ogretmenler: "nav.teachersRoster", "ogrenci-analizi": "nav.studentAnalysis", "bekleyen-onaylar": "nav.pendingApprovals", "soru-uretimi": "nav.questionGeneration", "calisma-programim": "nav.studyPlan", - devamsizlik: "nav.absence", - "sinav-sonuclari-veli": "nav.childExamResults", - "calisma-plani": "nav.childStudyPlan", }; export default function ComingSoonPage() { diff --git a/src/pages/dashboard-page.test.tsx b/src/pages/dashboard-page.test.tsx index 6123ec2..242ecd1 100644 --- a/src/pages/dashboard-page.test.tsx +++ b/src/pages/dashboard-page.test.tsx @@ -35,6 +35,10 @@ const DAY = 24 * 60 * 60 * 1000; const page = (items: T[]) => ({ items, total: items.length, limit: 50, offset: 0 }); const course = { id: "course-1", title: "Algebra", capacity: 24 }; +vi.mock("@/stores/modules-context", () => ({ + useModules: () => ({ enabled: () => null, isEnabled: () => true, refresh: () => {} }), +})); +vi.mock("@/api/modules", () => ({ getModulesCatalog: async () => ({ modules: [], packages: [] }) })); vi.mock("@/api/time/getTime", () => ({ getTime: async () => ({ now }) })); vi.mock("@/api/courses", () => ({ getCourses: async () => page([course]), diff --git a/src/pages/dashboard-page.tsx b/src/pages/dashboard-page.tsx index 721efe7..7c11e0c 100644 --- a/src/pages/dashboard-page.tsx +++ b/src/pages/dashboard-page.tsx @@ -37,6 +37,7 @@ import { IconSearch, IconUsers, IconUtensils, + IconPackage, } from "@/components/ui/icons"; import { PageSpinner } from "@/components/ui/page-spinner"; import type { MessageKey } from "@/i18n/messages"; @@ -44,7 +45,10 @@ import { cn } from "@/lib/cn"; import { formatDateTime } from "@/lib/format"; import { formatTry } from "@/lib/meals"; import { personLabel } from "@/lib/person"; +import { packageLabel } from "@/lib/module-labels"; import { hasMinRole } from "@/lib/roles"; +import { getModulesCatalog } from "@/api/modules"; +import { useModules } from "@/stores/modules-context"; import { useAuth } from "@/stores/auth-context"; import { usePreferences, useT } from "@/stores/preferences-context"; @@ -310,6 +314,28 @@ function DashboardContent() { })), ); + // The school's own entitlements per package: the catalog is deploy-constant, + // the enabled set is already in the shell's modules context. + const schoolModules = useModules(); + const [moduleCatalog] = createResource( + () => (isAdminHome() ? true : null), + () => getModulesCatalog().catch(() => null), + ); + const moduleQuickLinks = createMemo(() => { + const catalog = moduleCatalog(); + const enabled = schoolModules.enabled(); + if (!catalog || !enabled) return []; + return catalog.packages.map((pkg) => { + const on = pkg.modules.filter((module) => enabled.includes(module)); + return { + id: pkg.package, + primary: packageLabel(pkg.package, t), + secondary: `${on.length}/${pkg.modules.length}`, + Icon: IconPackage, + }; + }); + }); + // Hero search. `/users/search` is the only search endpoint the app has, so // this box only ever finds students — it never claims to search classes, // exams, or modules the way the Figma copy does. @@ -685,7 +711,12 @@ function DashboardContent() { empty={t("dashboard.quicklinks.empty")} onOpen={(row) => navigate({ to: "/management/classes/$id", params: { id: row.id } })} /> - + navigate({ to: "/management/modules" })} + /> diff --git a/src/pages/license-modules-page.tsx b/src/pages/license-modules-page.tsx new file mode 100644 index 0000000..ed982d0 --- /dev/null +++ b/src/pages/license-modules-page.tsx @@ -0,0 +1,172 @@ +import type { ColumnDef } from "@tanstack/solid-table"; +import { For, Show, Suspense, createMemo, createResource } from "solid-js"; +import { getModules, getModulesCatalog } from "@/api/modules"; +import { formatApiError } from "@/api/client"; +import { RouteGuard } from "@/components/layout/route-guard"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { ComingSoonBadge, ComingSoonPanel, ComingSoonValue } from "@/components/ui/coming-soon"; +import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; +import { ErrorAlert } from "@/components/ui/error-alert"; +import { IconDownload, IconPackage, IconPlus } from "@/components/ui/icons"; +import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { moduleLabel, packageLabel } from "@/lib/module-labels"; +import { useT } from "@/stores/preferences-context"; + +type ModuleRow = { module: string; package: string; requires: string[]; enabled: boolean }; + +export default function LicenseModulesPage() { + return ( + + + + ); +} + +// ADM-05. What the school has is real (GET /modules over the catalog); price, +// seat count, renewal and invoices belong to a billing API that does not +// exist, so those slots say "yakında". Selling a module is the operator's +// act on /builder, never a school admin's. +function LicenseModulesContent() { + const t = useT(); + const [data, { refetch }] = createResource(async () => { + const [catalog, mine] = await Promise.all([getModulesCatalog(), getModules()]); + const rows: ModuleRow[] = catalog.modules.map((entry) => ({ + module: entry.module, + package: entry.package, + requires: entry.requires, + enabled: mine.enabled.includes(entry.module), + })); + return { rows, packages: catalog.packages }; + }); + + const enabledCount = () => (data()?.rows ?? []).filter((row) => row.enabled).length; + const totalCount = () => data()?.rows.length ?? 0; + const isFull = () => totalCount() > 0 && enabledCount() === totalCount(); + const enabledPackages = () => + (data()?.packages ?? []) + .filter((pkg) => pkg.modules.some((module) => data()?.rows.find((row) => row.module === module)?.enabled)) + .map((pkg) => packageLabel(pkg.package, t)); + + const columns = createMemo[]>(() => [ + { + id: "module", + header: t("modules.module"), + cell: (cell) => ( +
+ + + +
+

{moduleLabel(cell.row.original.module, t)}

+

+ {packageLabel(cell.row.original.package, t)} + 0}> + {` · ${t("modules.requires")}: ${cell.row.original.requires.map((name) => moduleLabel(name, t)).join(", ")}`} + +

+
+
+ ), + }, + { + id: "status", + header: t("builder.status"), + cell: (cell) => ( + + {cell.row.original.enabled ? t("modules.active") : t("modules.off")} + + ), + }, + { id: "unitPrice", header: t("modules.unitPrice"), meta: { align: "right" }, enableSorting: false, cell: () => }, + { id: "seats", header: t("modules.activeSeats"), meta: { align: "right" }, enableSorting: false, cell: () => }, + { id: "annual", header: t("modules.annualAmount"), meta: { align: "right" }, enableSorting: false, cell: () => }, + ]); + + return ( +
+ + + {t("modules.tabOverview")} + + {(key) => ( + + {t(key)} + + + )} + + + + +
+
+

{t("nav.licenseModules")}

+

{t("modules.subtitle")}

+
+
+ + +
+
+ + }> + + void refetch()} /> + + + {(value) => ( + <> +
+
+
+
+

+ {isFull() ? t("modules.fullPackage") : t("modules.customPackage")} +

+ {t("modules.active")} +
+

{enabledPackages().join(" + ") || "—"}

+
+
+ +

{t("modules.annualTotal")}

+
+
+
+
+
+
+ {t("modules.enabledCount", { on: String(enabledCount()), total: String(totalCount()) })} + + {t("modules.renewal")}: + +
+
+ + + + + + )} +
+
+
+ ); +} diff --git a/src/pages/login-page.tsx b/src/pages/login-page.tsx index 6065353..6bf6f5e 100644 --- a/src/pages/login-page.tsx +++ b/src/pages/login-page.tsx @@ -154,6 +154,11 @@ function LoginForm() { {t("auth.register")}

+

+ + {t("builder.operatorLogin")} + +

); diff --git a/src/pages/my-students-page.tsx b/src/pages/my-students-page.tsx index d627b45..a3a5cbf 100644 --- a/src/pages/my-students-page.tsx +++ b/src/pages/my-students-page.tsx @@ -1,27 +1,39 @@ import { For, Match, Show, Suspense, Switch, createEffect, createMemo, createResource, createSignal, type Component } from "solid-js"; -import { useNavigate } from "@tanstack/solid-router"; +import { useLocation, useNavigate } from "@tanstack/solid-router"; import type { ColumnDef } from "@tanstack/solid-table"; import { getClassesByUserId } from "@/api/classes"; import { getMyStudents } from "@/api/parents"; +import { getPomodoroByUser } from "@/api/pomodoro"; import { getUserMarks } from "@/api/reports"; import { getUserAttendance } from "@/api/reports"; -import type { MarksReport, PersonRef } from "@/api/client"; +import { formatApiError, type MarksReport, type PersonRef } from "@/api/client"; import { HomeworkReportView } from "@/components/homework/homework-report-view"; import { RouteGuard } from "@/components/layout/route-guard"; import { PageHeader } from "@/components/layout/page-header"; import { EmptyState } from "@/components/ui/empty-state"; +import { ErrorAlert } from "@/components/ui/error-alert"; import { PageSpinner } from "@/components/ui/page-spinner"; import { SidePanel } from "@/components/ui/side-panel"; import { Button } from "@/components/ui/button"; import { DataTable, DataTableEmpty } from "@/components/ui/data-table"; import { personLabel } from "@/lib/person"; import { useT } from "@/stores/preferences-context"; -import { IconChart, IconChevronRight, IconClipboardCheck, IconExam, IconExternalLink, IconHomework, IconMessage } from "@/components/ui/icons"; +import { IconChart, IconChevronRight, IconClipboardCheck, IconClock, IconExam, IconExternalLink, IconHomework, IconMessage } from "@/components/ui/icons"; import { MarksReportView } from "@/components/marks/marks-report-view"; import { AttendanceReportView } from "@/components/attendance/attendance-report-view"; +import { PomodoroLogView } from "@/components/pomodoro/pomodoro-log-view"; +import { useModules } from "@/stores/modules-context"; import { examKindLabel } from "@/lib/exam-labels"; -type StudentTab = "marks" | "attendance" | "exams" | "homework"; +type StudentTab = "marks" | "attendance" | "exams" | "homework" | "study"; + +// /students opens a child on the progress report; the parent sidebar's +// Devamsızlık / Sınav sonuçları / Çalışma planı entries are the same page +// landing on another tab (/students/attendance, /students/exams, /students/study). +function tabFromPath(pathname: string): StudentTab { + const segment = pathname.split("/")[2]; + return segment === "attendance" || segment === "exams" || segment === "study" ? segment : "marks"; +} type CourseRow = MarksReport["courses"][number]; type ExamRow = CourseRow["results"][number] & { courseTitle: string }; @@ -41,7 +53,18 @@ export default function MyStudentsPage() { function MyStudentsContent() { const t = useT(); const [list] = createResource(async () => (await getMyStudents()).items); + const location = useLocation(); const [selectedStudent, setSelectedStudent] = createSignal(null); + const routeTab = () => tabFromPath(location().pathname); + // A parent with a single linked child has nothing to pick: open that child + // once, so a sidebar tab entry lands straight on its data. + let autoOpened = false; + createEffect(() => { + const items = list(); + if (autoOpened || !items || items.length !== 1) return; + autoOpened = true; + setSelectedStudent(items[0]); + }); return (
@@ -73,14 +96,15 @@ function MyStudentsContent() { - setSelectedStudent(null)} /> + setSelectedStudent(null)} />
); } -function StudentDetailPanel(props: { student: PersonRef | null; onClose: () => void }) { +function StudentDetailPanel(props: { student: PersonRef | null; initialTab: StudentTab; onClose: () => void }) { const t = useT(); const navigate = useNavigate(); + const modules = useModules(); const [activeTab, setActiveTab] = createSignal("marks"); const [marksRes] = createResource( @@ -99,8 +123,24 @@ function StudentDetailPanel(props: { student: PersonRef | null; onClose: () => v ); const studentClass = () => classesRes()?.[0] ?? null; + // Fetched only once the tab is opened: the pomodoro nest can be switched + // off per school, and the other tabs must not pay for it. + const [studyError, setStudyError] = createSignal(""); + const [pomodoroRes] = createResource( + () => (activeTab() === "study" ? props.student?.id : undefined), + async (id) => { + setStudyError(""); + try { + return await getPomodoroByUser(id, { limit: 50 }); + } catch (err) { + setStudyError(formatApiError(err)); + return null; + } + }, + ); + createEffect(() => { - if (props.student?.id) setActiveTab("marks"); + if (props.student?.id) setActiveTab(props.initialTab); }); const report = () => marksRes() ?? null; @@ -147,12 +187,13 @@ function StudentDetailPanel(props: { student: PersonRef | null; onClose: () => v // Ordered to match the Figma per-child screen set (Gelişim raporu → // Devamsızlık → Sınav sonuçları); "Ödevler" has no Figma screen of its own // but is kept — real, working functionality with nowhere else to live. - const tabs: Array<{ key: StudentTab; icon: Component<{ class?: string }>; label: string }> = [ + const tabs = createMemo; label: string }>>(() => [ { key: "marks", icon: IconChart, label: t("nav.progressReport") }, { key: "attendance", icon: IconClipboardCheck, label: t("nav.attendance") }, - { key: "exams", icon: IconExam, label: t("nav.examResults") }, + { key: "exams", icon: IconExam, label: t("nav.childExamResults") }, { key: "homework", icon: IconHomework, label: t("nav.homework") }, - ]; + ...(modules.isEnabled("pomodoro") ? [{ key: "study" as const, icon: IconClock, label: t("nav.childStudyPlan") }] : []), + ]); return ( !open && props.onClose()} title={props.student ? personLabel(props.student) : ""} description={`@${props.student?.username}`}> @@ -198,7 +239,7 @@ function StudentDetailPanel(props: { student: PersonRef | null; onClose: () => v
- + {(tab) => { const Icon = tab.icon; return ( @@ -233,6 +274,15 @@ function StudentDetailPanel(props: { student: PersonRef | null; onClose: () => v + + + + + + {(log) => } + + + }> diff --git a/src/pages/student-pomodoro-page.tsx b/src/pages/student-pomodoro-page.tsx index 9cc0042..caf44ee 100644 --- a/src/pages/student-pomodoro-page.tsx +++ b/src/pages/student-pomodoro-page.tsx @@ -2,18 +2,18 @@ import { Show, createMemo, createResource, createSignal } from "solid-js"; import type { ColumnDef } from "@tanstack/solid-table"; import { getPomodoroByUser } from "@/api/pomodoro"; import { getUserSearch } from "@/api/users"; -import type { PersonRef, PomodoroSession } from "@/api/client"; +import type { PersonRef } from "@/api/client"; import { ApiError, formatApiError } from "@/api/client"; import { RouteGuard } from "@/components/layout/route-guard"; +import { PomodoroLogView } from "@/components/pomodoro/pomodoro-log-view"; import { Alert } from "@/components/ui/alert"; import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; import { ErrorAlert } from "@/components/ui/error-alert"; import { IconEye } from "@/components/ui/icons"; import { SidePanel } from "@/components/ui/side-panel"; import { TableRowActions } from "@/components/ui/table-row-actions"; -import { formatDateTime, formatDurationClock } from "@/lib/format"; import { personLabel } from "@/lib/person"; -import { usePreferences, useT } from "@/stores/preferences-context"; +import { useT } from "@/stores/preferences-context"; const PAGE_SIZE = 10; @@ -27,7 +27,6 @@ export default function StudentPomodoroPage() { function StudentPomodoroContent() { const t = useT(); - const { locale } = usePreferences(); const [viewUser, setViewUser] = createSignal(null); const [error, setError] = createSignal(""); @@ -98,23 +97,6 @@ function StudentPomodoroContent() { ), }, ]); - const logColumns = createMemo[]>(() => [ - { - accessorKey: "started_at", - header: t("pomodoro.startedAt"), - cell: (cell) => {formatDateTime(cell.row.original.started_at, locale())}, - }, - { - accessorKey: "finished_at", - header: t("pomodoro.finishedAt"), - cell: (cell) => {formatDateTime(cell.row.original.finished_at, locale())}, - }, - { - accessorKey: "duration_ms", - header: t("pomodoro.duration"), - cell: (cell) => {formatDurationClock(cell.row.original.duration_ms)}, - }, - ]); return (
@@ -163,15 +145,7 @@ function StudentPomodoroContent() {

{t("common.loading")}

- {(p) => ( -
-
-

{t("pomodoro.total")}

-

{formatDurationClock(p().total_focus_ms)}

-
- -
- )} + {(p) => }
diff --git a/src/pages/students-roster-page.tsx b/src/pages/students-roster-page.tsx new file mode 100644 index 0000000..cce47a8 --- /dev/null +++ b/src/pages/students-roster-page.tsx @@ -0,0 +1,173 @@ +import { useNavigate } from "@tanstack/solid-router"; +import type { ColumnDef } from "@tanstack/solid-table"; +import { For, Show, Suspense, createMemo, createResource, createSignal } from "solid-js"; +import { getClassMembers, getClasses } from "@/api/classes"; +import { getTerms } from "@/api/terms"; +import { getUserSearch } from "@/api/users"; +import { formatApiError, type ClassGroup, type PersonRef } from "@/api/client"; +import { RouteGuard } from "@/components/layout/route-guard"; +import { RosterPersonCell } from "@/components/users/roster-person-cell"; +import { Button } from "@/components/ui/button"; +import { ComingSoonBadge, ComingSoonValue } from "@/components/ui/coming-soon"; +import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; +import { ErrorAlert } from "@/components/ui/error-alert"; +import { IconEye, IconPlus, IconUploadCloud } from "@/components/ui/icons"; +import { Select } from "@/components/ui/select"; +import { TableRowActions } from "@/components/ui/table-row-actions"; +import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { useT } from "@/stores/preferences-context"; + +const ROSTER_PAGE_SIZE = 10; + +type StudentRow = { person: PersonRef; classes: ClassGroup[] }; + +export default function StudentsRosterPage() { + return ( + + + + ); +} + +// ADM-02. The roster, class and term are real; topic mastery, plan adherence +// and the risk status are AI/analytics fields no endpoint serves, so their +// columns keep the design's slot and say "yakında" instead of a number. +function StudentsRosterContent() { + const t = useT(); + const navigate = useNavigate(); + const [classFilter, setClassFilter] = createSignal(""); + const [termFilter, setTermFilter] = createSignal(""); + + const [data, { refetch }] = createResource(async () => { + const [students, classes, terms] = await Promise.all([ + getUserSearch("", undefined, "student"), + getClasses(), + getTerms().catch(() => ({ items: [] })), + ]); + // No endpoint maps students to classes in bulk; one members read per class + // is bounded by the class count, not the student count. + const memberships = await Promise.all( + classes.items.map(async (cls) => ({ cls, members: (await getClassMembers(cls.id)).items })), + ); + const byStudent = new Map(); + for (const { cls, members } of memberships) { + for (const member of members) byStudent.set(member.user.id, [...(byStudent.get(member.user.id) ?? []), cls]); + } + const rows: StudentRow[] = students.items.map((person) => ({ person, classes: byStudent.get(person.id) ?? [] })); + return { rows, classes: classes.items, terms: terms.items }; + }); + + const rows = createMemo(() => + (data()?.rows ?? []).filter((row) => { + if (classFilter() && !row.classes.some((cls) => cls.id === classFilter())) return false; + if (termFilter() && !row.classes.some((cls) => cls.term === termFilter())) return false; + return true; + }), + ); + + const open = (row: StudentRow) => void navigate({ to: "/profile/$userId", params: { userId: row.person.id } }); + + const columns = createMemo[]>(() => [ + { + id: "student", size: 220, + header: t("roster.student"), + cell: (cell) => , + }, + { + id: "class", + size: 90, + header: t("roster.class"), + cell: (cell) => ( + {cell.row.original.classes.map((cls) => cls.name).join(", ") || "—"} + ), + }, + { id: "mastery", size: 130, header: t("roster.mastery"), enableSorting: false, cell: () => }, + { id: "attendance", size: 130, header: t("roster.attendance"), enableSorting: false, cell: () => }, + { id: "plan", size: 130, header: t("roster.planAdherence"), enableSorting: false, cell: () => }, + { id: "status", size: 130, header: t("roster.status"), enableSorting: false, cell: () => }, + { + id: "actions", + header: t("common.actions"), + meta: { headerClass: "w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap" }, + cell: (cell) => ( + , onSelect: () => open(cell.row.original) }]} + /> + ), + }, + ]); + + return ( +
+ + + {t("roster.tabAll")} + + {(key) => ( + + {t(key)} + + + )} + + + + +
+
+

{t("nav.studentsRoster")}

+

{t("roster.studentsSubtitle")}

+
+
+ + +
+
+ + }> + + void refetch()} /> + + + {(value) => ( + + [row.person.username, row.person.display_name ?? ""].join(" ").toLocaleLowerCase().includes(query.toLocaleLowerCase()) + } + filters={ + <> + + + + } + enablePagination + pageSize={ROSTER_PAGE_SIZE} + storageKey="students-roster" + onRowClick={open} + /> + )} + + +
+ ); +} diff --git a/src/pages/teachers-roster-page.tsx b/src/pages/teachers-roster-page.tsx new file mode 100644 index 0000000..cc21a1a --- /dev/null +++ b/src/pages/teachers-roster-page.tsx @@ -0,0 +1,134 @@ +import { useNavigate } from "@tanstack/solid-router"; +import type { ColumnDef } from "@tanstack/solid-table"; +import { For, Show, Suspense, createMemo, createResource } from "solid-js"; +import { getClasses } from "@/api/classes"; +import { getUserSearch } from "@/api/users"; +import { formatApiError, type PersonRef } from "@/api/client"; +import { RouteGuard } from "@/components/layout/route-guard"; +import { RosterPersonCell } from "@/components/users/roster-person-cell"; +import { Button } from "@/components/ui/button"; +import { ComingSoonBadge, ComingSoonValue } from "@/components/ui/coming-soon"; +import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; +import { ErrorAlert } from "@/components/ui/error-alert"; +import { IconEye, IconPlus, IconUploadCloud } from "@/components/ui/icons"; +import { TableRowActions } from "@/components/ui/table-row-actions"; +import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { useT } from "@/stores/preferences-context"; + +const ROSTER_PAGE_SIZE = 10; + +type TeacherRow = { person: PersonRef; homeroomClasses: number }; + +export default function TeachersRosterPage() { + return ( + + + + ); +} + +// ADM-08. "Sınıf" is the number of classes the teacher is homeroom teacher of +// (ClassGroup.teacher); branch, weekly load, AI acceptance and employment +// status have no field anywhere, so they stay "yakında". +function TeachersRosterContent() { + const t = useT(); + const navigate = useNavigate(); + + const [data, { refetch }] = createResource(async () => { + const [teachers, classes] = await Promise.all([getUserSearch("", undefined, "teacher"), getClasses()]); + const homeroom = new Map(); + for (const cls of classes.items) { + if (cls.teacher) homeroom.set(cls.teacher.id, (homeroom.get(cls.teacher.id) ?? 0) + 1); + } + return teachers.items.map((person) => ({ person, homeroomClasses: homeroom.get(person.id) ?? 0 })); + }); + + const open = (row: TeacherRow) => void navigate({ to: "/profile/$userId", params: { userId: row.person.id } }); + + const columns = createMemo[]>(() => [ + { id: "teacher", size: 220, header: t("roster.teacher"), cell: (cell) => }, + { id: "branch", size: 130, header: t("roster.branch"), enableSorting: false, cell: () => }, + { + accessorKey: "homeroomClasses", + size: 90, + header: t("roster.class"), + meta: { cellClass: "mono tabular-nums" }, + cell: (cell) => (cell.row.original.homeroomClasses > 0 ? cell.row.original.homeroomClasses : "—"), + }, + { id: "weekly", size: 130, header: t("roster.weeklyLessons"), enableSorting: false, cell: () => }, + { id: "acceptance", size: 130, header: t("roster.suggestionAcceptance"), enableSorting: false, cell: () => }, + { id: "status", size: 130, header: t("roster.status"), enableSorting: false, cell: () => }, + { + id: "actions", + header: t("common.actions"), + meta: { headerClass: "w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap" }, + cell: (cell) => ( + , onSelect: () => open(cell.row.original) }]} + /> + ), + }, + ]); + + return ( +
+ + + {t("roster.tabAll")} + + {(key) => ( + + {t(key)} + + + )} + + + + +
+
+

{t("nav.teachersRoster")}

+

{t("roster.teachersSubtitle")}

+
+
+ + +
+
+ + }> + + void refetch()} /> + + + {(rows) => ( + + [row.person.username, row.person.display_name ?? ""].join(" ").toLocaleLowerCase().includes(query.toLocaleLowerCase()) + } + enablePagination + pageSize={ROSTER_PAGE_SIZE} + storageKey="teachers-roster" + onRowClick={open} + /> + )} + + +
+ ); +} diff --git a/src/pages/work-log-page.tsx b/src/pages/work-log-page.tsx index d26559d..00a1a41 100644 --- a/src/pages/work-log-page.tsx +++ b/src/pages/work-log-page.tsx @@ -22,7 +22,7 @@ const WORK_PAGE_SIZE = 15; export default function WorkLogPage() { return ( - + ); diff --git a/src/routes/router.tsx b/src/routes/router.tsx index 442c277..ea6292a 100644 --- a/src/routes/router.tsx +++ b/src/routes/router.tsx @@ -68,6 +68,12 @@ const PaymentStatementPage = lazyRoute(() => import("@/pages/payment-statement-p const WhiteboardsPage = lazyRoute(() => import("@/pages/whiteboards-page")); const WhiteboardPage = lazyRoute(() => import("@/pages/whiteboard-page")); const ComingSoonPage = lazyRoute(() => import("@/pages/coming-soon-page")); +const StudentsRosterPage = lazyRoute(() => import("@/pages/students-roster-page")); +const TeachersRosterPage = lazyRoute(() => import("@/pages/teachers-roster-page")); +const LicenseModulesPage = lazyRoute(() => import("@/pages/license-modules-page")); +const BuilderLoginPage = lazyRoute(() => import("@/pages/builder-login-page")); +const BuilderSchoolsPage = lazyRoute(() => import("@/pages/builder-schools-page")); +const BuilderSchoolDetailPage = lazyRoute(() => import("@/pages/builder-school-detail-page")); function RootComponent() { return ( @@ -325,6 +331,24 @@ const myStudentsRoute = createRoute({ component: MyStudentsPage, }); +const myStudentsAttendanceRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/students/attendance", + component: MyStudentsPage, +}); + +const myStudentsExamsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/students/exams", + component: MyStudentsPage, +}); + +const myStudentsStudyRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/students/study", + component: MyStudentsPage, +}); + const questionsRoute = createRoute({ getParentRoute: () => rootRoute, path: "/questions", @@ -391,6 +415,44 @@ const whiteboardRoute = createRoute({ component: WhiteboardPage, }); +const studentsRosterRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/management/students", + component: StudentsRosterPage, +}); + +const teachersRosterRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/management/teachers", + component: TeachersRosterPage, +}); + +const licenseModulesRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/management/modules", + component: LicenseModulesPage, +}); + +// The vendor surface: a builder session, not a school user, so none of these +// render the school shell's sidebar (there is no school user to draw it for). +const builderLoginRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/builder/login", + component: BuilderLoginPage, +}); + +const builderSchoolsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/builder", + component: BuilderSchoolsPage, +}); + +const builderSchoolDetailRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/builder/schools/$slug", + component: BuilderSchoolDetailPage, +}); + // One route per Figma menu entry with no backend yet — each gets its own URL // (so breadcrumbs, back and direct links behave normally) but all render the // same "not ready" page. Slugs are read back by coming-soon-page.tsx. @@ -400,17 +462,11 @@ const COMING_SOON_SLUGS = [ "deneme-sinavlari", "optik-okuma", "raporlar", - "lisans-modulleri", "kvkk-denetim", - "ogrenciler", - "ogretmenler", "ogrenci-analizi", "bekleyen-onaylar", "soru-uretimi", "calisma-programim", - "devamsizlik", - "sinav-sonuclari-veli", - "calisma-plani", ] as const; const comingSoonRoutes = COMING_SOON_SLUGS.map((slug) => @@ -457,6 +513,9 @@ const routeTree = rootRoute.addChildren([ adminUserDetailRoute, guideRoute, myStudentsRoute, + myStudentsAttendanceRoute, + myStudentsExamsRoute, + myStudentsStudyRoute, questionsRoute, questionDetailRoute, calendarRoute, @@ -468,6 +527,12 @@ const routeTree = rootRoute.addChildren([ paymentStatementRoute, whiteboardsRoute, whiteboardRoute, + studentsRosterRoute, + teachersRosterRoute, + licenseModulesRoute, + builderLoginRoute, + builderSchoolsRoute, + builderSchoolDetailRoute, myProfileRoute, userProfileRoute, ...comingSoonRoutes, diff --git a/src/stores/builder-context.tsx b/src/stores/builder-context.tsx new file mode 100644 index 0000000..0af620f --- /dev/null +++ b/src/stores/builder-context.tsx @@ -0,0 +1,54 @@ +import { type Accessor, type ParentProps, createContext, createResource, useContext } from "solid-js"; +import { getBuilderMe, postBuilderLogout } from "@/api/builder"; +import { ApiError, type Builder } from "@/api/client"; + +type BuilderContextValue = { + /** undefined while resolving, null when this browser holds no builder session. */ + builder: Accessor; + loading: Accessor; + error: Accessor; + refresh: () => void; + logout: () => Promise; +}; + +const BuilderContext = createContext(); + +/** + * The deployment operator's session. Separate from AuthProvider on purpose: a + * builder cookie is 401 on every school route and a school cookie is 401 here, + * so the two never describe the same browser at once. + */ +export function BuilderProvider(props: ParentProps) { + let failure: unknown = null; + const [me, { refetch, mutate }] = createResource(async () => { + failure = null; + try { + return await getBuilderMe(); + } catch (err) { + if (!(err instanceof ApiError && err.status === 401)) failure = err; + return null; + } + }); + + const value: BuilderContextValue = { + builder: () => me(), + loading: () => me.loading, + error: () => (me() === null ? failure : null), + refresh: () => void refetch(), + logout: async () => { + try { + await postBuilderLogout(); + } finally { + mutate(null); + } + }, + }; + + return {props.children}; +} + +export function useBuilder(): BuilderContextValue { + const ctx = useContext(BuilderContext); + if (!ctx) throw new Error("useBuilder must be used within BuilderProvider"); + return ctx; +}