diff --git a/src/api/__tests__/academic-years/academic-years.test.ts b/src/api/__tests__/academic-years/academic-years.test.ts index d3eb9b9..933ba92 100644 --- a/src/api/__tests__/academic-years/academic-years.test.ts +++ b/src/api/__tests__/academic-years/academic-years.test.ts @@ -41,7 +41,7 @@ describe("academic years API", () => { name: "2026-2027", starts_at: 1780000000000, ends_at: 1810000000000, - grade_promotions: [{ from_grade: "5", to_grade: "6" }], + grade_promotions: [{ from_grade: 5, to_grade: 6 }], }; await postAcademicYear(body); diff --git a/src/api/__tests__/classes/classes.test.ts b/src/api/__tests__/classes/classes.test.ts index 41999e6..513f58b 100644 --- a/src/api/__tests__/classes/classes.test.ts +++ b/src/api/__tests__/classes/classes.test.ts @@ -33,7 +33,7 @@ describe("classes API", () => { it("postClass POSTs /classes and returns the create envelope", async () => { const envelope = { class: { id: "c1" }, skipped: [], stocked_from: null }; mockFetchSuccess(envelope); - const body = { name: "9-A", grade: "9", year: "y1" }; + const body = { name: "9-A", grade_level: 9, year: "y1" }; const created = await postClass(body); expect(created).toEqual(envelope); expect(created.class.id).toBe("c1"); @@ -75,7 +75,7 @@ describe("classes API", () => { it("patchClassById PATCHes /classes/:id with the body", async () => { mockFetchSuccess({ id: "c1" }); - const body = { name: "9-B", grade: null, term_id: null }; + const body = { name: "9-B", grade_level: 10, year: null }; await patchClassById("c1", body); const [url, init] = lastFetchCall(); expect(url).toBe("/api/classes/c1"); @@ -144,8 +144,8 @@ describe("classes API", () => { }); it("postClassBlueprint POSTs /classes/blueprints with the body", async () => { - mockFetchSuccess({ blueprint: { grade: "9", courses: [], creator: {} }, matched: 2, skipped: [] }); - const body = { grade: "9", course_ids: ["co1", "co2"] }; + mockFetchSuccess({ blueprint: { grade_level: 9, courses: [], creator: {} }, matched: 2, skipped: [] }); + const body = { grade_level: 9, course_ids: ["co1", "co2"] }; await postClassBlueprint(body); const [url, init] = lastFetchCall(); expect(url).toBe("/api/classes/blueprints"); @@ -160,17 +160,17 @@ describe("classes API", () => { expect(url).toBe("/api/classes/blueprints?limit=20&offset=40"); }); - it("getClassBlueprintByGrade encodes the grade, which is the record key", async () => { - mockFetchSuccess({ grade: "9/A", courses: [], creator: {} }); - await getClassBlueprintByGrade("9/A"); + it("getClassBlueprintByGrade keys the blueprint by its grade level", async () => { + mockFetchSuccess({ grade_level: 0, courses: [], creator: {} }); + await getClassBlueprintByGrade(0); const [url] = lastFetchCall(); - expect(url).toBe("/api/classes/blueprints/9%2FA"); + expect(url).toBe("/api/classes/blueprints/0"); }); it("patchClassBlueprintByGrade PATCHes the whole course set", async () => { - mockFetchSuccess({ blueprint: { grade: "9", courses: [], creator: {} }, matched: 2, skipped: [] }); + mockFetchSuccess({ blueprint: { grade_level: 9, courses: [], creator: {} }, matched: 2, skipped: [] }); const body = { course_ids: ["co1"] }; - await patchClassBlueprintByGrade("9", body); + await patchClassBlueprintByGrade(9, body); const [url, init] = lastFetchCall(); expect(url).toBe("/api/classes/blueprints/9"); expect(init?.method).toBe("PATCH"); @@ -179,9 +179,9 @@ describe("classes API", () => { it("deleteClassBlueprintByGrade DELETEs /classes/blueprints/:grade", async () => { mockFetch204(); - await deleteClassBlueprintByGrade("9/A"); + await deleteClassBlueprintByGrade(11); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/classes/blueprints/9%2FA"); + expect(url).toBe("/api/classes/blueprints/11"); expect(init?.method).toBe("DELETE"); }); @@ -195,12 +195,12 @@ describe("classes API", () => { }); it("getClassBlueprintStatus GETs /classes/blueprints/:grade/status", async () => { - const mockStatus = { grade: "9/A", courses: ["co1"], matched: 3, sections: [] }; + const mockStatus = { grade_level: 9, courses: ["co1"], matched: 3, sections: [] }; mockFetchSuccess(mockStatus); - const result = await getClassBlueprintStatus("9/A"); + const result = await getClassBlueprintStatus(9); expect(result).toEqual(mockStatus); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/classes/blueprints/9%2FA/status"); + expect(url).toBe("/api/classes/blueprints/9/status"); expect(init?.method).toBe("GET"); }); }); diff --git a/src/api/classes/deleteClassBlueprintByGrade.ts b/src/api/classes/deleteClassBlueprintByGrade.ts index 3f7f3b2..67e4a69 100644 --- a/src/api/classes/deleteClassBlueprintByGrade.ts +++ b/src/api/classes/deleteClassBlueprintByGrade.ts @@ -2,6 +2,6 @@ import { client } from "../client"; // Detaches every course this blueprint attached, across every class at the // grade, then drops the template. Hand-attached courses stay. -export function deleteClassBlueprintByGrade(grade: string): Promise { - return client(`/classes/blueprints/${encodeURIComponent(grade)}`, { method: "DELETE" }); +export function deleteClassBlueprintByGrade(gradeLevel: number): Promise { + return client(`/classes/blueprints/${gradeLevel}`, { method: "DELETE" }); } diff --git a/src/api/classes/getClassBlueprintByGrade.ts b/src/api/classes/getClassBlueprintByGrade.ts index f86444c..ae8e04e 100644 --- a/src/api/classes/getClassBlueprintByGrade.ts +++ b/src/api/classes/getClassBlueprintByGrade.ts @@ -1,8 +1,7 @@ import { client } from "../client"; import type { ClassBlueprint } from "../client"; -// The grade label is the record key and is free text, so it must be encoded — -// a grade like "9/A" would otherwise read as a second path segment. -export function getClassBlueprintByGrade(grade: string, signal?: AbortSignal): Promise { - return client(`/classes/blueprints/${encodeURIComponent(grade)}`, { signal }); +// The grade level (0..12) is the record key. +export function getClassBlueprintByGrade(gradeLevel: number, signal?: AbortSignal): Promise { + return client(`/classes/blueprints/${gradeLevel}`, { signal }); } diff --git a/src/api/classes/getClassBlueprintStatus.ts b/src/api/classes/getClassBlueprintStatus.ts index d43d04f..82117d3 100644 --- a/src/api/classes/getClassBlueprintStatus.ts +++ b/src/api/classes/getClassBlueprintStatus.ts @@ -1,6 +1,6 @@ import { client } from "../client"; import type { BlueprintStatus } from "../client"; -export function getClassBlueprintStatus(grade: string, signal?: AbortSignal): Promise { - return client(`/classes/blueprints/${encodeURIComponent(grade)}/status`, { signal }); +export function getClassBlueprintStatus(gradeLevel: number, signal?: AbortSignal): Promise { + return client(`/classes/blueprints/${gradeLevel}/status`, { signal }); } diff --git a/src/api/classes/patchClassBlueprintByGrade.ts b/src/api/classes/patchClassBlueprintByGrade.ts index af17af0..70c8117 100644 --- a/src/api/classes/patchClassBlueprintByGrade.ts +++ b/src/api/classes/patchClassBlueprintByGrade.ts @@ -9,10 +9,10 @@ export type UpdateBlueprintBody = { course_ids: string[] }; // A 409 means the blueprint changed since it was read — there is no version to // echo back, so re-read it and let the user resubmit from the fresh list. export function patchClassBlueprintByGrade( - grade: string, + gradeLevel: number, body: UpdateBlueprintBody, ): Promise { - return client(`/classes/blueprints/${encodeURIComponent(grade)}`, { + return client(`/classes/blueprints/${gradeLevel}`, { method: "PATCH", body, }); diff --git a/src/api/classes/patchClassById.ts b/src/api/classes/patchClassById.ts index e5b7f64..d390de1 100644 --- a/src/api/classes/patchClassById.ts +++ b/src/api/classes/patchClassById.ts @@ -1,10 +1,11 @@ import { client } from "../client"; import type { ClassGroup } from "../client"; -// Omit a field to keep it; send null on grade/year/teacher_id to clear/unlink it. +// Omit a field to keep it; send null on year/teacher_id to clear/unlink it. The +// grade is required on every class, so `grade_level` can be reset, never cleared. export type UpdateClassBody = { name?: string; - grade?: string | null; + grade_level?: number; /** The academic year (`getAcademicYears`) the şube sits in. */ year?: string | null; teacher_id?: string | null; diff --git a/src/api/classes/postClass.ts b/src/api/classes/postClass.ts index aa9c2e4..564f764 100644 --- a/src/api/classes/postClass.ts +++ b/src/api/classes/postClass.ts @@ -3,7 +3,8 @@ import type { CreateClassResponse } from "../client"; // `year` is the academic year (`getAcademicYears`) — what binds the şube to a // karne and to the rollover. A şube with no year takes no exam. -export type CreateClassBody = { name: string; grade?: string; year?: string; teacher_id?: string }; +// `grade_level` is the rung on the grade ladder, 0 (anaokulu) .. 12; required. +export type CreateClassBody = { name: string; grade_level: number; year?: string; teacher_id?: string }; // The 201 is a create envelope, not the bare class: its `class` is what the // route navigates to, and its `skipped` is the blueprint fallout the caller diff --git a/src/api/classes/postClassBlueprint.ts b/src/api/classes/postClassBlueprint.ts index f9114a1..d11a031 100644 --- a/src/api/classes/postClassBlueprint.ts +++ b/src/api/classes/postClassBlueprint.ts @@ -1,7 +1,7 @@ import { client } from "../client"; import type { BlueprintResult } from "../client"; -export type CreateBlueprintBody = { grade: string; course_ids: string[] }; +export type CreateBlueprintBody = { grade_level: number; course_ids: string[] }; // Manager+. Creates the blueprint and immediately applies it to every existing // class at that grade; pairs that could not land come back in `skipped`. diff --git a/src/api/client/client.ts b/src/api/client/client.ts index c8e7abb..3603c0a 100644 --- a/src/api/client/client.ts +++ b/src/api/client/client.ts @@ -356,6 +356,38 @@ const API_ERROR_CODE_MESSAGES: Record = { tr: "Öğrenci eklenirken şubenin derslerinden biri kaldırıldı. Sayfayı yenileyip tekrar dene.", }, student_number_taken: STUDENT_NUMBER_TAKEN, + session_time_taken: { + en: "Another lesson of this section already starts at this time. Pick a different start time.", + tr: "Bu şubenin başka bir dersi zaten bu saatte başlıyor. Farklı bir başlangıç saati seç.", + }, + offering_exists: { + en: "This course already has a template for this grade. Edit the existing template instead.", + tr: "Bu dersin bu seviye için zaten bir şablonu var. Bunun yerine mevcut şablonu düzenle.", + }, + offering_in_use: { + en: "Classes still teach from this template. Detach the course from those classes first.", + tr: "Bu şablondan hâlâ ders işleyen şubeler var. Önce dersi o şubelerden çıkar.", + }, + slot_overlap: { + en: "Another slot on this day overlaps this time window. Pick a different time.", + tr: "Bu gündeki başka bir ders saati bu zaman aralığıyla çakışıyor. Farklı bir saat seç.", + }, + slot_cap: { + en: "This weekly plan already holds the maximum number of slots. Remove one before adding another.", + tr: "Bu haftalık plan en fazla ders saati sayısına ulaştı. Yenisini eklemeden önce birini kaldır.", + }, + unknown_exam_kind: { + en: "This exam kind is not one the school uses. Pick a kind from the school settings.", + tr: "Bu sınav türü okulun kullandığı türlerden biri değil. Okul ayarlarındaki türlerden birini seç.", + }, + instance_has_no_weekly_plan: { + en: "This section has no weekly plan yet. Add slots before generating lessons.", + tr: "Bu şubenin henüz haftalık planı yok. Ders üretmeden önce ders saati ekle.", + }, + instance_has_no_teacher: { + en: "No teacher is assigned to this section. Assign a teacher before generating lessons.", + tr: "Bu şubeye atanmış öğretmen yok. Ders üretmeden önce bir öğretmen ata.", + }, not_ready: { en: "This audio is not ready yet. Wait for it to finish and try again.", tr: "Bu ses kaydı henüz hazır değil. Tamamlanmasını bekleyip tekrar dene.", diff --git a/src/api/client/types.ts b/src/api/client/types.ts index fa006ad..e2c74fa 100644 --- a/src/api/client/types.ts +++ b/src/api/client/types.ts @@ -110,9 +110,20 @@ export type EarnedBadge = { id: string; earned_at: number }; export type AvatarMeta = { content_type: string; size: number }; -export type ProfileClassRef = { id: string; name: string; grade: string | null }; +export type ProfileClassRef = { id: string; name: string; grade_level: number }; -export type ProfileCourseRef = { id: string; title: string; kind: CourseKind }; +// One class section a profile lists, never the catalog row: `id` is the +// instance id, `title` its resolved title. `class`, `class_name` and +// `grade_level` read null for a viewer below the classes-block bar. +export type ProfileCourseRef = { + id: string; + course: string; + class: string | null; + class_name: string | null; + title: string; + grade_level: number | null; + kind: CourseKind; +}; // Lifetime counters behind the badge ladders, plus the two live totals the // capped `classes`/`courses` lists would otherwise hide. @@ -335,17 +346,80 @@ export type Course = { class_course_count: number; // Individual club/etut memberships on the catalog row itself. course_membership_count: number; + // The sections teaching it, capped at limits.course.max_course_sections + // (class_course_count keeps the true total) and filtered to what the + // reader reaches. + sections: CourseSectionRef[]; }; +// One class section of a catalog course, as a course row or GET /courses/me +// lists it: `id` is the instance id, `title` and `ders_saati` resolved. +export type CourseSectionRef = { + id: string; + course: string; + class: string; + class_name: string; + title: string; + grade_level: number; + ders_saati: number; + teachers: PersonRef[]; + enrollment_count: number; +}; + +/** One exam kind's effective weight. */ +export type ExamWeightEntry = { kind: string; weight: number }; + +/** + * One slot of a weekly plan. `starts_at`/`ends_at` are minutes past midnight + * (540 = 09:00), `weekday` 1..7 (Monday first). + */ +export type WeeklySlot = { + id: string; + weekday: number; + starts_at: number; + ends_at: number; + topic?: string | null; +}; + +/** The override fields POST /instances/{id}/reset clears back to inherit. */ +export type InstanceOverrideField = + | "title" + | "description" + | "ders_saati" + | "counts_toward_karne" + | "subjects" + | "exam_weights" + | "weekly_plan"; + // One catalog course as one sube teaches it. This is what carries the roster, // the exams, the sessions and the karne weight. +// +// Every content field is resolved: a scalar runs section override -> the +// grade-level offering -> catalog/constant, and `*_overridden` tells the +// section's own value from an inherited one. The three sets (subjects, exam +// weights, weekly plan) follow a flag: `*_inherited: false` means the +// section's own rows are authoritative, even when empty. export type Instance = { id: string; class: string; course: string; + // The grade-level template (GET /offerings/{id}) unset fields inherit from. + offering: string; + title: string; + title_overridden: boolean; + description: string; + description_overridden: boolean; // Weekly lesson hours; the instance's weight in the year's karne average. ders_saati: number; + ders_saati_overridden: boolean; counts_toward_karne: boolean; + counts_toward_karne_overridden: boolean; + subjects_inherited: boolean; + subjects: Subject[]; + exam_weights_inherited: boolean; + exam_weights: ExamWeightEntry[]; + weekly_plan_inherited: boolean; + weekly_plan: WeeklySlot[]; enrollment_count: number; teachers: PersonRef[]; }; @@ -360,10 +434,10 @@ export type CourseMembership = { created_at: number; }; -/** One sınıf-geçme pair: the grade label students move to at rollover. */ +/** One sınıf-geçme pair: the grade level (0..12) students move to at rollover. */ export type GradePromotion = { - from_grade: string; - to_grade: string; + from_grade: number; + to_grade: number; }; // An academic year: the calendar structure dönemler and şubeler hang off. @@ -423,7 +497,8 @@ export type ClassGroup = { // GET /classes/user/{user}). creator: PersonRef | null; name: string; - grade: string | null; + // The class's rung on the grade ladder, 0 (anaokulu) .. 12. Required. + grade_level: number; // The academic year (AcademicYear id) the sube sits in; what binds it to a // karne and to the rollover. Null when none is set. year: string | null; @@ -436,7 +511,7 @@ export type ClassGroup = { // that stocked it. `skipped` is empty when the template took every course, and // always empty when no template covered the grade; `stocked_from` is null in // that second case. -export type CreateClassResponse = { class: ClassGroup; skipped: BlueprintSkip[]; stocked_from: string | null }; +export type CreateClassResponse = { class: ClassGroup; skipped: BlueprintSkip[]; stocked_from: number | null }; export type ClassMember = { id: string; @@ -451,9 +526,13 @@ export type ClassMember = { source_class_group: string | null; }; -// The instance as the class routes return it: an Instance plus who attached -// the course to the sube. -export type ClassCourse = Instance & { +// The instance as the class routes return it: the resolved scalars plus who +// attached the course to the sube. The override flags and the three resolved +// sets live on GET /instances/{id} only. +export type ClassCourse = Pick< + Instance, + "id" | "class" | "course" | "title" | "description" | "ders_saati" | "counts_toward_karne" | "enrollment_count" | "teachers" +> & { attached_by: PersonRef; }; @@ -461,7 +540,7 @@ export type ClassCourse = Instance & { // grade label is the record's key, so there is at most one per grade. Creating // or editing one applies it to every existing class at that grade right away. export type ClassBlueprint = { - grade: string; + grade_level: number; courses: string[]; creator: PersonRef; }; @@ -493,13 +572,62 @@ export type BlueprintSectionStatus = { /** Every section at a grade with the template courses it is missing. */ export type BlueprintStatus = { - grade: string; + grade_level: number; /** The template every section below is measured against. */ courses: string[]; matched: number; sections: BlueprintSectionStatus[]; }; +// A school-wide non-teaching day range. The materializer skips every day it +// reaches into; lessons already on those days stay. +export type Holiday = { + id: string; + name: string; + /** First blocked instant, UTC unix-millis. */ + starts_at: number; + /** Last blocked instant, UTC unix-millis. */ + ends_at: number; + /** One of limits.holiday.kinds. */ + kind: string; + creator: PersonRef; + created_at: number; +}; + +// A grade-level template of a catalog course: what every section at that +// grade inherits. Null fields inherit themselves (the catalog title/ +// description, 1 weekly hour, counted toward the karne). +export type Offering = { + id: string; + course: string; + grade_level: number; + title: string | null; + description: string | null; + default_ders_saati: number | null; + default_counts_toward_karne: boolean | null; + created_by: PersonRef; + created_at: number; + updated_at: number; +}; + +/** One day the materializer left out because a holiday covers it. */ +export type BlockedDay = { date: string; holiday: string }; + +// What POST /instances/{id}/weekly-plan/materialize answers. `created` is +// empty on a dry run; `candidates` is what an apply would try to write. +export type MaterializeReport = { + from: number; + to: number; + applied: boolean; + slots: number; + candidates: number; + created: CourseSession[]; + skipped_existing: number; + skipped_holiday: number; + blocked: BlockedDay[]; + range_days: number; +}; + export type CourseSession = { id: string; /** The instance this lesson belongs to. */ @@ -891,12 +1019,25 @@ export type Limits = { max_session_topic_len: number; max_term_name_len: number; max_class_name_len: number; - max_class_grade_len: number; + // The grade ladder: 0 (anaokulu) .. 12. + min_grade_level: number; + max_grade_level: number; max_class_members: number; max_class_courses: number; max_academic_year_name_len: number; min_ders_saati: number; max_ders_saati: number; + // How many sections a catalog course row embeds in `sections`. + max_course_sections: number; + }; + holiday: { max_name_len: number; kinds: string[] }; + weekly_plan: { + // Inclusive bounds for a slot's minutes past midnight. + min_slot_minute: number; + max_slot_minute: number; + max_weekly_slots: number; + max_materialize_days: number; + max_materialize_sessions: number; }; exam: { max_title_len: number; diff --git a/src/api/reports/getMyCourses.ts b/src/api/reports/getMyCourses.ts index 1ef1c1b..043e728 100644 --- a/src/api/reports/getMyCourses.ts +++ b/src/api/reports/getMyCourses.ts @@ -1,9 +1,11 @@ import { client } from "../client"; -import { normalizePage, type Page } from "../client"; -import type { Course } from "../client"; -import { courseListQuery, type CourseListParams } from "../courses/getCourses"; +import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { CourseSectionRef } from "../client"; -export async function getMyCourses(params?: CourseListParams, signal?: AbortSignal): Promise> { - const data = await client(`/courses/me${courseListQuery(params)}`, { signal }); - return normalizePage(data); +// One row per class section the caller reaches (şube roster, homeroom, taught, +// or a hand-placed enrollment) — `id` is the instance id, never the catalog +// course's; `course` names the catalog row. +export async function getMyCourses(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/courses/me${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/components/ai/note-studio-panel.tsx b/src/components/ai/note-studio-panel.tsx index 97975f9..24a2078 100644 --- a/src/components/ai/note-studio-panel.tsx +++ b/src/components/ai/note-studio-panel.tsx @@ -3,8 +3,7 @@ import { Link, useNavigate } from "@tanstack/solid-router"; import { createResource } from "@/lib/create-resource"; import { getCourseNotes } from "@/api/course-notes"; import { getCourses } from "@/api/courses"; -import { getMyCourses } from "@/api/reports"; -import { formatApiError, type CourseNote, type Role } from "@/api/client"; +import { formatApiError, type CourseNote } from "@/api/client"; import { PodcastPanel } from "@/components/notes/podcast-panel"; import { RagOutputsPanel } from "@/components/notes/rag-outputs-panel"; import { StudioOutputLibrary } from "@/components/ai/studio-output-library"; @@ -36,8 +35,9 @@ function readRailWidth(): number { type StudioNote = CourseNote & { courseTitle: string; courseCreatorId: string }; /** Every lesson note the account can produce from, with its course. */ -async function loadStudioNotes(role: Role): Promise { - const courses = role === "student" ? await getMyCourses({ limit: 100 }) : await getCourses({ limit: 100 }); +async function loadStudioNotes(): Promise { + // GET /courses is already scoped to what the caller teaches or takes. + const courses = await getCourses({ limit: 100 }); const rows = await Promise.all( courses.items.map(async (course) => { try { @@ -57,7 +57,7 @@ async function loadStudioNotes(role: Role): Promise { function useStudioNotes() { const auth = useAuth(); - return createResource(() => auth.user()?.role ?? null, loadStudioNotes); + return createResource(() => auth.user()?.role ?? null, () => loadStudioNotes()); } /** diff --git a/src/components/classes/blueprint-panel.tsx b/src/components/classes/blueprint-panel.tsx index dd1efd6..ba6dd32 100644 --- a/src/components/classes/blueprint-panel.tsx +++ b/src/components/classes/blueprint-panel.tsx @@ -7,6 +7,7 @@ import { import { ApiError, formatApiError, type BlueprintResult, type ClassBlueprint, type Course } from "@/api/client"; import { Alert } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; +import { GradeLevelSelect } from "@/components/classes/grade-level-select"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { SidePanel } from "@/components/ui/side-panel"; @@ -21,11 +22,12 @@ export function BlueprintPanel(props: { blueprint: ClassBlueprint | null; courses: Course[]; maxCourses: number; - maxGradeLen: number; + minGradeLevel?: number; + maxGradeLevel?: number; onSaved: (result: BlueprintResult) => void; }) { const t = useT(); - const [grade, setGrade] = createSignal(""); + const [gradeLevel, setGradeLevel] = createSignal(null); const [selected, setSelected] = createSignal([]); const [filter, setFilter] = createSignal(""); const [error, setError] = createSignal(""); @@ -40,7 +42,7 @@ export function BlueprintPanel(props: { createEffect(() => { if (!props.open) return; const bp = props.blueprint; - setGrade(bp?.grade ?? ""); + setGradeLevel(bp ? bp.grade_level : null); setSelected(bp?.courses ? [...bp.courses] : []); setFilter(""); setError(""); @@ -62,7 +64,7 @@ export function BlueprintPanel(props: { // A losing race has no version token to retry with, so re-read the blueprint, // reseed the checkboxes from the server's list, and let the user resubmit. - const reseedFromServer = async (g: string) => { + const reseedFromServer = async (g: number) => { try { const fresh = await getClassBlueprintByGrade(g); setSelected([...fresh.courses]); @@ -75,15 +77,15 @@ export function BlueprintPanel(props: { const submit = async (e: Event) => { e.preventDefault(); - const g = grade().trim(); - if (!g) return; + const g = gradeLevel(); + if (g === null) return; setError(""); setWarning(""); setPending(true); try { const result = editing() ? await patchClassBlueprintByGrade(g, { course_ids: selected() }) - : await postClassBlueprint({ grade: g, course_ids: selected() }); + : await postClassBlueprint({ grade_level: g, course_ids: selected() }); props.onSaved(result); } catch (err) { if (err instanceof ApiError && err.status === 409) { @@ -115,13 +117,13 @@ export function BlueprintPanel(props: {
- setGrade(e.currentTarget.value)} + onChange={setGradeLevel} />

{t("classBlueprints.gradeHint")}

@@ -170,7 +172,7 @@ export function BlueprintPanel(props: {
-
diff --git a/src/components/classes/blueprints-tab.tsx b/src/components/classes/blueprints-tab.tsx index 9b20a0e..89e6ead 100644 --- a/src/components/classes/blueprints-tab.tsx +++ b/src/components/classes/blueprints-tab.tsx @@ -15,6 +15,7 @@ import { IconClipboardCheck, IconEdit, IconPlus, IconTrash } from "@/components/ import { SidePanel } from "@/components/ui/side-panel"; import { TableRowActions } from "@/components/ui/table-row-actions"; import { createFlash } from "@/lib/flash"; +import { gradeLevelLabel } from "@/lib/grade-level"; import { personLabel } from "@/lib/person"; import { useT } from "@/stores/preferences-context"; @@ -47,7 +48,8 @@ export function BlueprintsTab(props: { const columns = createMemo[]>(() => [ { id: "grade", - accessorFn: (row) => row.grade, + accessorFn: (row) => gradeLevelLabel(row.grade_level, t), + sortingFn: (a, b) => a.original.grade_level - b.original.grade_level, header: t("classBlueprints.grade"), meta: { cellClass: "font-medium" }, }, @@ -97,7 +99,7 @@ export function BlueprintsTab(props: { { label: t("classBlueprints.status"), icon: , - onSelect: () => void checkStatus(cell.row.original.grade), + onSelect: () => void checkStatus(cell.row.original.grade_level), }, ]} /> @@ -113,10 +115,10 @@ export function BlueprintsTab(props: { setEditing(null); await refetch(); setSkipped(result.skipped); - // A grade label nobody carries is saved just the same, so it must not + // A grade no class sits on is saved just the same, so it must not // read as "applied" — that is the one outcome the admin needs to fix. if (result.matched === 0) { - setUnmatchedGrade(result.blueprint.grade); + setUnmatchedGrade(gradeLevelLabel(result.blueprint.grade_level, t)); return; } setUnmatchedGrade(null); @@ -128,7 +130,7 @@ export function BlueprintsTab(props: { if (!bp) return; setError(""); try { - await deleteClassBlueprintByGrade(bp.grade); + await deleteClassBlueprintByGrade(bp.grade_level); setDeleting(null); await refetch(); setFlash(t("classBlueprints.deleted")); @@ -136,10 +138,10 @@ export function BlueprintsTab(props: { setError(formatApiError(err)); } }; - const checkStatus = async (grade: string) => { + const checkStatus = async (gradeLevel: number) => { setError(""); try { - setStatus(await getClassBlueprintStatus(grade)); + setStatus(await getClassBlueprintStatus(gradeLevel)); } catch (err) { setError(formatApiError(err)); } @@ -221,7 +223,8 @@ export function BlueprintsTab(props: { blueprint={editing()} courses={courses.latest ?? []} maxCourses={limits.latest?.course.max_class_courses ?? 50} - maxGradeLen={limits.latest?.course.max_class_grade_len ?? 20} + minGradeLevel={limits.latest?.course.min_grade_level} + maxGradeLevel={limits.latest?.course.max_grade_level} onSaved={(result) => void handleSaved(result)} /> @@ -235,7 +238,7 @@ export function BlueprintsTab(props: { !open && setStatus(null)} - title={t("classBlueprints.statusTitle", { grade: status()?.grade ?? "" })} + title={t("classBlueprints.statusTitle", { grade: status() ? gradeLevelLabel(status()!.grade_level, t) : "" })} size="wide" > @@ -256,7 +259,7 @@ export function BlueprintsTab(props: { open={deleting() !== null} onOpenChange={(open) => !open && setDeleting(null)} title={t("classBlueprints.delete")} - summary={t("classBlueprints.deleteConfirm", { grade: deleting()?.grade ?? "" })} + summary={t("classBlueprints.deleteConfirm", { grade: deleting() ? gradeLevelLabel(deleting()!.grade_level, t) : "" })} variant="destructive" onConfirm={remove} /> diff --git a/src/components/classes/class-edit-panel.tsx b/src/components/classes/class-edit-panel.tsx index 639744c..b41353a 100644 --- a/src/components/classes/class-edit-panel.tsx +++ b/src/components/classes/class-edit-panel.tsx @@ -3,6 +3,7 @@ import { patchClassById } from "@/api/classes"; import { formatApiError, type AcademicYear, type ClassGroup } from "@/api/client"; import { Alert } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; +import { GradeLevelSelect } from "@/components/classes/grade-level-select"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Select } from "@/components/ui/select"; @@ -23,11 +24,12 @@ export function ClassEditPanel(props: { onSaved: (cls: ClassGroup) => void | Promise; years: AcademicYear[]; maxNameLen?: number; - maxGradeLen?: number; + minGradeLevel?: number; + maxGradeLevel?: number; }) { const t = useT(); const [name, setName] = createSignal(""); - const [grade, setGrade] = createSignal(""); + const [gradeLevel, setGradeLevel] = createSignal(null); const [yearId, setYearId] = createSignal(""); const [teacherId, setTeacherId] = createSignal(""); const [error, setError] = createSignal(""); @@ -38,7 +40,7 @@ export function ClassEditPanel(props: { const c = props.cls; if (!props.open || !c) return; setName(c.name); - setGrade(c.grade ?? ""); + setGradeLevel(c.grade_level); setYearId(c.year ?? ""); setTeacherId(c.teacher?.id ?? ""); setError(""); @@ -51,7 +53,7 @@ export function ClassEditPanel(props: { setError(""); setPending(true); try { - const saved = await patchClassById(c.id, { name: name().trim(), grade: grade().trim() || null, year: yearId() || null, teacher_id: teacherId() || null }); + const saved = await patchClassById(c.id, { name: name().trim(), ...(gradeLevel() !== null ? { grade_level: gradeLevel()! } : {}), year: yearId() || null, teacher_id: teacherId() || null }); props.onOpenChange(false); await props.onSaved(saved); } catch (err) { @@ -66,7 +68,7 @@ export function ClassEditPanel(props: {
setName(e.currentTarget.value)} />
-
setGrade(e.currentTarget.value)} />
+
diff --git a/src/components/classes/grade-level-select.tsx b/src/components/classes/grade-level-select.tsx new file mode 100644 index 0000000..52e95ef --- /dev/null +++ b/src/components/classes/grade-level-select.tsx @@ -0,0 +1,35 @@ +import { For } from "solid-js"; +import { Select } from "@/components/ui/select"; +import { gradeLevelLabel, gradeLevels } from "@/lib/grade-level"; +import { useT } from "@/stores/preferences-context"; + +/** + * A pick on the grade ladder (0 = anaokulu .. 12). `value` null shows the + * placeholder row — the ladder is required on a class, so a form checks it. + */ +export function GradeLevelSelect(props: { + id: string; + value: number | null; + onChange: (level: number | null) => void; + min?: number; + max?: number; + disabled?: boolean; + error?: boolean; +}) { + const t = useT(); + return ( + + ); +} diff --git a/src/components/users/profile-memberships.tsx b/src/components/users/profile-memberships.tsx index 5d15fa3..9075a1c 100644 --- a/src/components/users/profile-memberships.tsx +++ b/src/components/users/profile-memberships.tsx @@ -8,6 +8,7 @@ import { TablePagination } from "@/components/ui/table-pagination"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { cn } from "@/lib/cn"; import { personLabel } from "@/lib/person"; +import { gradeLevelLabel } from "@/lib/grade-level"; import { useT } from "@/stores/preferences-context"; const PAGE_SIZE = 5; @@ -78,13 +79,9 @@ export function ProfileMemberships(props: { : t("classGroups.noTeacher")} - - {(g) => ( - - {g()} - - )} - + + {gradeLevelLabel(c.grade_level, t)} + )} @@ -112,7 +109,7 @@ export function ProfileMemberships(props: {
  • - {c.title} + + {c.title} + + {(name) => {name()}} + + {courseKindLabel(c.kind, t)}
  • diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 95ab650..95ec7f0 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -116,13 +116,13 @@ export const en: Dict = { "classBlueprints.filterCourses": "Filter courses", "classBlueprints.noCourseMatch": "No course matches that filter.", "classBlueprints.savedMatched": "Blueprint saved and applied to {count} class(es) at this grade.", - "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.", + "classBlueprints.noMatch": "Blueprint saved, but no class is at {grade}, so nothing was attached.", "classBlueprints.delete": "Delete blueprint", "classBlueprints.deleteConfirm": - "Delete the blueprint for grade {grade}? The courses it attached are detached from every class at this grade. Hand-attached courses stay.", + "Delete the {grade} blueprint? The courses it attached are detached from every class at this grade. Hand-attached courses stay.", "classBlueprints.deleted": "Blueprint deleted.", "classBlueprints.status": "Check sync", - "classBlueprints.statusTitle": "Sync status for grade {grade}", + "classBlueprints.statusTitle": "Sync status for {grade}", "classBlueprints.statusEmpty": "Every section at this grade carries the full template.", "classBlueprints.statusSection": "Section", "classBlueprints.statusMissing": "Missing courses", @@ -130,7 +130,7 @@ export const en: Dict = { "classBlueprints.applyHint": "Attaches this grade's blueprint courses to this class.", "classBlueprints.applyNoGrade": "Assign a grade to this class first.", "classBlueprints.applied": "Blueprint applied.", - "classBlueprints.noBlueprintForGrade": "There is no blueprint for grade {grade} yet.", + "classBlueprints.noBlueprintForGrade": "There is no blueprint for {grade} yet.", "classBlueprints.conflictExists": "A blueprint already exists for this grade. Edit it from the list instead.", "classBlueprints.staleReload": "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 = { "errors.audienceOnlyDescription": "This view is shown only to the student or parent signed in to their own account; staff accounts do not open it.", "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.", "errors.openStaffView": "Open the management view", + "grade.kindergarten": "Kindergarten", + "grade.level": "Grade {level}", + "grade.select": "Select a grade", + "instances.teachers": "Teachers", + "instances.sectionsTruncated": "Showing {shown} of {total} sections; the full list is on the Classes page.", }; diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts index c3f911b..9a8e647 100644 --- a/src/i18n/locales/tr.ts +++ b/src/i18n/locales/tr.ts @@ -112,13 +112,13 @@ export const tr: Dict = { "classBlueprints.filterCourses": "Derslerde ara", "classBlueprints.noCourseMatch": "Bu aramayla eşleşen ders yok.", "classBlueprints.savedMatched": "Şablon kaydedildi ve bu seviyedeki {count} şubeye uygulandı.", - "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.", + "classBlueprints.noMatch": "Şablon kaydedildi ama {grade} seviyesinde hiç şube yok, bu yüzden hiçbir şubeye ders eklenmedi.", "classBlueprints.delete": "Şablonu sil", "classBlueprints.deleteConfirm": - "{grade} seviyesinin şablonu silinsin mi? Şablonun eklediği dersler bu seviyedeki her şubeden çıkarılır. Elle eklenen dersler kalır.", + "{grade} şablonu silinsin mi? Şablonun eklediği dersler bu seviyedeki her şubeden çıkarılır. Elle eklenen dersler kalır.", "classBlueprints.deleted": "Şablon silindi.", "classBlueprints.status": "Eşitleme kontrolü", - "classBlueprints.statusTitle": "{grade} seviyesi eşitleme durumu", + "classBlueprints.statusTitle": "{grade} eşitleme durumu", "classBlueprints.statusEmpty": "Bu seviyedeki her şube şablonun tamamını taşıyor.", "classBlueprints.statusSection": "Şube", "classBlueprints.statusMissing": "Eksik dersler", @@ -126,7 +126,7 @@ export const tr: Dict = { "classBlueprints.applyHint": "Bu seviyenin şablon derslerini bu şubeye ekler.", "classBlueprints.applyNoGrade": "Önce bu şubeye bir seviye ata.", "classBlueprints.applied": "Şablon uygulandı.", - "classBlueprints.noBlueprintForGrade": "{grade} seviyesi için henüz bir şablon yok.", + "classBlueprints.noBlueprintForGrade": "{grade} için henüz bir şablon yok.", "classBlueprints.conflictExists": "Bu seviye için zaten bir şablon var. Bunun yerine listeden düzenle.", "classBlueprints.staleReload": "Sen düzenlerken bu şablon değişti. Liste yenilendi — gözden geçirip tekrar kaydet.", @@ -2452,4 +2452,9 @@ export const tr: Dict = { "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.", "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.", "errors.openStaffView": "Yönetim görünümünü aç", + "grade.kindergarten": "Anaokulu", + "grade.level": "{level}. sınıf", + "grade.select": "Seviye seçin", + "instances.teachers": "Öğretmenler", + "instances.sectionsTruncated": "{total} şubeden ilk {shown} tanesi gösteriliyor; tamamı Sınıflar sayfasında.", }; diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index 1283585..b770365 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -2435,7 +2435,12 @@ export type MessageKey = | "errors.parentOnlyTitle" | "errors.audienceOnlyDescription" | "errors.audienceOnlyWithAlternative" - | "errors.openStaffView"; + | "errors.openStaffView" + | "grade.kindergarten" + | "grade.level" + | "grade.select" + | "instances.teachers" + | "instances.sectionsTruncated"; export type Dict = Record; diff --git a/src/lib/command-search.test.ts b/src/lib/command-search.test.ts index 4fec0de..b4a23f3 100644 --- a/src/lib/command-search.test.ts +++ b/src/lib/command-search.test.ts @@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; const api = vi.hoisted(() => ({ getCourses: vi.fn(), - getMyCourses: vi.fn(), getExams: vi.fn(), getHomework: vi.fn(), getEvents: vi.fn(), @@ -11,7 +10,6 @@ const api = vi.hoisted(() => ({ })); vi.mock("@/api/courses", () => ({ getCourses: api.getCourses })); -vi.mock("@/api/reports", () => ({ getMyCourses: api.getMyCourses })); vi.mock("@/api/exams", () => ({ getExams: api.getExams })); vi.mock("@/api/homework", () => ({ getHomework: api.getHomework })); vi.mock("@/api/events", () => ({ getEvents: api.getEvents })); @@ -66,7 +64,6 @@ describe("loadCommandRecords", () => { beforeEach(() => { resetCommandRecordCache(); api.getCourses.mockResolvedValue(page([{ id: "c1", title: "Biyoloji", description: "", kind: "course" }])); - api.getMyCourses.mockResolvedValue(page([{ id: "c9", title: "Fizik", description: "", kind: "course" }])); api.getExams.mockResolvedValue( page([ { id: "e1", title: "Yazılı", description: "", class_course: "i1", starts_at: 5 }, @@ -81,10 +78,10 @@ describe("loadCommandRecords", () => { afterEach(() => vi.clearAllMocks()); test("a student reads their own courses and only exams in their own sections", async () => { + // GET /courses is already scoped to the student's own courses. const out = await loadCommandRecords("student", ["course", "exam"]); - expect(api.getMyCourses).toHaveBeenCalled(); - expect(api.getCourses).not.toHaveBeenCalled(); - expect(out.map((r) => r.id)).toEqual(["c9", "e1"]); + expect(api.getCourses).toHaveBeenCalled(); + expect(out.map((r) => r.id)).toEqual(["c1", "e1"]); expect(out[1].context).toBe("Biyoloji — 10-B"); }); diff --git a/src/lib/command-search.ts b/src/lib/command-search.ts index f1892aa..dc10b81 100644 --- a/src/lib/command-search.ts +++ b/src/lib/command-search.ts @@ -3,7 +3,6 @@ import { getExams } from "@/api/exams"; import { getEvents } from "@/api/events"; import { getHomework } from "@/api/homework"; import { getMyInstances } from "@/api/instances"; -import { getMyCourses } from "@/api/reports"; import type { Role } from "@/api/client"; import { LIST_CAP, loadCappedList } from "@/lib/capped-list"; import { loadInstanceLabels } from "@/lib/instance-labels"; @@ -71,9 +70,9 @@ export function filterCommandRecords( return out; } -async function loadCourses(role: Role): Promise { - // As on /courses: a student's list is their own enrolments. - const page = role === "student" ? await getMyCourses() : await getCourses(); +async function loadCourses(): Promise { + // GET /courses is already scoped: a student's list is their own enrolments. + const page = await getCourses(); return page.items.map((course) => ({ kind: "course", id: course.id, diff --git a/src/lib/grade-level.ts b/src/lib/grade-level.ts new file mode 100644 index 0000000..bbb6f9d --- /dev/null +++ b/src/lib/grade-level.ts @@ -0,0 +1,27 @@ +import type { MessageKey } from "@/i18n/messages"; + +type Translate = (key: MessageKey, params?: Record) => string; + +/** The grade ladder the backend accepts: 0 (anaokulu) through 12. */ +export const MIN_GRADE_LEVEL = 0; +export const MAX_GRADE_LEVEL = 12; + +/** "Anaokulu" at the floor, "9. sınıf" elsewhere. */ +export function gradeLevelLabel(level: number, t: Translate): string { + return level === 0 ? t("grade.kindergarten") : t("grade.level", { level: String(level) }); +} + +/** Every rung between the published bounds, lowest first. */ +export function gradeLevels(min = MIN_GRADE_LEVEL, max = MAX_GRADE_LEVEL): number[] { + const levels: number[] = []; + for (let level = min; level <= max; level++) levels.push(level); + return levels; +} + +/** + * The backend's own text for a rung ("Anaokulu", "1".."12") — what a RAG + * scope pair names as `sinif`. Not a display string; use gradeLevelLabel. + */ +export function gradeLevelWireLabel(level: number): string { + return level === 0 ? "Anaokulu" : String(level); +} diff --git a/src/lib/question-generation.ts b/src/lib/question-generation.ts index 7806e8a..4ddfef2 100644 --- a/src/lib/question-generation.ts +++ b/src/lib/question-generation.ts @@ -2,6 +2,7 @@ import { getClasses } from "@/api/classes"; import type { ClassGroup, Course } from "@/api/client"; import { getCourseById } from "@/api/courses"; import { getMyInstances } from "@/api/instances"; +import { gradeLevelWireLabel } from "@/lib/grade-level"; import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; /** Pages one request may name; a wider range is almost always a typo. */ @@ -54,7 +55,7 @@ export async function loadStudyScopes(): Promise { getMyInstances({ limit: 200 }), getClasses({ limit: 200 }).catch(() => ({ items: [] as ClassGroup[] })), ]); - const gradeOf = new Map(classes.items.map((klass) => [klass.id, klass.grade])); + const gradeOf = new Map(classes.items.map((klass) => [klass.id, gradeLevelWireLabel(klass.grade_level)])); const courseIds = [...new Set(instances.items.map((instance) => instance.course))]; const courses = await mapConcurrent(courseIds, FAN_OUT_LIMIT, (id) => getCourseById(id).catch(() => null)); 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 { for (const instance of instances.items) { const course = courseById.get(instance.course); if (!course) continue; - const sinif = course.kind === "course" ? gradeOf.get(instance.class)?.trim() || null : null; - const key = `${course.title}\u0000${sinif ?? ""}`; + const sinif = course.kind === "course" ? gradeOf.get(instance.class) ?? null : null; + // The backend names a section's pair by its resolved title, not the catalog's. + const ders = instance.title || course.title; + const key = `${ders}\u0000${sinif ?? ""}`; if (!options.has(key)) { - options.set(key, { key, ders: course.title, sinif, course, label: sinif ? `${course.title} · ${sinif}` : course.title }); + options.set(key, { key, ders, sinif, course, label: sinif ? `${ders} · ${sinif}` : ders }); } } return [...options.values()].sort((a, b) => a.label.localeCompare(b.label, "tr")); diff --git a/src/lib/student-directory.ts b/src/lib/student-directory.ts index 1a9e9e1..136a9b3 100644 --- a/src/lib/student-directory.ts +++ b/src/lib/student-directory.ts @@ -29,9 +29,7 @@ const collator = new Intl.Collator("tr", { numeric: true, sensitivity: "base" }) /** Class order a school reads rosters in: grade (9 before 10), then the şube name. */ export function compareClasses(a: ClassGroup, b: ClassGroup): number { - const gradeA = Number.parseInt(a.grade ?? a.name, 10); - const gradeB = Number.parseInt(b.grade ?? b.name, 10); - if (Number.isFinite(gradeA) && Number.isFinite(gradeB) && gradeA !== gradeB) return gradeA - gradeB; + if (a.grade_level !== b.grade_level) return a.grade_level - b.grade_level; return collator.compare(a.name, b.name); } diff --git a/src/pages/academic-years-page.tsx b/src/pages/academic-years-page.tsx index bdf5fe3..80cbd2a 100644 --- a/src/pages/academic-years-page.tsx +++ b/src/pages/academic-years-page.tsx @@ -30,6 +30,7 @@ import { TableRowActions } from "@/components/ui/table-row-actions"; import { createFlash } from "@/lib/flash"; import { formatDate } from "@/lib/format"; import { usePreferences, useT } from "@/stores/preferences-context"; +import { GradeLevelSelect } from "@/components/classes/grade-level-select"; const YEAR_PAGE_SIZE = 10; @@ -70,7 +71,8 @@ function AcademicYearsContent() { const [name, setName] = createSignal(""); const [starts, setStarts] = createSignal(""); const [ends, setEnds] = createSignal(""); - const [promotions, setPromotions] = createSignal([]); + // A row being written may still have a half unpicked. + const [promotions, setPromotions] = createSignal<{ from_grade: number | null; to_grade: number | null }[]>([]); const [editing, setEditing] = createSignal(null); const [deleteTarget, setDeleteTarget] = createSignal(null); const [detail, setDetail] = createSignal(null); @@ -120,9 +122,9 @@ function AcademicYearsContent() { } // A blank half is a half-written rule, not a policy — drop it rather than // sending a promotion the rollover cannot act on. - const grade_promotions = promotions() - .map((pair) => ({ from_grade: pair.from_grade.trim(), to_grade: pair.to_grade.trim() })) - .filter((pair) => pair.from_grade && pair.to_grade); + const grade_promotions = promotions().filter( + (pair): pair is GradePromotion => pair.from_grade !== null && pair.to_grade !== null, + ); setPending(true); try { @@ -346,7 +348,7 @@ function AcademicYearsContent() { size="sm" variant="outline" class="rounded-lg" - onClick={() => setPromotions((rows) => [...rows, { from_grade: "", to_grade: "" }])} + onClick={() => setPromotions((rows) => [...rows, { from_grade: null, to_grade: null }])} > {t("academicYears.addPromotion")} @@ -355,24 +357,18 @@ function AcademicYearsContent() { {(pair, index) => (
    - - setPromotions((rows) => rows.map((row, i) => (i === index() ? { ...row, from_grade: e.currentTarget.value } : row))) + onChange={(level) => + setPromotions((rows) => rows.map((row, i) => (i === index() ? { ...row, from_grade: level } : row))) } /> - - setPromotions((rows) => rows.map((row, i) => (i === index() ? { ...row, to_grade: e.currentTarget.value } : row))) + onChange={(level) => + setPromotions((rows) => rows.map((row, i) => (i === index() ? { ...row, to_grade: level } : row))) } />