forge
Explore
Log in

Don't you dare go Hollow

🎓 follow the backend's grade ladder and per-section course rows

Browse files at this commit

167d960f88502ad06c3b152db62925d529045873Burak BoduroğluParent: 50dd157
  • fix
    • 🎓 follow the backend's grade ladder and per-section course rows
Show full message
fix: 🎓 follow the backend's grade ladder and per-section course rows

- classes, blueprints and year promotions carry an integer grade_level
  (0 = anaokulu .. 12) instead of a free-text grade; shared
  GradeLevelSelect picker and gradeLevelLabel helper
- blueprint routes key on the grade level; limits publish
  min/max_grade_level instead of max_class_grade_len
- GET /courses/me now lists class sections, so catalog consumers read the
  already-scoped GET /courses; course detail draws its sections from the
  embedded course.sections instead of a per-class fan-out
- profile course rows are sections: link to the catalog course, show the
  class name; profile class badges show the grade label
- RAG study scopes name the backend's grade label and the section's
  resolved title
- instance/course/limit types gain the resolved-override, section,
  holiday, offering and weekly-plan shapes; map the new refusal codes
src/api/__tests__/academic-years/academic-years.test.tsmodified+1 -1
@@ -41,7 +41,7 @@ describe("academic years API", () => {
4141 name: "2026-2027",
4242 starts_at: 1780000000000,
4343 ends_at: 1810000000000,
44- grade_promotions: [{ from_grade: "5", to_grade: "6" }],
44+ grade_promotions: [{ from_grade: 5, to_grade: 6 }],
4545 };
4646
4747 await postAcademicYear(body);
src/api/__tests__/classes/classes.test.tsmodified+15 -15
@@ -33,7 +33,7 @@ describe("classes API", () => {
3333 it("postClass POSTs /classes and returns the create envelope", async () => {
3434 const envelope = { class: { id: "c1" }, skipped: [], stocked_from: null };
3535 mockFetchSuccess(envelope);
36- const body = { name: "9-A", grade: "9", year: "y1" };
36+ const body = { name: "9-A", grade_level: 9, year: "y1" };
3737 const created = await postClass(body);
3838 expect(created).toEqual(envelope);
3939 expect(created.class.id).toBe("c1");
@@ -75,7 +75,7 @@ describe("classes API", () => {
7575
7676 it("patchClassById PATCHes /classes/:id with the body", async () => {
7777 mockFetchSuccess({ id: "c1" });
78- const body = { name: "9-B", grade: null, term_id: null };
78+ const body = { name: "9-B", grade_level: 10, year: null };
7979 await patchClassById("c1", body);
8080 const [url, init] = lastFetchCall();
8181 expect(url).toBe("/api/classes/c1");
@@ -144,8 +144,8 @@ describe("classes API", () => {
144144 });
145145
146146 it("postClassBlueprint POSTs /classes/blueprints with the body", async () => {
147- mockFetchSuccess({ blueprint: { grade: "9", courses: [], creator: {} }, matched: 2, skipped: [] });
148- const body = { grade: "9", course_ids: ["co1", "co2"] };
147+ mockFetchSuccess({ blueprint: { grade_level: 9, courses: [], creator: {} }, matched: 2, skipped: [] });
148+ const body = { grade_level: 9, course_ids: ["co1", "co2"] };
149149 await postClassBlueprint(body);
150150 const [url, init] = lastFetchCall();
151151 expect(url).toBe("/api/classes/blueprints");
@@ -160,17 +160,17 @@ describe("classes API", () => {
160160 expect(url).toBe("/api/classes/blueprints?limit=20&offset=40");
161161 });
162162
163- it("getClassBlueprintByGrade encodes the grade, which is the record key", async () => {
164- mockFetchSuccess({ grade: "9/A", courses: [], creator: {} });
165- await getClassBlueprintByGrade("9/A");
163+ it("getClassBlueprintByGrade keys the blueprint by its grade level", async () => {
164+ mockFetchSuccess({ grade_level: 0, courses: [], creator: {} });
165+ await getClassBlueprintByGrade(0);
166166 const [url] = lastFetchCall();
167- expect(url).toBe("/api/classes/blueprints/9%2FA");
167+ expect(url).toBe("/api/classes/blueprints/0");
168168 });
169169
170170 it("patchClassBlueprintByGrade PATCHes the whole course set", async () => {
171- mockFetchSuccess({ blueprint: { grade: "9", courses: [], creator: {} }, matched: 2, skipped: [] });
171+ mockFetchSuccess({ blueprint: { grade_level: 9, courses: [], creator: {} }, matched: 2, skipped: [] });
172172 const body = { course_ids: ["co1"] };
173- await patchClassBlueprintByGrade("9", body);
173+ await patchClassBlueprintByGrade(9, body);
174174 const [url, init] = lastFetchCall();
175175 expect(url).toBe("/api/classes/blueprints/9");
176176 expect(init?.method).toBe("PATCH");
@@ -179,9 +179,9 @@ describe("classes API", () => {
179179
180180 it("deleteClassBlueprintByGrade DELETEs /classes/blueprints/:grade", async () => {
181181 mockFetch204();
182- await deleteClassBlueprintByGrade("9/A");
182+ await deleteClassBlueprintByGrade(11);
183183 const [url, init] = lastFetchCall();
184- expect(url).toBe("/api/classes/blueprints/9%2FA");
184+ expect(url).toBe("/api/classes/blueprints/11");
185185 expect(init?.method).toBe("DELETE");
186186 });
187187
@@ -195,12 +195,12 @@ describe("classes API", () => {
195195 });
196196
197197 it("getClassBlueprintStatus GETs /classes/blueprints/:grade/status", async () => {
198- const mockStatus = { grade: "9/A", courses: ["co1"], matched: 3, sections: [] };
198+ const mockStatus = { grade_level: 9, courses: ["co1"], matched: 3, sections: [] };
199199 mockFetchSuccess(mockStatus);
200- const result = await getClassBlueprintStatus("9/A");
200+ const result = await getClassBlueprintStatus(9);
201201 expect(result).toEqual(mockStatus);
202202 const [url, init] = lastFetchCall();
203- expect(url).toBe("/api/classes/blueprints/9%2FA/status");
203+ expect(url).toBe("/api/classes/blueprints/9/status");
204204 expect(init?.method).toBe("GET");
205205 });
206206 });
src/api/classes/deleteClassBlueprintByGrade.tsmodified+2 -2
@@ -2,6 +2,6 @@ import { client } from "../client";
22
33 // Detaches every course this blueprint attached, across every class at the
44 // grade, then drops the template. Hand-attached courses stay.
5-export function deleteClassBlueprintByGrade(grade: string): Promise<void> {
6- return client<void>(`/classes/blueprints/${encodeURIComponent(grade)}`, { method: "DELETE" });
5+export function deleteClassBlueprintByGrade(gradeLevel: number): Promise<void> {
6+ return client<void>(`/classes/blueprints/${gradeLevel}`, { method: "DELETE" });
77 }
src/api/classes/getClassBlueprintByGrade.tsmodified+3 -4
@@ -1,8 +1,7 @@
11 import { client } from "../client";
22 import type { ClassBlueprint } from "../client";
33
4-// The grade label is the record key and is free text, so it must be encoded —
5-// a grade like "9/A" would otherwise read as a second path segment.
6-export function getClassBlueprintByGrade(grade: string, signal?: AbortSignal): Promise<ClassBlueprint> {
7- return client<ClassBlueprint>(`/classes/blueprints/${encodeURIComponent(grade)}`, { signal });
4+// The grade level (0..12) is the record key.
5+export function getClassBlueprintByGrade(gradeLevel: number, signal?: AbortSignal): Promise<ClassBlueprint> {
6+ return client<ClassBlueprint>(`/classes/blueprints/${gradeLevel}`, { signal });
87 }
src/api/classes/getClassBlueprintStatus.tsmodified+2 -2
@@ -1,6 +1,6 @@
11 import { client } from "../client";
22 import type { BlueprintStatus } from "../client";
33
4-export function getClassBlueprintStatus(grade: string, signal?: AbortSignal): Promise<BlueprintStatus> {
5- return client<BlueprintStatus>(`/classes/blueprints/${encodeURIComponent(grade)}/status`, { signal });
4+export function getClassBlueprintStatus(gradeLevel: number, signal?: AbortSignal): Promise<BlueprintStatus> {
5+ return client<BlueprintStatus>(`/classes/blueprints/${gradeLevel}/status`, { signal });
66 }
src/api/classes/patchClassBlueprintByGrade.tsmodified+2 -2
@@ -9,10 +9,10 @@ export type UpdateBlueprintBody = { course_ids: string[] };
99 // A 409 means the blueprint changed since it was read — there is no version to
1010 // echo back, so re-read it and let the user resubmit from the fresh list.
1111 export function patchClassBlueprintByGrade(
12- grade: string,
12+ gradeLevel: number,
1313 body: UpdateBlueprintBody,
1414 ): Promise<BlueprintResult> {
15- return client<BlueprintResult>(`/classes/blueprints/${encodeURIComponent(grade)}`, {
15+ return client<BlueprintResult>(`/classes/blueprints/${gradeLevel}`, {
1616 method: "PATCH",
1717 body,
1818 });
src/api/classes/patchClassById.tsmodified+3 -2
@@ -1,10 +1,11 @@
11 import { client } from "../client";
22 import type { ClassGroup } from "../client";
33
4-// Omit a field to keep it; send null on grade/year/teacher_id to clear/unlink it.
4+// Omit a field to keep it; send null on year/teacher_id to clear/unlink it. The
5+// grade is required on every class, so `grade_level` can be reset, never cleared.
56 export type UpdateClassBody = {
67 name?: string;
7- grade?: string | null;
8+ grade_level?: number;
89 /** The academic year (`getAcademicYears`) the şube sits in. */
910 year?: string | null;
1011 teacher_id?: string | null;
src/api/classes/postClass.tsmodified+2 -1
@@ -3,7 +3,8 @@ import type { CreateClassResponse } from "../client";
33
44 // `year` is the academic year (`getAcademicYears`) — what binds the şube to a
55 // karne and to the rollover. A şube with no year takes no exam.
6-export type CreateClassBody = { name: string; grade?: string; year?: string; teacher_id?: string };
6+// `grade_level` is the rung on the grade ladder, 0 (anaokulu) .. 12; required.
7+export type CreateClassBody = { name: string; grade_level: number; year?: string; teacher_id?: string };
78
89 // The 201 is a create envelope, not the bare class: its `class` is what the
910 // route navigates to, and its `skipped` is the blueprint fallout the caller
src/api/classes/postClassBlueprint.tsmodified+1 -1
@@ -1,7 +1,7 @@
11 import { client } from "../client";
22 import type { BlueprintResult } from "../client";
33
4-export type CreateBlueprintBody = { grade: string; course_ids: string[] };
4+export type CreateBlueprintBody = { grade_level: number; course_ids: string[] };
55
66 // Manager+. Creates the blueprint and immediately applies it to every existing
77 // class at that grade; pairs that could not land come back in `skipped`.
src/api/client/client.tsmodified+32 -0
@@ -356,6 +356,38 @@ const API_ERROR_CODE_MESSAGES: Record<string, LocalizedMessage> = {
356356 tr: "Öğrenci eklenirken şubenin derslerinden biri kaldırıldı. Sayfayı yenileyip tekrar dene.",
357357 },
358358 student_number_taken: STUDENT_NUMBER_TAKEN,
359+ session_time_taken: {
360+ en: "Another lesson of this section already starts at this time. Pick a different start time.",
361+ tr: "Bu şubenin başka bir dersi zaten bu saatte başlıyor. Farklı bir başlangıç saati seç.",
362+ },
363+ offering_exists: {
364+ en: "This course already has a template for this grade. Edit the existing template instead.",
365+ tr: "Bu dersin bu seviye için zaten bir şablonu var. Bunun yerine mevcut şablonu düzenle.",
366+ },
367+ offering_in_use: {
368+ en: "Classes still teach from this template. Detach the course from those classes first.",
369+ tr: "Bu şablondan hâlâ ders işleyen şubeler var. Önce dersi o şubelerden çıkar.",
370+ },
371+ slot_overlap: {
372+ en: "Another slot on this day overlaps this time window. Pick a different time.",
373+ tr: "Bu gündeki başka bir ders saati bu zaman aralığıyla çakışıyor. Farklı bir saat seç.",
374+ },
375+ slot_cap: {
376+ en: "This weekly plan already holds the maximum number of slots. Remove one before adding another.",
377+ tr: "Bu haftalık plan en fazla ders saati sayısına ulaştı. Yenisini eklemeden önce birini kaldır.",
378+ },
379+ unknown_exam_kind: {
380+ en: "This exam kind is not one the school uses. Pick a kind from the school settings.",
381+ tr: "Bu sınav türü okulun kullandığı türlerden biri değil. Okul ayarlarındaki türlerden birini seç.",
382+ },
383+ instance_has_no_weekly_plan: {
384+ en: "This section has no weekly plan yet. Add slots before generating lessons.",
385+ tr: "Bu şubenin henüz haftalık planı yok. Ders üretmeden önce ders saati ekle.",
386+ },
387+ instance_has_no_teacher: {
388+ en: "No teacher is assigned to this section. Assign a teacher before generating lessons.",
389+ tr: "Bu şubeye atanmış öğretmen yok. Ders üretmeden önce bir öğretmen ata.",
390+ },
359391 not_ready: {
360392 en: "This audio is not ready yet. Wait for it to finish and try again.",
361393 tr: "Bu ses kaydı henüz hazır değil. Tamamlanmasını bekleyip tekrar dene.",
src/api/client/types.tsmodified+154 -13
@@ -110,9 +110,20 @@ export type EarnedBadge = { id: string; earned_at: number };
110110
111111 export type AvatarMeta = { content_type: string; size: number };
112112
113-export type ProfileClassRef = { id: string; name: string; grade: string | null };
113+export type ProfileClassRef = { id: string; name: string; grade_level: number };
114114
115-export type ProfileCourseRef = { id: string; title: string; kind: CourseKind };
115+// One class section a profile lists, never the catalog row: `id` is the
116+// instance id, `title` its resolved title. `class`, `class_name` and
117+// `grade_level` read null for a viewer below the classes-block bar.
118+export type ProfileCourseRef = {
119+ id: string;
120+ course: string;
121+ class: string | null;
122+ class_name: string | null;
123+ title: string;
124+ grade_level: number | null;
125+ kind: CourseKind;
126+};
116127
117128 // Lifetime counters behind the badge ladders, plus the two live totals the
118129 // capped `classes`/`courses` lists would otherwise hide.
@@ -335,17 +346,80 @@ export type Course = {
335346 class_course_count: number;
336347 // Individual club/etut memberships on the catalog row itself.
337348 course_membership_count: number;
349+ // The sections teaching it, capped at limits.course.max_course_sections
350+ // (class_course_count keeps the true total) and filtered to what the
351+ // reader reaches.
352+ sections: CourseSectionRef[];
338353 };
339354
355+// One class section of a catalog course, as a course row or GET /courses/me
356+// lists it: `id` is the instance id, `title` and `ders_saati` resolved.
357+export type CourseSectionRef = {
358+ id: string;
359+ course: string;
360+ class: string;
361+ class_name: string;
362+ title: string;
363+ grade_level: number;
364+ ders_saati: number;
365+ teachers: PersonRef[];
366+ enrollment_count: number;
367+};
368+
369+/** One exam kind's effective weight. */
370+export type ExamWeightEntry = { kind: string; weight: number };
371+
372+/**
373+ * One slot of a weekly plan. `starts_at`/`ends_at` are minutes past midnight
374+ * (540 = 09:00), `weekday` 1..7 (Monday first).
375+ */
376+export type WeeklySlot = {
377+ id: string;
378+ weekday: number;
379+ starts_at: number;
380+ ends_at: number;
381+ topic?: string | null;
382+};
383+
384+/** The override fields POST /instances/{id}/reset clears back to inherit. */
385+export type InstanceOverrideField =
386+ | "title"
387+ | "description"
388+ | "ders_saati"
389+ | "counts_toward_karne"
390+ | "subjects"
391+ | "exam_weights"
392+ | "weekly_plan";
393+
340394 // One catalog course as one sube teaches it. This is what carries the roster,
341395 // the exams, the sessions and the karne weight.
396+//
397+// Every content field is resolved: a scalar runs section override -> the
398+// grade-level offering -> catalog/constant, and `*_overridden` tells the
399+// section's own value from an inherited one. The three sets (subjects, exam
400+// weights, weekly plan) follow a flag: `*_inherited: false` means the
401+// section's own rows are authoritative, even when empty.
342402 export type Instance = {
343403 id: string;
344404 class: string;
345405 course: string;
406+ // The grade-level template (GET /offerings/{id}) unset fields inherit from.
407+ offering: string;
408+ title: string;
409+ title_overridden: boolean;
410+ description: string;
411+ description_overridden: boolean;
346412 // Weekly lesson hours; the instance's weight in the year's karne average.
347413 ders_saati: number;
414+ ders_saati_overridden: boolean;
348415 counts_toward_karne: boolean;
416+ counts_toward_karne_overridden: boolean;
417+ subjects_inherited: boolean;
418+ subjects: Subject[];
419+ exam_weights_inherited: boolean;
420+ exam_weights: ExamWeightEntry[];
421+ weekly_plan_inherited: boolean;
422+ weekly_plan: WeeklySlot[];
349423 enrollment_count: number;
350424 teachers: PersonRef[];
351425 };
@@ -360,10 +434,10 @@ export type CourseMembership = {
360434 created_at: number;
361435 };
362436
363-/** One sınıf-geçme pair: the grade label students move to at rollover. */
437+/** One sınıf-geçme pair: the grade level (0..12) students move to at rollover. */
364438 export type GradePromotion = {
365- from_grade: string;
366- to_grade: string;
439+ from_grade: number;
440+ to_grade: number;
367441 };
368442
369443 // An academic year: the calendar structure dönemler and şubeler hang off.
@@ -423,7 +497,8 @@ export type ClassGroup = {
423497 // GET /classes/user/{user}).
424498 creator: PersonRef | null;
425499 name: string;
426- grade: string | null;
500+ // The class's rung on the grade ladder, 0 (anaokulu) .. 12. Required.
501+ grade_level: number;
427502 // The academic year (AcademicYear id) the sube sits in; what binds it to a
428503 // karne and to the rollover. Null when none is set.
429504 year: string | null;
@@ -436,7 +511,7 @@ export type ClassGroup = {
436511 // that stocked it. `skipped` is empty when the template took every course, and
437512 // always empty when no template covered the grade; `stocked_from` is null in
438513 // that second case.
439-export type CreateClassResponse = { class: ClassGroup; skipped: BlueprintSkip[]; stocked_from: string | null };
514+export type CreateClassResponse = { class: ClassGroup; skipped: BlueprintSkip[]; stocked_from: number | null };
440515
441516 export type ClassMember = {
442517 id: string;
@@ -451,9 +526,13 @@ export type ClassMember = {
451526 source_class_group: string | null;
452527 };
453528
454-// The instance as the class routes return it: an Instance plus who attached
455-// the course to the sube.
456-export type ClassCourse = Instance & {
529+// The instance as the class routes return it: the resolved scalars plus who
530+// attached the course to the sube. The override flags and the three resolved
531+// sets live on GET /instances/{id} only.
532+export type ClassCourse = Pick<
533+ Instance,
534+ "id" | "class" | "course" | "title" | "description" | "ders_saati" | "counts_toward_karne" | "enrollment_count" | "teachers"
535+> & {
457536 attached_by: PersonRef;
458537 };
459538
@@ -461,7 +540,7 @@ export type ClassCourse = Instance & {
461540 // grade label is the record's key, so there is at most one per grade. Creating
462541 // or editing one applies it to every existing class at that grade right away.
463542 export type ClassBlueprint = {
464- grade: string;
543+ grade_level: number;
465544 courses: string[];
466545 creator: PersonRef;
467546 };
@@ -493,13 +572,62 @@ export type BlueprintSectionStatus = {
493572
494573 /** Every section at a grade with the template courses it is missing. */
495574 export type BlueprintStatus = {
496- grade: string;
575+ grade_level: number;
497576 /** The template every section below is measured against. */
498577 courses: string[];
499578 matched: number;
500579 sections: BlueprintSectionStatus[];
501580 };
502581
582+// A school-wide non-teaching day range. The materializer skips every day it
583+// reaches into; lessons already on those days stay.
584+export type Holiday = {
585+ id: string;
586+ name: string;
587+ /** First blocked instant, UTC unix-millis. */
588+ starts_at: number;
589+ /** Last blocked instant, UTC unix-millis. */
590+ ends_at: number;
591+ /** One of limits.holiday.kinds. */
592+ kind: string;
593+ creator: PersonRef;
594+ created_at: number;
595+};
596+
597+// A grade-level template of a catalog course: what every section at that
598+// grade inherits. Null fields inherit themselves (the catalog title/
599+// description, 1 weekly hour, counted toward the karne).
600+export type Offering = {
601+ id: string;
602+ course: string;
603+ grade_level: number;
604+ title: string | null;
605+ description: string | null;
606+ default_ders_saati: number | null;
607+ default_counts_toward_karne: boolean | null;
608+ created_by: PersonRef;
609+ created_at: number;
610+ updated_at: number;
611+};
612+
613+/** One day the materializer left out because a holiday covers it. */
614+export type BlockedDay = { date: string; holiday: string };
615+
616+// What POST /instances/{id}/weekly-plan/materialize answers. `created` is
617+// empty on a dry run; `candidates` is what an apply would try to write.
618+export type MaterializeReport = {
619+ from: number;
620+ to: number;
621+ applied: boolean;
622+ slots: number;
623+ candidates: number;
624+ created: CourseSession[];
625+ skipped_existing: number;
626+ skipped_holiday: number;
627+ blocked: BlockedDay[];
628+ range_days: number;
629+};
630+
503631 export type CourseSession = {
504632 id: string;
505633 /** The instance this lesson belongs to. */
@@ -891,12 +1019,25 @@ export type Limits = {
8911019 max_session_topic_len: number;
8921020 max_term_name_len: number;
8931021 max_class_name_len: number;
894- max_class_grade_len: number;
1022+ // The grade ladder: 0 (anaokulu) .. 12.
1023+ min_grade_level: number;
1024+ max_grade_level: number;
8951025 max_class_members: number;
8961026 max_class_courses: number;
8971027 max_academic_year_name_len: number;
8981028 min_ders_saati: number;
8991029 max_ders_saati: number;
1030+ // How many sections a catalog course row embeds in `sections`.
1031+ max_course_sections: number;
1032+ };
1033+ holiday: { max_name_len: number; kinds: string[] };
1034+ weekly_plan: {
1035+ // Inclusive bounds for a slot's minutes past midnight.
1036+ min_slot_minute: number;
1037+ max_slot_minute: number;
1038+ max_weekly_slots: number;
1039+ max_materialize_days: number;
1040+ max_materialize_sessions: number;
9001041 };
9011042 exam: {
9021043 max_title_len: number;
src/api/reports/getMyCourses.tsmodified+8 -6
@@ -1,9 +1,11 @@
11 import { client } from "../client";
2-import { normalizePage, type Page } from "../client";
3-import type { Course } from "../client";
4-import { courseListQuery, type CourseListParams } from "../courses/getCourses";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "../client";
3+import type { CourseSectionRef } from "../client";
54
6-export async function getMyCourses(params?: CourseListParams, signal?: AbortSignal): Promise<Page<Course>> {
7- const data = await client<unknown>(`/courses/me${courseListQuery(params)}`, { signal });
8- return normalizePage<Course>(data);
5+// One row per class section the caller reaches (şube roster, homeroom, taught,
6+// or a hand-placed enrollment) — `id` is the instance id, never the catalog
7+// course's; `course` names the catalog row.
8+export async function getMyCourses(params?: PageParams, signal?: AbortSignal): Promise<Page<CourseSectionRef>> {
9+ const data = await client<unknown>(`/courses/me${pageQuery(params)}`, { signal });
10+ return normalizePage<CourseSectionRef>(data);
911 }
src/components/ai/note-studio-panel.tsxmodified+5 -5
@@ -3,8 +3,7 @@ import { Link, useNavigate } from "@tanstack/solid-router";
33 import { createResource } from "@/lib/create-resource";
44 import { getCourseNotes } from "@/api/course-notes";
55 import { getCourses } from "@/api/courses";
6-import { getMyCourses } from "@/api/reports";
7-import { formatApiError, type CourseNote, type Role } from "@/api/client";
6+import { formatApiError, type CourseNote } from "@/api/client";
87 import { PodcastPanel } from "@/components/notes/podcast-panel";
98 import { RagOutputsPanel } from "@/components/notes/rag-outputs-panel";
109 import { StudioOutputLibrary } from "@/components/ai/studio-output-library";
@@ -36,8 +35,9 @@ function readRailWidth(): number {
3635 type StudioNote = CourseNote & { courseTitle: string; courseCreatorId: string };
3736
3837 /** Every lesson note the account can produce from, with its course. */
39-async function loadStudioNotes(role: Role): Promise<StudioNote[]> {
40- const courses = role === "student" ? await getMyCourses({ limit: 100 }) : await getCourses({ limit: 100 });
38+async function loadStudioNotes(): Promise<StudioNote[]> {
39+ // GET /courses is already scoped to what the caller teaches or takes.
40+ const courses = await getCourses({ limit: 100 });
4141 const rows = await Promise.all(
4242 courses.items.map(async (course) => {
4343 try {
@@ -57,7 +57,7 @@ async function loadStudioNotes(role: Role): Promise<StudioNote[]> {
5757
5858 function useStudioNotes() {
5959 const auth = useAuth();
60- return createResource(() => auth.user()?.role ?? null, loadStudioNotes);
60+ return createResource(() => auth.user()?.role ?? null, () => loadStudioNotes());
6161 }
6262
6363 /**
src/components/classes/blueprint-panel.tsxmodified+15 -13
@@ -7,6 +7,7 @@ import {
77 import { ApiError, formatApiError, type BlueprintResult, type ClassBlueprint, type Course } from "@/api/client";
88 import { Alert } from "@/components/ui/alert";
99 import { Button } from "@/components/ui/button";
10+import { GradeLevelSelect } from "@/components/classes/grade-level-select";
1011 import { Input } from "@/components/ui/input";
1112 import { Label } from "@/components/ui/label";
1213 import { SidePanel } from "@/components/ui/side-panel";
@@ -21,11 +22,12 @@ export function BlueprintPanel(props: {
2122 blueprint: ClassBlueprint | null;
2223 courses: Course[];
2324 maxCourses: number;
24- maxGradeLen: number;
25+ minGradeLevel?: number;
26+ maxGradeLevel?: number;
2527 onSaved: (result: BlueprintResult) => void;
2628 }) {
2729 const t = useT();
28- const [grade, setGrade] = createSignal("");
30+ const [gradeLevel, setGradeLevel] = createSignal<number | null>(null);
2931 const [selected, setSelected] = createSignal<string[]>([]);
3032 const [filter, setFilter] = createSignal("");
3133 const [error, setError] = createSignal("");
@@ -40,7 +42,7 @@ export function BlueprintPanel(props: {
4042 createEffect(() => {
4143 if (!props.open) return;
4244 const bp = props.blueprint;
43- setGrade(bp?.grade ?? "");
45+ setGradeLevel(bp ? bp.grade_level : null);
4446 setSelected(bp?.courses ? [...bp.courses] : []);
4547 setFilter("");
4648 setError("");
@@ -62,7 +64,7 @@ export function BlueprintPanel(props: {
6264
6365 // A losing race has no version token to retry with, so re-read the blueprint,
6466 // reseed the checkboxes from the server's list, and let the user resubmit.
65- const reseedFromServer = async (g: string) => {
67+ const reseedFromServer = async (g: number) => {
6668 try {
6769 const fresh = await getClassBlueprintByGrade(g);
6870 setSelected([...fresh.courses]);
@@ -75,15 +77,15 @@ export function BlueprintPanel(props: {
7577
7678 const submit = async (e: Event) => {
7779 e.preventDefault();
78- const g = grade().trim();
79- if (!g) return;
80+ const g = gradeLevel();
81+ if (g === null) return;
8082 setError("");
8183 setWarning("");
8284 setPending(true);
8385 try {
8486 const result = editing()
8587 ? await patchClassBlueprintByGrade(g, { course_ids: selected() })
86- : await postClassBlueprint({ grade: g, course_ids: selected() });
88+ : await postClassBlueprint({ grade_level: g, course_ids: selected() });
8789 props.onSaved(result);
8890 } catch (err) {
8991 if (err instanceof ApiError && err.status === 409) {
@@ -115,13 +117,13 @@ export function BlueprintPanel(props: {
115117
116118 <div class="space-y-1.5">
117119 <Label for="bp-grade">{t("classBlueprints.grade")}</Label>
118- <Input
120+ <GradeLevelSelect
119121 id="bp-grade"
120- class="h-10"
121- maxlength={props.maxGradeLen}
122- value={grade()}
122+ value={gradeLevel()}
123+ min={props.minGradeLevel}
124+ max={props.maxGradeLevel}
123125 disabled={editing()}
124- onInput={(e) => setGrade(e.currentTarget.value)}
126+ onChange={setGradeLevel}
125127 />
126128 <p class="text-xs text-muted-foreground">{t("classBlueprints.gradeHint")}</p>
127129 </div>
@@ -170,7 +172,7 @@ export function BlueprintPanel(props: {
170172 </Show>
171173
172174 <div class="flex justify-end">
173- <Button type="submit" class="w-full sm:w-auto" disabled={pending() || !grade().trim()}>
175+ <Button type="submit" class="w-full sm:w-auto" disabled={pending() || gradeLevel() === null}>
174176 {t("common.save")}
175177 </Button>
176178 </div>
src/components/classes/blueprints-tab.tsxmodified+13 -10
@@ -15,6 +15,7 @@ import { IconClipboardCheck, IconEdit, IconPlus, IconTrash } from "@/components/
1515 import { SidePanel } from "@/components/ui/side-panel";
1616 import { TableRowActions } from "@/components/ui/table-row-actions";
1717 import { createFlash } from "@/lib/flash";
18+import { gradeLevelLabel } from "@/lib/grade-level";
1819 import { personLabel } from "@/lib/person";
1920 import { useT } from "@/stores/preferences-context";
2021
@@ -47,7 +48,8 @@ export function BlueprintsTab(props: {
4748 const columns = createMemo<ColumnDef<ClassBlueprint>[]>(() => [
4849 {
4950 id: "grade",
50- accessorFn: (row) => row.grade,
51+ accessorFn: (row) => gradeLevelLabel(row.grade_level, t),
52+ sortingFn: (a, b) => a.original.grade_level - b.original.grade_level,
5153 header: t("classBlueprints.grade"),
5254 meta: { cellClass: "font-medium" },
5355 },
@@ -97,7 +99,7 @@ export function BlueprintsTab(props: {
9799 {
98100 label: t("classBlueprints.status"),
99101 icon: <IconClipboardCheck class="h-4 w-4" />,
100- onSelect: () => void checkStatus(cell.row.original.grade),
102+ onSelect: () => void checkStatus(cell.row.original.grade_level),
101103 },
102104 ]}
103105 />
@@ -113,10 +115,10 @@ export function BlueprintsTab(props: {
113115 setEditing(null);
114116 await refetch();
115117 setSkipped(result.skipped);
116- // A grade label nobody carries is saved just the same, so it must not
118+ // A grade no class sits on is saved just the same, so it must not
117119 // read as "applied" — that is the one outcome the admin needs to fix.
118120 if (result.matched === 0) {
119- setUnmatchedGrade(result.blueprint.grade);
121+ setUnmatchedGrade(gradeLevelLabel(result.blueprint.grade_level, t));
120122 return;
121123 }
122124 setUnmatchedGrade(null);
@@ -128,7 +130,7 @@ export function BlueprintsTab(props: {
128130 if (!bp) return;
129131 setError("");
130132 try {
131- await deleteClassBlueprintByGrade(bp.grade);
133+ await deleteClassBlueprintByGrade(bp.grade_level);
132134 setDeleting(null);
133135 await refetch();
134136 setFlash(t("classBlueprints.deleted"));
@@ -136,10 +138,10 @@ export function BlueprintsTab(props: {
136138 setError(formatApiError(err));
137139 }
138140 };
139- const checkStatus = async (grade: string) => {
141+ const checkStatus = async (gradeLevel: number) => {
140142 setError("");
141143 try {
142- setStatus(await getClassBlueprintStatus(grade));
144+ setStatus(await getClassBlueprintStatus(gradeLevel));
143145 } catch (err) {
144146 setError(formatApiError(err));
145147 }
@@ -221,7 +223,8 @@ export function BlueprintsTab(props: {
221223 blueprint={editing()}
222224 courses={courses.latest ?? []}
223225 maxCourses={limits.latest?.course.max_class_courses ?? 50}
224- maxGradeLen={limits.latest?.course.max_class_grade_len ?? 20}
226+ minGradeLevel={limits.latest?.course.min_grade_level}
227+ maxGradeLevel={limits.latest?.course.max_grade_level}
225228 onSaved={(result) => void handleSaved(result)}
226229 />
227230
@@ -235,7 +238,7 @@ export function BlueprintsTab(props: {
235238 <SidePanel
236239 open={status() != null}
237240 onOpenChange={(open) => !open && setStatus(null)}
238- title={t("classBlueprints.statusTitle", { grade: status()?.grade ?? "" })}
241+ title={t("classBlueprints.statusTitle", { grade: status() ? gradeLevelLabel(status()!.grade_level, t) : "" })}
239242 size="wide"
240243 >
241244 <Show when={status()}>
@@ -256,7 +259,7 @@ export function BlueprintsTab(props: {
256259 open={deleting() !== null}
257260 onOpenChange={(open) => !open && setDeleting(null)}
258261 title={t("classBlueprints.delete")}
259- summary={t("classBlueprints.deleteConfirm", { grade: deleting()?.grade ?? "" })}
262+ summary={t("classBlueprints.deleteConfirm", { grade: deleting() ? gradeLevelLabel(deleting()!.grade_level, t) : "" })}
260263 variant="destructive"
261264 onConfirm={remove}
262265 />
src/components/classes/class-edit-panel.tsxmodified+7 -5
@@ -3,6 +3,7 @@ import { patchClassById } from "@/api/classes";
33 import { formatApiError, type AcademicYear, type ClassGroup } from "@/api/client";
44 import { Alert } from "@/components/ui/alert";
55 import { Button } from "@/components/ui/button";
6+import { GradeLevelSelect } from "@/components/classes/grade-level-select";
67 import { Input } from "@/components/ui/input";
78 import { Label } from "@/components/ui/label";
89 import { Select } from "@/components/ui/select";
@@ -23,11 +24,12 @@ export function ClassEditPanel(props: {
2324 onSaved: (cls: ClassGroup) => void | Promise<void>;
2425 years: AcademicYear[];
2526 maxNameLen?: number;
26- maxGradeLen?: number;
27+ minGradeLevel?: number;
28+ maxGradeLevel?: number;
2729 }) {
2830 const t = useT();
2931 const [name, setName] = createSignal("");
30- const [grade, setGrade] = createSignal("");
32+ const [gradeLevel, setGradeLevel] = createSignal<number | null>(null);
3133 const [yearId, setYearId] = createSignal("");
3234 const [teacherId, setTeacherId] = createSignal("");
3335 const [error, setError] = createSignal("");
@@ -38,7 +40,7 @@ export function ClassEditPanel(props: {
3840 const c = props.cls;
3941 if (!props.open || !c) return;
4042 setName(c.name);
41- setGrade(c.grade ?? "");
43+ setGradeLevel(c.grade_level);
4244 setYearId(c.year ?? "");
4345 setTeacherId(c.teacher?.id ?? "");
4446 setError("");
@@ -51,7 +53,7 @@ export function ClassEditPanel(props: {
5153 setError("");
5254 setPending(true);
5355 try {
54- const saved = await patchClassById(c.id, { name: name().trim(), grade: grade().trim() || null, year: yearId() || null, teacher_id: teacherId() || null });
56+ const saved = await patchClassById(c.id, { name: name().trim(), ...(gradeLevel() !== null ? { grade_level: gradeLevel()! } : {}), year: yearId() || null, teacher_id: teacherId() || null });
5557 props.onOpenChange(false);
5658 await props.onSaved(saved);
5759 } catch (err) {
@@ -66,7 +68,7 @@ export function ClassEditPanel(props: {
6668 <form class="space-y-4" onSubmit={submit}>
6769 <div class="space-y-3">
6870 <div class="space-y-1.5"><Label for="edit-class-name">{t("classGroups.className")}</Label><Input id="edit-class-name" maxlength={props.maxNameLen} value={name()} onInput={(e) => setName(e.currentTarget.value)} /></div>
69- <div class="space-y-1.5"><Label for="edit-class-grade">{t("classGroups.grade")}</Label><Input id="edit-class-grade" maxlength={props.maxGradeLen} value={grade()} onInput={(e) => setGrade(e.currentTarget.value)} /></div>
71+ <div class="space-y-1.5"><Label for="edit-class-grade">{t("classGroups.grade")}</Label><GradeLevelSelect id="edit-class-grade" value={gradeLevel()} min={props.minGradeLevel} max={props.maxGradeLevel} onChange={setGradeLevel} /></div>
7072 <div class="space-y-1.5"><Label for="edit-class-year">{t("academicYears.year")}</Label><Select id="edit-class-year" value={yearId()} onChange={(e) => setYearId(e.currentTarget.value)}><option value="">{t("academicYears.unassigned")}</option><For each={props.years}>{(year) => <option value={year.id}>{year.name}</option>}</For></Select></div>
7173 <UserSearchSelect id="edit-class-teacher" label={t("classGroups.homeroomTeacher")} value={teacherId()} initialUser={props.cls?.teacher} onChange={setTeacherId} placeholder={t("classGroups.selectTeacher")} role="teacher" />
7274 </div>
src/components/classes/grade-level-select.tsxadded+35 -0
@@ -0,0 +1,35 @@
1+import { For } from "solid-js";
2+import { Select } from "@/components/ui/select";
3+import { gradeLevelLabel, gradeLevels } from "@/lib/grade-level";
4+import { useT } from "@/stores/preferences-context";
5+
6+/**
7+ * A pick on the grade ladder (0 = anaokulu .. 12). `value` null shows the
8+ * placeholder row — the ladder is required on a class, so a form checks it.
9+ */
10+export function GradeLevelSelect(props: {
11+ id: string;
12+ value: number | null;
13+ onChange: (level: number | null) => void;
14+ min?: number;
15+ max?: number;
16+ disabled?: boolean;
17+ error?: boolean;
18+}) {
19+ const t = useT();
20+ return (
21+ <Select
22+ id={props.id}
23+ value={props.value === null ? "" : String(props.value)}
24+ disabled={props.disabled}
25+ aria-invalid={props.error || undefined}
26+ onChange={(e) => {
27+ const raw = e.currentTarget.value;
28+ props.onChange(raw === "" ? null : Number(raw));
29+ }}
30+ >
31+ <option value="">{t("grade.select")}</option>
32+ <For each={gradeLevels(props.min, props.max)}>{(level) => <option value={String(level)}>{gradeLevelLabel(level, t)}</option>}</For>
33+ </Select>
34+ );
35+}
src/components/users/profile-memberships.tsxmodified+11 -9
@@ -8,6 +8,7 @@ import { TablePagination } from "@/components/ui/table-pagination";
88 import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
99 import { cn } from "@/lib/cn";
1010 import { personLabel } from "@/lib/person";
11+import { gradeLevelLabel } from "@/lib/grade-level";
1112 import { useT } from "@/stores/preferences-context";
1213
1314 const PAGE_SIZE = 5;
@@ -78,13 +79,9 @@ export function ProfileMemberships(props: {
7879 : t("classGroups.noTeacher")}
7980 </span>
8081 </span>
81- <Show when={c.grade}>
82- {(g) => (
83- <Badge variant="secondary" class="shrink-0 rounded-md">
84- {g()}
85- </Badge>
86- )}
87- </Show>
82+ <Badge variant="secondary" class="shrink-0 rounded-md">
83+ {gradeLevelLabel(c.grade_level, t)}
84+ </Badge>
8885 </li>
8986 )}
9087 </For>
@@ -112,7 +109,7 @@ export function ProfileMemberships(props: {
112109 <li>
113110 <Link
114111 to="/courses/$id"
115- params={{ id: c.id }}
112+ params={{ id: c.course }}
116113 class="flex items-center gap-3 rounded-lg border border-border/60 px-3 py-2.5 transition-colors hover:border-primary/40 hover:bg-muted/40"
117114 >
118115 <span
@@ -123,7 +120,12 @@ export function ProfileMemberships(props: {
123120 >
124121 <IconBook class="h-4 w-4" />
125122 </span>
126- <span class="min-w-0 flex-1 truncate text-sm font-medium">{c.title}</span>
123+ <span class="min-w-0 flex-1">
124+ <span class="block truncate text-sm font-medium">{c.title}</span>
125+ <Show when={c.class_name}>
126+ {(name) => <span class="block truncate text-xs text-muted-foreground">{name()}</span>}
127+ </Show>
128+ </span>
127129 <Badge variant="outline" class="shrink-0 rounded-md">{courseKindLabel(c.kind, t)}</Badge>
128130 </Link>
129131 </li>
src/i18n/locales/en.tsmodified+9 -4
@@ -116,13 +116,13 @@ export const en: Dict = {
116116 "classBlueprints.filterCourses": "Filter courses",
117117 "classBlueprints.noCourseMatch": "No course matches that filter.",
118118 "classBlueprints.savedMatched": "Blueprint saved and applied to {count} class(es) at this grade.",
119- "classBlueprints.noMatch": "Blueprint saved, but no class carries the grade \"{grade}\", so nothing was attached. Grades must match exactly — \"9\", \"9 \" and \"9-A\" are three different grades.",
119+ "classBlueprints.noMatch": "Blueprint saved, but no class is at {grade}, so nothing was attached.",
120120 "classBlueprints.delete": "Delete blueprint",
121121 "classBlueprints.deleteConfirm":
122- "Delete the blueprint for grade {grade}? The courses it attached are detached from every class at this grade. Hand-attached courses stay.",
122+ "Delete the {grade} blueprint? The courses it attached are detached from every class at this grade. Hand-attached courses stay.",
123123 "classBlueprints.deleted": "Blueprint deleted.",
124124 "classBlueprints.status": "Check sync",
125- "classBlueprints.statusTitle": "Sync status for grade {grade}",
125+ "classBlueprints.statusTitle": "Sync status for {grade}",
126126 "classBlueprints.statusEmpty": "Every section at this grade carries the full template.",
127127 "classBlueprints.statusSection": "Section",
128128 "classBlueprints.statusMissing": "Missing courses",
@@ -130,7 +130,7 @@ export const en: Dict = {
130130 "classBlueprints.applyHint": "Attaches this grade's blueprint courses to this class.",
131131 "classBlueprints.applyNoGrade": "Assign a grade to this class first.",
132132 "classBlueprints.applied": "Blueprint applied.",
133- "classBlueprints.noBlueprintForGrade": "There is no blueprint for grade {grade} yet.",
133+ "classBlueprints.noBlueprintForGrade": "There is no blueprint for {grade} yet.",
134134 "classBlueprints.conflictExists": "A blueprint already exists for this grade. Edit it from the list instead.",
135135 "classBlueprints.staleReload":
136136 "This blueprint changed while you were editing. The list has been refreshed — review it and save again.",
@@ -2456,4 +2456,9 @@ export const en: Dict = {
24562456 "errors.audienceOnlyDescription": "This view is shown only to the student or parent signed in to their own account; staff accounts do not open it.",
24572457 "errors.audienceOnlyWithAlternative": "This view is shown only to the student or parent signed in to their own account. The school-wide view of the same data is under management.",
24582458 "errors.openStaffView": "Open the management view",
2459+ "grade.kindergarten": "Kindergarten",
2460+ "grade.level": "Grade {level}",
2461+ "grade.select": "Select a grade",
2462+ "instances.teachers": "Teachers",
2463+ "instances.sectionsTruncated": "Showing {shown} of {total} sections; the full list is on the Classes page.",
24592464 };
src/i18n/locales/tr.tsmodified+9 -4
@@ -112,13 +112,13 @@ export const tr: Dict = {
112112 "classBlueprints.filterCourses": "Derslerde ara",
113113 "classBlueprints.noCourseMatch": "Bu aramayla eşleşen ders yok.",
114114 "classBlueprints.savedMatched": "Şablon kaydedildi ve bu seviyedeki {count} şubeye uygulandı.",
115- "classBlueprints.noMatch": "Şablon kaydedildi ama \"{grade}\" seviyesinde hiç şube yok, bu yüzden hiçbir şubeye ders eklenmedi. Seviye tam eşleşmeli — \"9\", \"9 \" ve \"9-A\" üç farklı seviyedir.",
115+ "classBlueprints.noMatch": "Şablon kaydedildi ama {grade} seviyesinde hiç şube yok, bu yüzden hiçbir şubeye ders eklenmedi.",
116116 "classBlueprints.delete": "Şablonu sil",
117117 "classBlueprints.deleteConfirm":
118- "{grade} seviyesinin şablonu silinsin mi? Şablonun eklediği dersler bu seviyedeki her şubeden çıkarılır. Elle eklenen dersler kalır.",
118+ "{grade} şablonu silinsin mi? Şablonun eklediği dersler bu seviyedeki her şubeden çıkarılır. Elle eklenen dersler kalır.",
119119 "classBlueprints.deleted": "Şablon silindi.",
120120 "classBlueprints.status": "Eşitleme kontrolü",
121- "classBlueprints.statusTitle": "{grade} seviyesi eşitleme durumu",
121+ "classBlueprints.statusTitle": "{grade} eşitleme durumu",
122122 "classBlueprints.statusEmpty": "Bu seviyedeki her şube şablonun tamamını taşıyor.",
123123 "classBlueprints.statusSection": "Şube",
124124 "classBlueprints.statusMissing": "Eksik dersler",
@@ -126,7 +126,7 @@ export const tr: Dict = {
126126 "classBlueprints.applyHint": "Bu seviyenin şablon derslerini bu şubeye ekler.",
127127 "classBlueprints.applyNoGrade": "Önce bu şubeye bir seviye ata.",
128128 "classBlueprints.applied": "Şablon uygulandı.",
129- "classBlueprints.noBlueprintForGrade": "{grade} seviyesi için henüz bir şablon yok.",
129+ "classBlueprints.noBlueprintForGrade": "{grade} için henüz bir şablon yok.",
130130 "classBlueprints.conflictExists": "Bu seviye için zaten bir şablon var. Bunun yerine listeden düzenle.",
131131 "classBlueprints.staleReload":
132132 "Sen düzenlerken bu şablon değişti. Liste yenilendi — gözden geçirip tekrar kaydet.",
@@ -2452,4 +2452,9 @@ export const tr: Dict = {
24522452 "errors.audienceOnlyDescription": "Bu görünüm yalnızca kendi hesabıyla giriş yapan öğrenci ya da veliye gösterilir; personel hesaplarında açılmaz.",
24532453 "errors.audienceOnlyWithAlternative": "Bu görünüm yalnızca kendi hesabıyla giriş yapan öğrenci ya da veliye gösterilir. Aynı bilgilerin okul geneli görünümü yönetim bölümünde.",
24542454 "errors.openStaffView": "Yönetim görünümünü aç",
2455+ "grade.kindergarten": "Anaokulu",
2456+ "grade.level": "{level}. sınıf",
2457+ "grade.select": "Seviye seçin",
2458+ "instances.teachers": "Öğretmenler",
2459+ "instances.sectionsTruncated": "{total} şubeden ilk {shown} tanesi gösteriliyor; tamamı Sınıflar sayfasında.",
24552460 };
src/i18n/messages.tsmodified+6 -1
@@ -2435,7 +2435,12 @@ export type MessageKey =
24352435 | "errors.parentOnlyTitle"
24362436 | "errors.audienceOnlyDescription"
24372437 | "errors.audienceOnlyWithAlternative"
2438- | "errors.openStaffView";
2438+ | "errors.openStaffView"
2439+ | "grade.kindergarten"
2440+ | "grade.level"
2441+ | "grade.select"
2442+ | "instances.teachers"
2443+ | "instances.sectionsTruncated";
24392444
24402445 export type Dict = Record<MessageKey, string>;
24412446
src/lib/command-search.test.tsmodified+3 -6
@@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
22
33 const api = vi.hoisted(() => ({
44 getCourses: vi.fn(),
5- getMyCourses: vi.fn(),
65 getExams: vi.fn(),
76 getHomework: vi.fn(),
87 getEvents: vi.fn(),
@@ -11,7 +10,6 @@ const api = vi.hoisted(() => ({
1110 }));
1211
1312 vi.mock("@/api/courses", () => ({ getCourses: api.getCourses }));
14-vi.mock("@/api/reports", () => ({ getMyCourses: api.getMyCourses }));
1513 vi.mock("@/api/exams", () => ({ getExams: api.getExams }));
1614 vi.mock("@/api/homework", () => ({ getHomework: api.getHomework }));
1715 vi.mock("@/api/events", () => ({ getEvents: api.getEvents }));
@@ -66,7 +64,6 @@ describe("loadCommandRecords", () => {
6664 beforeEach(() => {
6765 resetCommandRecordCache();
6866 api.getCourses.mockResolvedValue(page([{ id: "c1", title: "Biyoloji", description: "", kind: "course" }]));
69- api.getMyCourses.mockResolvedValue(page([{ id: "c9", title: "Fizik", description: "", kind: "course" }]));
7067 api.getExams.mockResolvedValue(
7168 page([
7269 { id: "e1", title: "Yazılı", description: "", class_course: "i1", starts_at: 5 },
@@ -81,10 +78,10 @@ describe("loadCommandRecords", () => {
8178 afterEach(() => vi.clearAllMocks());
8279
8380 test("a student reads their own courses and only exams in their own sections", async () => {
81+ // GET /courses is already scoped to the student's own courses.
8482 const out = await loadCommandRecords("student", ["course", "exam"]);
85- expect(api.getMyCourses).toHaveBeenCalled();
86- expect(api.getCourses).not.toHaveBeenCalled();
87- expect(out.map((r) => r.id)).toEqual(["c9", "e1"]);
83+ expect(api.getCourses).toHaveBeenCalled();
84+ expect(out.map((r) => r.id)).toEqual(["c1", "e1"]);
8885 expect(out[1].context).toBe("Biyoloji — 10-B");
8986 });
9087
src/lib/command-search.tsmodified+3 -4
@@ -3,7 +3,6 @@ import { getExams } from "@/api/exams";
33 import { getEvents } from "@/api/events";
44 import { getHomework } from "@/api/homework";
55 import { getMyInstances } from "@/api/instances";
6-import { getMyCourses } from "@/api/reports";
76 import type { Role } from "@/api/client";
87 import { LIST_CAP, loadCappedList } from "@/lib/capped-list";
98 import { loadInstanceLabels } from "@/lib/instance-labels";
@@ -71,9 +70,9 @@ export function filterCommandRecords(
7170 return out;
7271 }
7372
74-async function loadCourses(role: Role): Promise<CommandRecord[]> {
75- // As on /courses: a student's list is their own enrolments.
76- const page = role === "student" ? await getMyCourses() : await getCourses();
73+async function loadCourses(): Promise<CommandRecord[]> {
74+ // GET /courses is already scoped: a student's list is their own enrolments.
75+ const page = await getCourses();
7776 return page.items.map((course) => ({
7877 kind: "course",
7978 id: course.id,
src/lib/grade-level.tsadded+27 -0
@@ -0,0 +1,27 @@
1+import type { MessageKey } from "@/i18n/messages";
2+
3+type Translate = (key: MessageKey, params?: Record<string, string>) => string;
4+
5+/** The grade ladder the backend accepts: 0 (anaokulu) through 12. */
6+export const MIN_GRADE_LEVEL = 0;
7+export const MAX_GRADE_LEVEL = 12;
8+
9+/** "Anaokulu" at the floor, "9. sınıf" elsewhere. */
10+export function gradeLevelLabel(level: number, t: Translate): string {
11+ return level === 0 ? t("grade.kindergarten") : t("grade.level", { level: String(level) });
12+}
13+
14+/** Every rung between the published bounds, lowest first. */
15+export function gradeLevels(min = MIN_GRADE_LEVEL, max = MAX_GRADE_LEVEL): number[] {
16+ const levels: number[] = [];
17+ for (let level = min; level <= max; level++) levels.push(level);
18+ return levels;
19+}
20+
21+/**
22+ * The backend's own text for a rung ("Anaokulu", "1".."12") — what a RAG
23+ * scope pair names as `sinif`. Not a display string; use gradeLevelLabel.
24+ */
25+export function gradeLevelWireLabel(level: number): string {
26+ return level === 0 ? "Anaokulu" : String(level);
27+}
src/lib/question-generation.tsmodified+7 -4
@@ -2,6 +2,7 @@ import { getClasses } from "@/api/classes";
22 import type { ClassGroup, Course } from "@/api/client";
33 import { getCourseById } from "@/api/courses";
44 import { getMyInstances } from "@/api/instances";
5+import { gradeLevelWireLabel } from "@/lib/grade-level";
56 import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent";
67
78 /** Pages one request may name; a wider range is almost always a typo. */
@@ -54,7 +55,7 @@ export async function loadStudyScopes(): Promise<StudyScopeOption[]> {
5455 getMyInstances({ limit: 200 }),
5556 getClasses({ limit: 200 }).catch(() => ({ items: [] as ClassGroup[] })),
5657 ]);
57- const gradeOf = new Map(classes.items.map((klass) => [klass.id, klass.grade]));
58+ const gradeOf = new Map(classes.items.map((klass) => [klass.id, gradeLevelWireLabel(klass.grade_level)]));
5859 const courseIds = [...new Set(instances.items.map((instance) => instance.course))];
5960 const courses = await mapConcurrent(courseIds, FAN_OUT_LIMIT, (id) => getCourseById(id).catch(() => null));
6061 const courseById = new Map(courses.filter((course): course is Course => course !== null).map((course) => [course.id, course]));
@@ -63,10 +64,12 @@ export async function loadStudyScopes(): Promise<StudyScopeOption[]> {
6364 for (const instance of instances.items) {
6465 const course = courseById.get(instance.course);
6566 if (!course) continue;
66- const sinif = course.kind === "course" ? gradeOf.get(instance.class)?.trim() || null : null;
67- const key = `${course.title}\u0000${sinif ?? ""}`;
67+ const sinif = course.kind === "course" ? gradeOf.get(instance.class) ?? null : null;
68+ // The backend names a section's pair by its resolved title, not the catalog's.
69+ const ders = instance.title || course.title;
70+ const key = `${ders}\u0000${sinif ?? ""}`;
6871 if (!options.has(key)) {
69- options.set(key, { key, ders: course.title, sinif, course, label: sinif ? `${course.title} · ${sinif}` : course.title });
72+ options.set(key, { key, ders, sinif, course, label: sinif ? `${ders} · ${sinif}` : ders });
7073 }
7174 }
7275 return [...options.values()].sort((a, b) => a.label.localeCompare(b.label, "tr"));
src/lib/student-directory.tsmodified+1 -3
@@ -29,9 +29,7 @@ const collator = new Intl.Collator("tr", { numeric: true, sensitivity: "base" })
2929
3030 /** Class order a school reads rosters in: grade (9 before 10), then the şube name. */
3131 export function compareClasses(a: ClassGroup, b: ClassGroup): number {
32- const gradeA = Number.parseInt(a.grade ?? a.name, 10);
33- const gradeB = Number.parseInt(b.grade ?? b.name, 10);
34- if (Number.isFinite(gradeA) && Number.isFinite(gradeB) && gradeA !== gradeB) return gradeA - gradeB;
32+ if (a.grade_level !== b.grade_level) return a.grade_level - b.grade_level;
3533 return collator.compare(a.name, b.name);
3634 }
3735
src/pages/academic-years-page.tsxmodified+15 -19
@@ -30,6 +30,7 @@ import { TableRowActions } from "@/components/ui/table-row-actions";
3030 import { createFlash } from "@/lib/flash";
3131 import { formatDate } from "@/lib/format";
3232 import { usePreferences, useT } from "@/stores/preferences-context";
33+import { GradeLevelSelect } from "@/components/classes/grade-level-select";
3334
3435 const YEAR_PAGE_SIZE = 10;
3536
@@ -70,7 +71,8 @@ function AcademicYearsContent() {
7071 const [name, setName] = createSignal("");
7172 const [starts, setStarts] = createSignal("");
7273 const [ends, setEnds] = createSignal("");
73- const [promotions, setPromotions] = createSignal<GradePromotion[]>([]);
74+ // A row being written may still have a half unpicked.
75+ const [promotions, setPromotions] = createSignal<{ from_grade: number | null; to_grade: number | null }[]>([]);
7476 const [editing, setEditing] = createSignal<AcademicYear | null>(null);
7577 const [deleteTarget, setDeleteTarget] = createSignal<AcademicYear | null>(null);
7678 const [detail, setDetail] = createSignal<AcademicYear | null>(null);
@@ -120,9 +122,9 @@ function AcademicYearsContent() {
120122 }
121123 // A blank half is a half-written rule, not a policy — drop it rather than
122124 // sending a promotion the rollover cannot act on.
123- const grade_promotions = promotions()
124- .map((pair) => ({ from_grade: pair.from_grade.trim(), to_grade: pair.to_grade.trim() }))
125- .filter((pair) => pair.from_grade && pair.to_grade);
125+ const grade_promotions = promotions().filter(
126+ (pair): pair is GradePromotion => pair.from_grade !== null && pair.to_grade !== null,
127+ );
126128
127129 setPending(true);
128130 try {
@@ -346,7 +348,7 @@ function AcademicYearsContent() {
346348 size="sm"
347349 variant="outline"
348350 class="rounded-lg"
349- onClick={() => setPromotions((rows) => [...rows, { from_grade: "", to_grade: "" }])}
351+ onClick={() => setPromotions((rows) => [...rows, { from_grade: null, to_grade: null }])}
350352 >
351353 <IconPlus class="h-4 w-4" />
352354 {t("academicYears.addPromotion")}
@@ -355,24 +357,18 @@ function AcademicYearsContent() {
355357 <For each={promotions()}>
356358 {(pair, index) => (
357359 <div class="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_2.25rem] items-center gap-2">
358- <Input
359- aria-label={t("academicYears.fromGrade")}
360- class="h-9 rounded-md"
361- maxlength={20}
360+ <GradeLevelSelect
361+ id={`promotion-from-${index()}`}
362362 value={pair.from_grade}
363- placeholder={t("academicYears.fromGrade")}
364- onInput={(e) =>
365- setPromotions((rows) => rows.map((row, i) => (i === index() ? { ...row, from_grade: e.currentTarget.value } : row)))
363+ onChange={(level) =>
364+ setPromotions((rows) => rows.map((row, i) => (i === index() ? { ...row, from_grade: level } : row)))
366365 }
367366 />
368- <Input
369- aria-label={t("academicYears.toGrade")}
370- class="h-9 rounded-md"
371- maxlength={20}
367+ <GradeLevelSelect
368+ id={`promotion-to-${index()}`}
372369 value={pair.to_grade}
373- placeholder={t("academicYears.toGrade")}
374- onInput={(e) =>
375- setPromotions((rows) => rows.map((row, i) => (i === index() ? { ...row, to_grade: e.currentTarget.value } : row)))
370+ onChange={(level) =>
371+ setPromotions((rows) => rows.map((row, i) => (i === index() ? { ...row, to_grade: level } : row)))
376372 }
377373 />
378374 <Button
src/pages/calendar-page.test.tsxmodified+0 -1
@@ -25,7 +25,6 @@ vi.mock("@/api/exams", () => ({ getExams }));
2525 vi.mock("@/api/homework", () => ({ getHomework: vi.fn(async () => page([])) }));
2626 vi.mock("@/api/appointments", () => ({ getAppointments: vi.fn(async () => page([])) }));
2727 vi.mock("@/api/courses", () => ({ getCourses: vi.fn(async () => page([])) }));
28-vi.mock("@/api/reports", () => ({ getMyCourses: vi.fn(async () => page([])) }));
2928 vi.mock("@/api/instances", () => ({
3029 getMyInstances: vi.fn(async () => page([])),
3130 getInstanceSessions: vi.fn(async () => page([])),
src/pages/calendar-page.tsxmodified+2 -3
@@ -8,7 +8,6 @@ import { getHomework } from "@/api/homework";
88 import { getAppointments } from "@/api/appointments";
99 import { getCourses } from "@/api/courses";
1010 import { getInstanceSessions, getMyInstances } from "@/api/instances";
11-import { getMyCourses } from "@/api/reports";
1211 import type { Appointment, AppointmentStatus, Course } from "@/api/client";
1312 import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status";
1413 import { RouteGuard } from "@/components/layout/route-guard";
@@ -214,12 +213,12 @@ function CalendarContent() {
214213 // own `kind` is what separates them.
215214 const [sessions] = board.createResource(
216215 () => auth.user()?.role ?? null,
217- async (role) => {
216+ async () => {
218217 // Sessions hang off the instance (şube × ders) now; the catalog course is
219218 // still what says whether a meeting is a ders, an etüt or a kulüp.
220219 const [instances, courses] = await Promise.all([
221220 getMyInstances({ limit: 200 }),
222- role === "student" ? getMyCourses() : getCourses(),
221+ getCourses(),
223222 ]);
224223 const byId = new Map<string, Course>(courses.items.map((course) => [course.id, course]));
225224 const pages = await mapConcurrent(
src/pages/class-detail-page.tsxmodified+7 -5
@@ -43,6 +43,7 @@ import { matchesSearch } from "@/lib/search-text";
4343 import { createUrlString } from "@/lib/url-state";
4444 import { useAuth } from "@/stores/auth-context";
4545 import { useT } from "@/stores/preferences-context";
46+import { gradeLevelLabel } from "@/lib/grade-level";
4647 import { RecordNotFound } from "@/components/layout/record-not-found";
4748 import { isNotFoundError } from "@/lib/record-list-path";
4849
@@ -297,9 +298,9 @@ function ClassDetailContent() {
297298 size="sm"
298299 variant="outline"
299300 class={cn(ACTION_BUTTON, "w-full")}
300- disabled={pending() || !c().grade}
301- title={c().grade ? t("classBlueprints.applyHint") : t("classBlueprints.applyNoGrade")}
302- onClick={() => void applyBlueprint(c().grade ?? "")}
301+ disabled={pending()}
302+ title={t("classBlueprints.applyHint")}
303+ onClick={() => void applyBlueprint(gradeLevelLabel(c().grade_level, t))}
303304 >
304305 <IconListChecks class="h-4 w-4" />
305306 {t("classBlueprints.apply")}
@@ -332,7 +333,7 @@ function ClassDetailContent() {
332333 <div class="grid gap-3 border-t border-border-hairline pt-3 pb-1 text-sm grid-cols-2 lg:grid-cols-5">
333334 <div class={TILE}>
334335 <p class={TILE_LABEL}>{t("classGroups.grade")}</p>
335- <p class={TILE_VALUE}>{c().grade || "—"}</p>
336+ <p class={TILE_VALUE}>{gradeLevelLabel(c().grade_level, t)}</p>
336337 </div>
337338 <div class={TILE}>
338339 <p class={TILE_LABEL}>{t("academicYears.year")}</p>
@@ -428,7 +429,8 @@ function ClassDetailContent() {
428429 onOpenChange={setEditing}
429430 years={years.latest ?? []}
430431 maxNameLen={limits.latest?.course.max_class_name_len}
431- maxGradeLen={limits.latest?.course.max_class_grade_len}
432+ minGradeLevel={limits.latest?.course.min_grade_level}
433+ maxGradeLevel={limits.latest?.course.max_grade_level}
432434 onSaved={async () => { setFlash(t("common.saved")); await refresh(refetchClass); }}
433435 />
434436
src/pages/classes-page.test.tsxmodified+5 -4
@@ -29,12 +29,12 @@ vi.mock("@/stores/auth-context", () => ({
2929 vi.mock("@/api/classes", () => ({ getClasses, getClassMembers, postClass }));
3030 vi.mock("@/api/academic-years", () => ({ getAcademicYears: vi.fn(async () => ({ items: [] })) }));
3131 vi.mock("@/api/limits", () => ({
32- getLimits: vi.fn(async () => ({ course: { max_class_name_len: 60, max_class_grade_len: 10 } })),
32+ getLimits: vi.fn(async () => ({ course: { max_class_name_len: 60, min_grade_level: 0, max_grade_level: 12 } })),
3333 }));
3434 vi.mock("@/api/courses", () => ({ getCourses }));
3535 vi.mock("@/api/users", () => ({ getUserSearch: vi.fn(async () => ({ items: [] })) }));
3636
37-const createdClass = { id: "c-new", creator: null, name: "9-A", grade: "9", year: null, teacher: null };
37+const createdClass = { id: "c-new", creator: null, name: "9-A", grade_level: 9, year: null, teacher: null };
3838
3939 afterEach(() => {
4040 cleanup();
@@ -48,6 +48,7 @@ async function openCreateForm() {
4848
4949 fireEvent.click(await screen.findByRole("button", { name: /New class/ }));
5050 fireEvent.input(await screen.findByLabelText(/^Name/), { target: { value: "9-A" } });
51+ fireEvent.change(document.getElementById("class-grade")!, { target: { value: "9" } });
5152 fireEvent.click(screen.getByRole("button", { name: "Create" }));
5253 }
5354
@@ -61,14 +62,14 @@ test("creating a class opens the class the server made", async () => {
6162 await waitFor(() =>
6263 expect(navigate).toHaveBeenCalledWith({ to: "/management/classes/$id", params: { id: "c-new" } }),
6364 );
64- expect(postClass).toHaveBeenCalledWith({ name: "9-A", grade: undefined, year: undefined, teacher_id: undefined });
65+ expect(postClass).toHaveBeenCalledWith({ name: "9-A", grade_level: 9, year: undefined, teacher_id: undefined });
6566 });
6667
6768 test("a create whose blueprint left pairs behind holds the page until the report closes", async () => {
6869 postClass.mockResolvedValue({
6970 class: createdClass,
7071 skipped: [{ class: "c-new", class_name: "9-A", course: "k1", reason: "the class is already at its course ceiling" }],
71- stocked_from: "9",
72+ stocked_from: 9,
7273 });
7374 getCourses.mockResolvedValue({ items: [{ id: "k1", title: "Algebra" }] });
7475
src/pages/classes-page.tsxmodified+27 -21
@@ -32,6 +32,8 @@ import { compareClasses } from "@/lib/student-directory";
3232 import { createUrlString } from "@/lib/url-state";
3333 import { useAuth } from "@/stores/auth-context";
3434 import { useT } from "@/stores/preferences-context";
35+import { GradeLevelSelect } from "@/components/classes/grade-level-select";
36+import { gradeLevelLabel } from "@/lib/grade-level";
3537
3638 // A class's member count has no aggregate field on ClassGroup and no bulk
3739 // endpoint — each card's count is one `getClassMembers(id, {limit:1})` read
@@ -54,7 +56,8 @@ function ClassesContent() {
5456 const [gradeFilter, setGradeFilter] = createUrlString("grade", "all");
5557 const [showForm, setShowForm] = createSignal(false);
5658 const [name, setName] = createSignal("");
57- const [grade, setGrade] = createSignal("");
59+ const [gradeLevel, setGradeLevel] = createSignal<number | null>(null);
60+ const [gradeError, setGradeError] = createSignal("");
5861 const [yearId, setYearId] = createSignal("");
5962 const [teacherId, setTeacherId] = createSignal("");
6063 const [error, setError] = createSignal("");
@@ -75,15 +78,8 @@ function ClassesContent() {
7578 const listData = () => list.latest ?? list() ?? [];
7679 const yearName = (id: string | null) => (id ? years.latest?.find((year) => year.id === id)?.name ?? "—" : t("academicYears.unassigned"));
7780
78- // Grade tabs mirror Figma's Tümü/Lise/Ortaokul row structurally, but the
79- // labels are read from whatever `grade` values this school actually uses
80- // (freeform text on ClassGroup) instead of assuming a Turkish lise/ortaokul
81- // split that may not hold for every institution.
82- const grades = createMemo(() => {
83- const seen = new Set<string>();
84- for (const cls of listData()) if (cls.grade) seen.add(cls.grade);
85- return [...seen].sort((a, b) => a.localeCompare(b, "tr"));
86- });
81+ // The grade filter offers only the rungs this school's classes sit on.
82+ const grades = createMemo(() => [...new Set(listData().map((cls) => cls.grade_level))].sort((a, b) => a - b));
8783
8884 const memberCountIds = createMemo(() => {
8985 const ids = listData().map((cls) => cls.id);
@@ -104,7 +100,7 @@ function ClassesContent() {
104100 // Class by class (9-A, 9-B, 10-A…) until a column header re-sorts it.
105101 const gradeFiltered = createMemo(() => {
106102 const g = gradeFilter();
107- return (g === "all" ? listData() : listData().filter((cls) => cls.grade === g)).slice().sort(compareClasses);
103+ return (g === "all" ? listData() : listData().filter((cls) => String(cls.grade_level) === g)).slice().sort(compareClasses);
108104 });
109105 // A fresh array once the member counts land: the table redraws a row only
110106 // when its data changes, so the counts would otherwise stay "—".
@@ -145,7 +141,7 @@ function ClassesContent() {
145141 } catch (err) {
146142 // A 404 here means no blueprint covers this grade, not a missing class.
147143 setRowError(err instanceof ApiError && err.status === 404
148- ? t("classBlueprints.noBlueprintForGrade", { grade: cls.grade ?? "" })
144+ ? t("classBlueprints.noBlueprintForGrade", { grade: gradeLevelLabel(cls.grade_level, t) })
149145 : formatApiError(err));
150146 } finally {
151147 setPending(false);
@@ -162,12 +158,12 @@ function ClassesContent() {
162158 },
163159 {
164160 id: "grade",
165- accessorFn: (row) => row.grade ?? "",
161+ accessorFn: (row) => row.grade_level,
166162 header: t("classGroups.grade"),
167163 size: 90,
168164 minSize: 80,
169165 meta: { cellClass: "whitespace-nowrap text-center", align: "center" },
170- cell: (cell) => cell.row.original.grade || "—",
166+ cell: (cell) => gradeLevelLabel(cell.row.original.grade_level, t),
171167 },
172168 {
173169 id: "year",
@@ -213,7 +209,7 @@ function ClassesContent() {
213209 {
214210 label: t("classBlueprints.apply"),
215211 icon: <IconListChecks class="h-4 w-4" />,
216- disabled: pending() || !cell.row.original.grade,
212+ disabled: pending(),
217213 onSelect: () => void applyBlueprint(cell.row.original),
218214 },
219215 { label: t("classGroups.deleteClass"), icon: <IconTrash class="h-4 w-4" />, destructive: true, onSelect: () => setDeleteTarget(cell.row.original) },
@@ -236,15 +232,20 @@ function ClassesContent() {
236232 document.getElementById("class-name")?.focus();
237233 return;
238234 }
235+ const level = gradeLevel();
236+ if (level === null) {
237+ setGradeError(t("form.fieldRequired"));
238+ return;
239+ }
239240 setPending(true);
240241 try {
241242 const created = await postClass({
242243 name: name().trim(),
243- grade: grade().trim() || undefined,
244+ grade_level: level,
244245 year: yearId() || undefined,
245246 teacher_id: teacherId() || undefined,
246247 });
247- setName(""); setGrade(""); setYearId(""); setTeacherId(""); setShowForm(false);
248+ setName(""); setGradeLevel(null); setYearId(""); setTeacherId(""); setShowForm(false);
248249 // Reloading the list is housekeeping for a page we are leaving anyway: a
249250 // failure here used to be reported as if the class had not been created,
250251 // and it swallowed the navigation to the class that plainly existed.
@@ -297,7 +298,11 @@ function ClassesContent() {
297298 <form class="space-y-4" noValidate onSubmit={createClass}>
298299 <div class="space-y-3">
299300 <div class="space-y-1.5"><Label for="class-name">{t("classGroups.className")}<span class="ml-0.5 text-destructive-text">*</span></Label><Input id="class-name" required aria-required="true" maxlength={limits.latest?.course.max_class_name_len} value={name()} error={nameError()} onInput={(e) => { setName(e.currentTarget.value); setNameError(""); }} /></div>
300- <div class="space-y-1.5"><Label for="class-grade">{t("classGroups.grade")}</Label><Input id="class-grade" maxlength={limits.latest?.course.max_class_grade_len} value={grade()} onInput={(e) => setGrade(e.currentTarget.value)} /></div>
301+ <div class="space-y-1.5">
302+ <Label for="class-grade">{t("classGroups.grade")}<span class="ml-0.5 text-destructive-text">*</span></Label>
303+ <GradeLevelSelect id="class-grade" value={gradeLevel()} error={!!gradeError()} min={limits.latest?.course.min_grade_level} max={limits.latest?.course.max_grade_level} onChange={(level) => { setGradeLevel(level); setGradeError(""); }} />
304+ <Show when={gradeError()}><p class="text-xs font-medium text-destructive-text">{gradeError()}</p></Show>
305+ </div>
301306 <div class="space-y-1.5"><Label for="class-year">{t("academicYears.year")}</Label><Select id="class-year" value={yearId()} onChange={(e) => setYearId(e.currentTarget.value)}><option value="">{t("academicYears.unassigned")}</option><For each={years.latest ?? []}>{(year) => <option value={year.id}>{year.name}</option>}</For></Select></div>
302307 <UserSearchSelect id="class-teacher" label={t("classGroups.homeroomTeacher")} value={teacherId()} onChange={setTeacherId} placeholder={t("classGroups.selectTeacher")} role="teacher" />
303308 </div>
@@ -312,7 +317,8 @@ function ClassesContent() {
312317 onOpenChange={(open) => { if (!open) setEditTarget(null); }}
313318 years={years.latest ?? []}
314319 maxNameLen={limits.latest?.course.max_class_name_len}
315- maxGradeLen={limits.latest?.course.max_class_grade_len}
320+ minGradeLevel={limits.latest?.course.min_grade_level}
321+ maxGradeLevel={limits.latest?.course.max_grade_level}
316322 onSaved={async () => { setFlash(t("common.saved")); await refreshList(); }}
317323 />
318324
@@ -380,7 +386,7 @@ function ClassesContent() {
380386 columns={columns()}
381387 data={rows()}
382388 tableClass="table-fixed min-w-[48rem]"
383- searchPredicate={(cls, needle) => matchesSearch(needle, cls.name, cls.grade, cls.teacher ? personLabel(cls.teacher) : null)}
389+ searchPredicate={(cls, needle) => matchesSearch(needle, cls.name, gradeLevelLabel(cls.grade_level, t), cls.teacher ? personLabel(cls.teacher) : null)}
384390 filterPlaceholder={t("classGroups.searchPlaceholder")}
385391 filterHint={t("search.hint.classes")}
386392 enablePagination
@@ -395,7 +401,7 @@ function ClassesContent() {
395401 <Show when={grades().length > 0}>
396402 <DropdownSelect
397403 labelPrefix={t("classGroups.grade")}
398- options={[{ value: "all", label: t("common.all") }, ...grades().map((g) => ({ value: g, label: g }))]}
404+ options={[{ value: "all", label: t("common.all") }, ...grades().map((g) => ({ value: String(g), label: gradeLevelLabel(g, t) }))]}
399405 value={gradeFilter()}
400406 onChange={setGradeFilter}
401407 />
src/pages/course-detail-page.tsxmodified+47 -58
@@ -7,11 +7,9 @@ import { deleteCourseMemberByUserId } from "@/api/courses";
77 import { getCourseById } from "@/api/courses";
88 import { getCourseMembers } from "@/api/courses";
99 import { postCourseMember } from "@/api/courses";
10-import { getClasses, getClassInstances, getMyClasses } from "@/api/classes";
11-import { getMyInstances } from "@/api/instances";
12-import { getMyCourses } from "@/api/reports";
10+import { getCourses } from "@/api/courses";
1311 import { formatApiError } from "@/api/client";
14-import type { ClassCourse, ClassGroup, CourseKind, CourseMembership, Instance } from "@/api/client";
12+import type { CourseKind, CourseMembership, CourseSectionRef } from "@/api/client";
1513 import { CourseEditPanel } from "@/components/courses/course-edit-panel";
1614 import { CourseNotesPanel } from "@/components/courses/course-notes-panel";
1715 import { CourseSubjectsPanel } from "@/components/courses/course-subjects-panel";
@@ -19,7 +17,6 @@ import { RouteGuard } from "@/components/layout/route-guard";
1917 import { PageHeader } from "@/components/layout/page-header";
2018 import { Breadcrumbs } from "@/components/layout/breadcrumbs";
2119 import { Alert } from "@/components/ui/alert";
22-import { Badge } from "@/components/ui/badge";
2320 import { Button } from "@/components/ui/button";
2421 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
2522 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
@@ -38,9 +35,9 @@ import { hasMinRole } from "@/lib/roles";
3835 import { createUrlString } from "@/lib/url-state";
3936 import { cn } from "@/lib/cn";
4037 import { matchesSearch } from "@/lib/search-text";
38+import { gradeLevelLabel } from "@/lib/grade-level";
39+import { personLabel } from "@/lib/person";
4140
42-/** One row of the "taught in" list: an instance plus the şube's name. */
43-type SectionRow = { instance: Instance | ClassCourse; className: string };
4441
4542 // Literal class names so Tailwind sees every column count the tab strip can take.
4643 const TAB_GRID_COLS: Record<number, string> = { 1: "sm:grid-cols-1", 2: "sm:grid-cols-2", 3: "sm:grid-cols-3", 4: "sm:grid-cols-4" };
@@ -88,9 +85,10 @@ function CourseDetailContent() {
8885 return tabs.length === 0 || tabs.includes(requestedTab()) ? requestedTab() : tabs[0];
8986 };
9087 const [course, { refetch: refetchCourse }] = createResource(id, (courseId) => getCourseById(courseId));
88+ // GET /courses is already scoped to a student's own courses.
9189 const [mine] = createResource(
9290 () => (auth.user()?.role === "student" ? true : null),
93- async (enabled) => (enabled ? (await getMyCourses()).items : []),
91+ async (enabled) => (enabled ? (await getCourses()).items : []),
9492 );
9593
9694 // Catalog rights: the creator or a manager+. Teaching rights now live on the
@@ -106,37 +104,14 @@ function CourseDetailContent() {
106104 // — its students come from the şube that attached it.
107105 const hasMembers = () => course()?.kind === "club" || course()?.kind === "study";
108106
109- // The şubeler teaching this course. A student or teacher reads their own set
110- // in one call; the office has no course-scoped instance route, so it walks
111- // the class list instead (one call per class, capped by the page limit).
112- const [sections] = createResource(
113- () => (course() && tabOn.sections() ? { courseId: id(), office: isOffice() } : null),
114- async (args): Promise<SectionRow[]> => {
115- if (!args) return [];
116- if (!args.office) {
117- // `/instances/me` is the one instance list a student or teacher can
118- // read; `/classes/me` names the şubeler behind it (one call each).
119- const [instances, classes] = await Promise.all([
120- getMyInstances({ limit: 200 }),
121- getMyClasses({ limit: 200 }).catch(() => ({ items: [] as ClassGroup[] })),
122- ]);
123- const names = new Map(classes.items.map((klass) => [klass.id, klass.name]));
124- return instances.items
125- .filter((instance) => instance.course === args.courseId)
126- .map((instance) => ({ instance, className: names.get(instance.class) ?? "—" }));
127- }
128- const classes = (await getClasses({ limit: 200 })).items;
129- const perClass = await Promise.all(
130- classes.map(async (klass) => {
131- const instances = (await getClassInstances(klass.id, { limit: 200 })).items;
132- return instances
133- .filter((instance) => instance.course === args.courseId)
134- .map((instance) => ({ instance, className: klass.name }));
135- }),
136- );
137- return perClass.flat();
138- },
139- );
107+ // The şubeler teaching this course ride the catalog row itself, already
108+ // narrowed to the sections this reader reaches and capped at
109+ // limits.course.max_course_sections; class_course_count keeps the total.
110+ const sections = () => course()?.sections ?? [];
111+ const sectionsTruncated = () => {
112+ const c = course();
113+ return !!c && isOffice() && c.class_course_count > c.sections.length;
114+ };
140115
141116 const [members, { refetch: refetchMembers }] = createResource(
142117 () => (hasMembers() && canManageCatalog() ? id() : null),
@@ -166,47 +141,56 @@ function CourseDetailContent() {
166141 const courseKindLabel = (value: CourseKind | undefined) =>
167142 value === "study" ? t("courses.kind.study") : value === "club" ? t("courses.kind.club") : t("courses.kind.course");
168143 const courseListSearch = (value: CourseKind | undefined) => (value ? ({ kind: value } as never) : ({} as never));
169- const sectionCount = createMemo(() => sections()?.length ?? 0);
144+ const sectionCount = createMemo(() => sections().length);
170145 const visibleSections = createMemo(() => {
171146 const query = sectionSearch().trim();
172- return query ? (sections() ?? []).filter((section) => matchesSearch(query, section.className)) : sections() ?? [];
147+ return query
148+ ? sections().filter((section) => matchesSearch(query, section.class_name, section.title, ...section.teachers.map(personLabel)))
149+ : sections();
173150 });
174151 const memberUserIds = () => (members() ?? []).map((row) => row.user.id);
175152
176- const sectionColumns = createMemo<ColumnDef<SectionRow>[]>(() => [
153+ const sectionColumns = createMemo<ColumnDef<CourseSectionRef>[]>(() => [
177154 {
178155 id: "class",
179- accessorFn: (row) => row.className,
156+ accessorFn: (row) => row.class_name,
180157 header: t("classGroups.className"),
181158 meta: { cellClass: "font-medium" },
182159 cell: (cell) => (
183- <Link to="/instances/$id" params={{ id: cell.row.original.instance.id }} class="hover:text-primary-text hover:underline">
184- {cell.row.original.className}
160+ <Link to="/instances/$id" params={{ id: cell.row.original.id }} class="hover:text-primary-text hover:underline">
161+ {cell.row.original.class_name}
185162 </Link>
186163 ),
187164 },
165+ {
166+ id: "title",
167+ accessorFn: (row) => row.title,
168+ header: t("form.title"),
169+ },
170+ {
171+ id: "grade",
172+ accessorFn: (row) => row.grade_level,
173+ header: t("classGroups.grade"),
174+ cell: (cell) => gradeLevelLabel(cell.row.original.grade_level, t),
175+ },
176+ {
177+ id: "teachers",
178+ accessorFn: (row) => row.teachers.map(personLabel).join(", "),
179+ header: t("instances.teachers"),
180+ cell: (cell) => cell.row.original.teachers.map(personLabel).join(", ") || "—",
181+ },
188182 {
189183 id: "dersSaati",
190- accessorFn: (row) => row.instance.ders_saati,
184+ accessorFn: (row) => row.ders_saati,
191185 header: t("instances.dersSaati"),
192186 meta: { cellClass: "" },
193187 },
194188 {
195189 id: "roster",
196- accessorFn: (row) => row.instance.enrollment_count,
190+ accessorFn: (row) => row.enrollment_count,
197191 header: t("courses.roster"),
198192 meta: { cellClass: "" },
199193 },
200- {
201- id: "karne",
202- accessorFn: (row) => (row.instance.counts_toward_karne ? t("common.yes") : t("common.no")),
203- header: t("instances.countsTowardKarne"),
204- cell: (cell) => (
205- <Badge variant={cell.row.original.instance.counts_toward_karne ? "secondary" : "outline"} class="rounded-full">
206- {cell.row.original.instance.counts_toward_karne ? t("common.yes") : t("common.no")}
207- </Badge>
208- ),
209- },
210194 ]);
211195
212196 const memberColumns = createMemo<ColumnDef<CourseMembership>[]>(() => [
@@ -439,8 +423,13 @@ function CourseDetailContent() {
439423 enablePagination
440424 pageSize={10}
441425 empty={t("common.noMatches")}
442- onRowClick={(row) => void navigate({ to: "/instances/$id", params: { id: row.instance.id } })}
426+ onRowClick={(row) => void navigate({ to: "/instances/$id", params: { id: row.id } })}
443427 />
428+ <Show when={sectionsTruncated()}>
429+ <p class="text-xs text-muted-foreground">
430+ {t("instances.sectionsTruncated", { shown: String(sections().length), total: String(course()?.class_course_count ?? 0) })}
431+ </p>
432+ </Show>
444433 </Show>
445434 </Suspense>
446435 </TabsContent>
src/pages/courses-page.test.tsxmodified+5 -7
@@ -3,9 +3,8 @@ import type { JSX } from "solid-js";
33 import CoursesPage from "@/pages/courses-page";
44 import { PreferencesProvider } from "@/stores/preferences-context";
55
6-const { getCourses, getMyCourses, navigate } = vi.hoisted(() => ({
6+const { getCourses, navigate } = vi.hoisted(() => ({
77 getCourses: vi.fn(),
8- getMyCourses: vi.fn(),
98 navigate: vi.fn(),
109 }));
1110
@@ -27,7 +26,6 @@ vi.mock("@/api/courses", () => ({
2726 getCourses,
2827 postCourse: vi.fn(),
2928 }));
30-vi.mock("@/api/reports", () => ({ getMyCourses }));
3129 vi.mock("@/api/limits", () => ({ getLimits: vi.fn() }));
3230
3331 afterEach(() => {
@@ -35,8 +33,9 @@ afterEach(() => {
3533 vi.clearAllMocks();
3634 });
3735
36+// GET /courses is scoped server-side: a student reads only what they take.
3837 test("student class directory uses only enrolled-course data", async () => {
39- getMyCourses.mockResolvedValue({
38+ getCourses.mockResolvedValue({
4039 items: [
4140 {
4241 id: "course-1",
@@ -75,13 +74,12 @@ test("student class directory uses only enrolled-course data", async () => {
7574
7675 expect(await screen.findByRole("button", { name: /^Algebra/ })).toBeTruthy();
7776 expect(screen.getAllByText("Enrolled")).toHaveLength(3);
78- expect(getMyCourses).toHaveBeenCalledWith();
79- expect(getCourses).not.toHaveBeenCalled();
77+ expect(getCourses).toHaveBeenCalledWith();
8078
8179 fireEvent.click(screen.getByRole("tab", { name: "Study" }));
8280 expect(await screen.findByRole("button", { name: /^Study Lab/ })).toBeTruthy();
8381 expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull();
84- expect(getMyCourses).toHaveBeenCalledTimes(1);
82+ expect(getCourses).toHaveBeenCalledTimes(1);
8583 const tabNavigation = navigate.mock.calls.at(-1)?.[0] as { to: string; replace: boolean; search: (prev: Record<string, unknown>) => Record<string, unknown> };
8684 expect(tabNavigation.to).toBe("/courses");
8785 expect(tabNavigation.replace).toBe(true);
src/pages/courses-page.tsxmodified+2 -2
@@ -3,7 +3,6 @@ import { createResource } from "@/lib/create-resource";
33 import { useNavigate, useSearch } from "@tanstack/solid-router";
44 import type { ColumnDef } from "@tanstack/solid-table";
55 import { deleteCourseById, getCourses, postCourse } from "@/api/courses";
6-import { getMyCourses } from "@/api/reports";
76 import { getLimits } from "@/api/limits";
87 import { formatApiError, type Course, type CourseKind } from "@/api/client";
98 import { CourseEditPanel } from "@/components/courses/course-edit-panel";
@@ -72,7 +71,8 @@ function CoursesContent() {
7271 const [limits, { refetch: refetchLimits }] = createResource(() => canCreate() ? getLimits() : null);
7372 const [list, { refetch }] = createResource(
7473 () => auth.user()?.role ?? null,
75- async (role) => role === "student" ? getMyCourses() : getCourses(),
74+ // Scoped server-side: a student reads only the courses they take.
75+ () => getCourses(),
7676 );
7777 const listData = () => list.latest ?? list();
7878 // A memo: the table must see one array per change, not a fresh one per read.
src/pages/dashboard-page.test.tsxmodified+0 -1
@@ -78,7 +78,6 @@ vi.mock("@/api/sessions", () => ({
7878 getSessionAttendance: async () => ({ items: [], total: 0, limit: 1, offset: 0 }),
7979 }));
8080 vi.mock("@/api/reports", () => ({
81- getMyCourses: async () => page([course]),
8281 getMyMarks: async () => (calls.push("marks"), {
8382 overall_average: 82.5,
8483 courses: [{
src/pages/dashboard-page.tsxmodified+2 -2
@@ -15,7 +15,7 @@ import { getMealMenus } from "@/api/meals";
1515 import { getMyStudents } from "@/api/parents";
1616 import { getPaymentStatementByUserId } from "@/api/payments";
1717 import { getPomodoroMe } from "@/api/pomodoro";
18-import { getMyAttendance, getMyCourses, getMyMarks, getUserAttendance } from "@/api/reports";
18+import { getMyAttendance, getMyMarks, getUserAttendance } from "@/api/reports";
1919 import { getTime } from "@/api/time/getTime";
2020 import { getUsers } from "@/api/users";
2121 import { RouteGuard } from "@/components/layout/route-guard";
@@ -179,7 +179,7 @@ function DashboardContent() {
179179 // excludes studies and clubs has to be counted here over the whole list.
180180 const [courses] = createResource(
181181 () => role() === "parent" || !on("courses") ? null : role(),
182- (currentRole) => quiet(currentRole === "student" ? getMyCourses() : getCourses()),
182+ () => quiet(getCourses()),
183183 );
184184 const courseTitleOf = (courseId: string) => courses()?.items.find((course) => course.id === courseId)?.title ?? "…";
185185 const courseCount = () => (courses.error ? "—" : String((courses()?.items ?? []).filter((course) => course.kind === "course").length));
src/pages/profile-page.tsxmodified+2 -3
@@ -26,6 +26,7 @@ import { genderLabel } from "@/lib/gender";
2626 import { personLabel } from "@/lib/person";
2727 import { studentInfoSource } from "@/lib/student-info-access";
2828 import { useAuth } from "@/stores/auth-context";
29+import { gradeLevelLabel } from "@/lib/grade-level";
2930 import { useT } from "@/stores/preferences-context";
3031
3132 export default function ProfilePage() {
@@ -189,9 +190,7 @@ function ProfileContent() {
189190 <IconSchool class="h-4 w-4 text-muted-foreground" />
190191 {c().name}
191192 </span>
192- <Show when={c().grade}>
193- {(g) => <Badge variant="secondary" class="rounded-md">{g()}</Badge>}
194- </Show>
193+ <Badge variant="secondary" class="rounded-md">{gradeLevelLabel(c().grade_level, t)}</Badge>
195194 <span class="text-muted-foreground">
196195 ·{" "}
197196 {currentClass()?.teacher