diff --git a/AGENTS.md b/AGENTS.md index c7e6d80..6c03f5d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,6 +11,14 @@ Bilingual codebase: Turkish UI labels, English code + commits. - **SolidJS, not React.** Components run once. No re-render. Signals = functions. Load `solidjs-pitfalls` skill before writing components. +- **A ders is a catalog row; a şube×ders `instance` is where teaching happens.** + `/courses/{id}` is the catalog (title, kind, subjects, notes, club/etüt + members). Attaching it to a class (`postClassInstance`) mints the instance, + and that is what carries enrollments, exams, homework, sessions, roll call, + `ders_saati` and the karne flag — see `src/api/instances/` and + `/instances/$id`. Exam/homework/session rows name `class_course`, never + `course`; a class links an academic year (`/academic-years`), and a dönem + lives inside one. - **Podman, not Docker.** Never suggest docker. `podman build`, `podman compose`. - **Bun only, never npm/npx/yarn/pnpm.** Install/run/exec with `bun add`, `bun run`, `bunx` — this repo has no `package-lock.json`/`yarn.lock`/ diff --git a/CLAUDE.md b/CLAUDE.md index dbfdeb1..2f8cf7d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,6 +10,14 @@ Bilingual codebase: Turkish UI labels, English code + commits. - **SolidJS, not React.** Components run once. No re-render. Signals = functions. Load `solidjs-pitfalls` skill before writing components. +- **A ders is a catalog row; a şube×ders `instance` is where teaching happens.** + `/courses/{id}` is the catalog (title, kind, subjects, notes, club/etüt + members). Attaching it to a class (`postClassInstance`) mints the instance, + and that is what carries enrollments, exams, homework, sessions, roll call, + `ders_saati` and the karne flag — see `src/api/instances/` and + `/instances/$id`. Exam/homework/session rows name `class_course`, never + `course`; a class links an academic year (`/academic-years`), and a dönem + lives inside one. - **Podman, not Docker.** Never suggest docker. `podman build`, `podman compose`. - **Bun only, never npm/npx/yarn/pnpm.** Install/run/exec with `bun add`, `bun run`, `bunx` — this repo has no `package-lock.json`/`yarn.lock`/ diff --git a/src/api/__tests__/academic-years/academic-years.test.ts b/src/api/__tests__/academic-years/academic-years.test.ts new file mode 100644 index 0000000..d3eb9b9 --- /dev/null +++ b/src/api/__tests__/academic-years/academic-years.test.ts @@ -0,0 +1,98 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + deleteAcademicYearById, + getAcademicYearById, + getAcademicYears, + patchAcademicYearById, + postAcademicYear, + postAcademicYearArchive, + postAcademicYearRollover, +} from "../../academic-years"; +import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; + +describe("academic years API", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("getAcademicYears GETs /academic-years with pagination", async () => { + mockFetchSuccess({ items: [{ id: "y1" }], total: 1 }); + + const result = await getAcademicYears({ limit: 10 }); + expect(result.items).toEqual([{ id: "y1" }]); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/academic-years?limit=10"); + expect(init?.method).toBe("GET"); + }); + + it("getAcademicYearById GETs /academic-years/:id", async () => { + mockFetchSuccess({ id: "y1" }); + + await getAcademicYearById("y1"); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/academic-years/y1"); + }); + + it("postAcademicYear POSTs /academic-years with the body", async () => { + mockFetchSuccess({ id: "y1" }); + const body = { + name: "2026-2027", + starts_at: 1780000000000, + ends_at: 1810000000000, + grade_promotions: [{ from_grade: "5", to_grade: "6" }], + }; + + await postAcademicYear(body); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/academic-years"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("patchAcademicYearById PATCHes /academic-years/:id", async () => { + mockFetchSuccess({ id: "y1" }); + const body = { name: "2027-2028" }; + + await patchAcademicYearById("y1", body); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/academic-years/y1"); + expect(init?.method).toBe("PATCH"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("deleteAcademicYearById DELETEs /academic-years/:id", async () => { + mockFetch204(); + + await deleteAcademicYearById("y1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/academic-years/y1"); + expect(init?.method).toBe("DELETE"); + }); + + it("postAcademicYearArchive POSTs /academic-years/:id/archive", async () => { + mockFetchSuccess({ id: "y1", archived_at: 1 }); + + await postAcademicYearArchive("y1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/academic-years/y1/archive"); + expect(init?.method).toBe("POST"); + }); + + it("postAcademicYearRollover POSTs /academic-years/:id/rollover with from_year", async () => { + mockFetchSuccess({ year: "y2", classes: 12, students: 312, graduated: ["12"] }); + + const result = await postAcademicYearRollover("y2", "y1"); + expect(result.classes).toBe(12); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/academic-years/y2/rollover"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify({ from_year: "y1" })); + }); +}); diff --git a/src/api/__tests__/ai/ai.test.ts b/src/api/__tests__/ai/ai.test.ts index 9ef4a8b..fd84ee8 100644 --- a/src/api/__tests__/ai/ai.test.ts +++ b/src/api/__tests__/ai/ai.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { getBridgeCertificate } from "../../ai"; +import { getAiCapabilities, getBridgeCertificate } from "../../ai"; import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch"; describe("ai API", () => { afterEach(() => vi.restoreAllMocks()); @@ -8,4 +8,10 @@ describe("ai API", () => { await getBridgeCertificate(); expect(lastFetchCall()[0]).toBe("/api/ai/certificate"); }); + it("gets the bridge capabilities", async () => { + mockFetchSuccess({ enabled: true, protocol: "hab/2", capabilities: [] }); + const result = await getAiCapabilities(); + expect(result.protocol).toBe("hab/2"); + expect(lastFetchCall()[0]).toBe("/api/ai/capabilities"); + }); }); diff --git a/src/api/__tests__/classes/classes.test.ts b/src/api/__tests__/classes/classes.test.ts index af8b2f6..da5f2a8 100644 --- a/src/api/__tests__/classes/classes.test.ts +++ b/src/api/__tests__/classes/classes.test.ts @@ -10,9 +10,9 @@ import { postClassMember, getClassMembers, deleteClassMember, - postClassCourse, - getClassCourses, - deleteClassCourse, + postClassInstance, + getClassInstances, + deleteClassInstance, postClassBlueprint, getClassBlueprints, getClassBlueprintByGrade, @@ -111,28 +111,30 @@ describe("classes API", () => { expect(init?.method).toBe("DELETE"); }); - it("postClassCourse POSTs /classes/:id/courses with the body", async () => { + it("postClassInstance POSTs /classes/:id/instances with the body", async () => { mockFetchSuccess({ id: "cc1" }); const body = { course_id: "co1" }; - await postClassCourse("c1", body); + await postClassInstance("c1", body); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/classes/c1/courses"); + expect(url).toBe("/api/classes/c1/instances"); expect(init?.method).toBe("POST"); expect(init?.body).toBe(JSON.stringify(body)); }); - it("getClassCourses GETs /classes/:id/courses with pagination", async () => { + it("getClassInstances GETs /classes/:id/instances with pagination", async () => { mockFetchSuccess({ items: [], total: 0 }); - await getClassCourses("c1", { limit: 5, offset: 10 }); + await getClassInstances("c1", { limit: 5, offset: 10 }); const [url] = lastFetchCall(); - expect(url).toBe("/api/classes/c1/courses?limit=5&offset=10"); + expect(url).toBe("/api/classes/c1/instances?limit=5&offset=10"); }); - it("deleteClassCourse DELETEs /classes/:id/courses/:course", async () => { + // The second segment is the instance id, not the course id — two şubeler + // teaching the same course hold two instances. + it("deleteClassInstance DELETEs /classes/:id/instances/:instance", async () => { mockFetch204(); - await deleteClassCourse("c1", "co1"); + await deleteClassInstance("c1", "i1"); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/classes/c1/courses/co1"); + expect(url).toBe("/api/classes/c1/instances/i1"); expect(init?.method).toBe("DELETE"); }); diff --git a/src/api/__tests__/contract/bank-questions.contract.test.ts b/src/api/__tests__/contract/bank-questions.contract.test.ts index 1d0788c..7139455 100644 --- a/src/api/__tests__/contract/bank-questions.contract.test.ts +++ b/src/api/__tests__/contract/bank-questions.contract.test.ts @@ -4,15 +4,39 @@ import type { BankQuestion, Course, ExamQuestion, Subject } from "@/api/client"; if (!isLive) console.warn(SKIP_MESSAGE); describe.skipIf(!isLive)(`bank-questions contract @ ${contractBaseUrl}`, () => { + let yearId = ""; + let termId = ""; + let classId = ""; let courseId = ""; + let instanceId = ""; let subjectId = ""; let questionId = ""; + // Bank templates hang off a catalog subject, but the exam that copies one + // has to live in an instance — so the fixture builds the whole şube chain. beforeAll(async () => { await loginAdmin(); + const tag = `contract-${Date.now()}`; + + const year = await json<{ id: string }>("/academic-years", { + method: "POST", + body: { name: tag, starts_at: Date.now(), ends_at: Date.now() + 300 * 24 * 60 * 60 * 1000 }, + }); + yearId = year.id; + const term = await json<{ id: string }>("/terms", { + method: "POST", + body: { name: tag, year: yearId, starts_at: Date.now(), ends_at: Date.now() + 120 * 24 * 60 * 60 * 1000 }, + }); + termId = term.id; + const klass = await json<{ id: string }>("/classes", { + method: "POST", + body: { name: tag, grade: "9", year: yearId }, + }); + classId = klass.id; + const course = await json("/courses", { method: "POST", - body: { title: `contract-${Date.now()}` }, + body: { title: tag }, }); courseId = course.id; const subject = await json(`/courses/${courseId}/subjects`, { @@ -20,6 +44,12 @@ describe.skipIf(!isLive)(`bank-questions contract @ ${contractBaseUrl}`, () => { body: { name: "contract subject" }, }); subjectId = subject.id; + + const instance = await json<{ id: string }>(`/classes/${classId}/instances`, { + method: "POST", + body: { course_id: courseId }, + }); + instanceId = instance.id; }); /** Templates created by the paging/search tests, torn down with the course. */ @@ -28,7 +58,11 @@ describe.skipIf(!isLive)(`bank-questions contract @ ${contractBaseUrl}`, () => { afterAll(async () => { for (const id of scratchIds) await api(`/bank-questions/${id}`, { method: "DELETE" }); if (questionId) await api(`/bank-questions/${questionId}`, { method: "DELETE" }); + if (instanceId) await api(`/classes/${classId}/instances/${instanceId}`, { method: "DELETE" }); if (courseId) await api(`/courses/${courseId}`, { method: "DELETE" }); + if (classId) await api(`/classes/${classId}`, { method: "DELETE" }); + if (termId) await api(`/terms/${termId}`, { method: "DELETE" }); + if (yearId) await api(`/academic-years/${yearId}`, { method: "DELETE" }); }); const createTemplate = async (text: string) => { @@ -226,9 +260,9 @@ describe.skipIf(!isLive)(`bank-questions contract @ ${contractBaseUrl}`, () => { it("reports used_count on the list and refreshes a copy from its template", async () => { const tag = `use${Date.now()}`; const template = await createTemplate(`${tag} original text`); - const exam = await json<{ id: string }>(`/courses/${courseId}/exams`, { + const exam = await json<{ id: string }>(`/instances/${instanceId}/exams`, { method: "POST", - body: { title: tag, kind: await configuredExamKind() }, + body: { title: tag, kind: await configuredExamKind(), term: termId }, }); const copy = await json( diff --git a/src/api/__tests__/contract/learning.contract.test.ts b/src/api/__tests__/contract/learning.contract.test.ts index c462289..3fccb5d 100644 --- a/src/api/__tests__/contract/learning.contract.test.ts +++ b/src/api/__tests__/contract/learning.contract.test.ts @@ -3,32 +3,78 @@ import { api, configuredExamKind, contractBaseUrl, expectPage, isLive, json, log if (!isLive) console.warn(SKIP_MESSAGE); describe.skipIf(!isLive)(`learning contract @ ${contractBaseUrl}`, () => { + let yearId = ""; + let termId = ""; + let classId = ""; let courseId = ""; + let instanceId = ""; let examId = ""; + // A catalog course teaches nobody on its own: the chain an exam needs is + // academic year → dönem → şube → attach the course (which mints the + // instance) → exam inside that instance. beforeAll(async () => { await loginAdmin(); const tag = `contract-learning-${Date.now()}`; + + const year = await json<{ id: string }>("/academic-years", { + method: "POST", + body: { name: tag, starts_at: Date.now(), ends_at: Date.now() + 300 * 24 * 60 * 60 * 1000 }, + }); + yearId = year.id; + + const term = await json<{ id: string; year: string }>("/terms", { + method: "POST", + body: { name: tag, year: yearId, starts_at: Date.now(), ends_at: Date.now() + 120 * 24 * 60 * 60 * 1000 }, + }); + termId = term.id; + expect(term.year).toBe(yearId); + + const klass = await json<{ id: string }>("/classes", { + method: "POST", + body: { name: tag, grade: "9", year: yearId }, + }); + classId = klass.id; + const course = await json<{ id: string; title: string; kind: string }>("/courses", { method: "POST", body: { title: tag, kind: "course" }, }); courseId = course.id; expect(course).toMatchObject({ title: tag, kind: "course" }); + + const instance = await json<{ id: string; class: string; course: string }>(`/classes/${classId}/instances`, { + method: "POST", + body: { course_id: courseId }, + }); + instanceId = instance.id; + expect(instance).toMatchObject({ class: classId, course: courseId }); }); + // Teardown runs inside-out: an instance holds the exams, a şube holds the + // instance, and a year refuses deletion while a dönem or şube still links it. afterAll(async () => { + if (instanceId) await api(`/classes/${classId}/instances/${instanceId}`, { method: "DELETE" }); if (courseId) await api(`/courses/${courseId}`, { method: "DELETE" }); + if (classId) await api(`/classes/${classId}`, { method: "DELETE" }); + if (termId) await api(`/terms/${termId}`, { method: "DELETE" }); + if (yearId) await api(`/academic-years/${yearId}`, { method: "DELETE" }); }); - // `/courses` takes limit/offset only — kind/term/search filtering is the - // caller's job, so this asserts the envelope, not a server-side filter. + // `/courses` takes limit/offset only — kind/search filtering is the caller's + // job, so this asserts the envelope, not a server-side filter. it("returns courses through the standard page envelope", async () => { const page = await json<{ items: Array<{ id: string }> }>(`/courses?limit=10`); expectPage(page); expect(page.items.some((course) => course.id === courseId)).toBe(true); }); + it("lists the instances a class carries", async () => { + const page = await json<{ items: Array<{ id: string }> }>(`/classes/${classId}/instances?limit=10`); + expectPage(page); + expect(page.items.some((instance) => instance.id === instanceId)).toBe(true); + }); + it("supports course subjects and exam-question lists", async () => { const subject = await json<{ id: string; course: string }>(`/courses/${courseId}/subjects`, { method: "POST", @@ -37,12 +83,16 @@ describe.skipIf(!isLive)(`learning contract @ ${contractBaseUrl}`, () => { expect(subject.course).toBe(courseId); const examKind = await configuredExamKind(); - const exam = await json<{ id: string; course: string; draft: boolean }>(`/courses/${courseId}/exams`, { - method: "POST", - body: { title: "contract exam", kind: examKind, draft: true }, - }); + const exam = await json<{ id: string; class_course: string; term: string; draft: boolean }>( + `/instances/${instanceId}/exams`, + { + method: "POST", + body: { title: "contract exam", kind: examKind, term: termId, draft: true }, + }, + ); examId = exam.id; - expect(exam.course).toBe(courseId); + expect(exam.class_course).toBe(instanceId); + expect(exam.term).toBe(termId); const question = await json<{ id: string; exam: string }>(`/exams/${examId}/questions`, { method: "POST", @@ -50,6 +100,6 @@ describe.skipIf(!isLive)(`learning contract @ ${contractBaseUrl}`, () => { }); expect(question.exam).toBe(examId); expectPage(await json(`/exams/${examId}/questions?limit=10`)); - expectPage(await json(`/courses/${courseId}/exams?limit=10`)); + expectPage(await json(`/instances/${instanceId}/exams?limit=10`)); }); }); diff --git a/src/api/__tests__/course-notes/course-notes.test.ts b/src/api/__tests__/course-notes/course-notes.test.ts index 40ce633..ea0141d 100644 --- a/src/api/__tests__/course-notes/course-notes.test.ts +++ b/src/api/__tests__/course-notes/course-notes.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { getCourseNotes } from "../../course-notes"; +import { postCourseNoteRagReindex } from "../../course-notes"; import { getCourseNoteById } from "../../course-notes"; import { postCourseNote } from "../../course-notes"; import { patchCourseNoteById } from "../../course-notes"; @@ -164,4 +165,14 @@ describe("course notes API", () => { expect(url).toBe("/api/course-notes/cn1/rag/r1"); expect(init?.method).toBe("DELETE"); }); + it("postCourseNoteRagReindex POSTs /course-notes/:id/rag/reindex", async () => { + mockFetch204(); + + await postCourseNoteRagReindex("n1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/course-notes/n1/rag/reindex"); + expect(init?.method).toBe("POST"); + }); + }); diff --git a/src/api/__tests__/courses/courses.test.ts b/src/api/__tests__/courses/courses.test.ts index 66433f8..ef0df3d 100644 --- a/src/api/__tests__/courses/courses.test.ts +++ b/src/api/__tests__/courses/courses.test.ts @@ -4,19 +4,11 @@ import { getCourseById } from "../../courses"; import { postCourse } from "../../courses"; import { patchCourseById } from "../../courses"; import { deleteCourseById } from "../../courses"; -import { getCourseEnrollments } from "../../courses"; -import { postCourseEnrollment } from "../../courses"; -import { deleteCourseEnrollmentByUserId } from "../../courses"; -import { getCourseSessions } from "../../courses"; -import { postCourseSession } from "../../courses"; +import { getCourseMembers } from "../../courses"; +import { postCourseMember } from "../../courses"; +import { deleteCourseMemberByUserId } from "../../courses"; import { getCourseSubjects } from "../../courses"; import { postCourseSubject } from "../../courses"; -import { getCourseExams } from "../../courses"; -import { postCourseExam } from "../../courses"; -import { postCourseTeacher } from "../../courses"; -import { deleteCourseTeacherByUserId } from "../../courses"; -import { getCourseHomework } from "../../courses"; -import { postCourseHomework } from "../../courses"; import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; describe("courses API", () => { @@ -24,30 +16,6 @@ describe("courses API", () => { vi.restoreAllMocks(); }); - it("postCourseTeacher calls /courses/:id/teachers", async () => { - const mockCourse = { id: "c1", title: "Course", teachers: [{ id: "t1", username: "teacher1", display_name: "Teacher 1" }] }; - mockFetchSuccess(mockCourse); - - const result = await postCourseTeacher("c1", "t1"); - expect(result).toEqual(mockCourse); - - const [url, init] = lastFetchCall(); - expect(url).toBe("/api/courses/c1/teachers"); - expect(init?.method).toBe("POST"); - expect(init?.body).toBe(JSON.stringify({ user_id: "t1" })); - }); - - it("deleteCourseTeacherByUserId calls /courses/:id/teachers/:userId", async () => { - mockFetch204(); - - await deleteCourseTeacherByUserId("c1", "t1"); - - const [url, init] = lastFetchCall(); - expect(url).toBe("/api/courses/c1/teachers/t1"); - expect(init?.method).toBe("DELETE"); - }); - - it("getCourses calls /courses with pagination", async () => { const mockPage = { items: [{ id: "c1" }], total: 1 }; mockFetchSuccess(mockPage); @@ -116,67 +84,6 @@ describe("courses API", () => { expect(init?.method).toBe("DELETE"); }); - it("getCourseEnrollments calls /courses/:id/enrollments", async () => { - const mockPage = { items: [{ id: "en1" }], total: 1 }; - mockFetchSuccess(mockPage); - - const result = await getCourseEnrollments("c1"); - expect(result).toEqual({ ...mockPage, limit: null, offset: 0 }); - - const [url, init] = lastFetchCall(); - expect(url).toBe("/api/courses/c1/enrollments"); - expect(init?.method).toBe("GET"); - }); - - it("postCourseEnrollment calls /courses/:id/enrollments", async () => { - const mockEnr = { id: "en1", course: "c1" }; - mockFetchSuccess(mockEnr); - - const result = await postCourseEnrollment("c1", "u1"); - expect(result).toEqual(mockEnr); - - const [url, init] = lastFetchCall(); - expect(url).toBe("/api/courses/c1/enrollments"); - expect(init?.method).toBe("POST"); - expect(init?.body).toBe(JSON.stringify({ user_id: "u1" })); - }); - - it("deleteCourseEnrollmentByUserId calls /courses/:id/enrollments/:userId", async () => { - mockFetch204(); - - await deleteCourseEnrollmentByUserId("c1", "u1"); - - const [url, init] = lastFetchCall(); - expect(url).toBe("/api/courses/c1/enrollments/u1"); - expect(init?.method).toBe("DELETE"); - }); - - it("getCourseSessions calls /courses/:id/sessions", async () => { - const mockPage = { items: [{ id: "s1" }], total: 1 }; - mockFetchSuccess(mockPage); - - const result = await getCourseSessions("c1"); - expect(result).toEqual({ ...mockPage, limit: null, offset: 0 }); - - const [url, init] = lastFetchCall(); - expect(url).toBe("/api/courses/c1/sessions"); - expect(init?.method).toBe("GET"); - }); - - it("postCourseSession calls /courses/:id/sessions", async () => { - const mockSession = { id: "s1", course: "c1" }; - mockFetchSuccess(mockSession); - - const data = { topic: "Topic", starts_at: 1000 }; - const result = await postCourseSession("c1", data); - expect(result).toEqual(mockSession); - - const [url, init] = lastFetchCall(); - expect(url).toBe("/api/courses/c1/sessions"); - expect(init?.method).toBe("POST"); - expect(init?.body).toBe(JSON.stringify(data)); - }); - it("getCourseSubjects calls /courses/:id/subjects", async () => { const mockPage = { items: [{ id: "sub1" }], total: 1 }; mockFetchSuccess(mockPage); @@ -203,55 +110,36 @@ describe("courses API", () => { expect(init?.body).toBe(JSON.stringify(data)); }); - it("getCourseExams calls /courses/:id/exams", async () => { - const mockPage = { items: [{ id: "ex1" }], total: 1 }; - mockFetchSuccess(mockPage); + it("getCourseMembers calls /courses/:id/members with pagination", async () => { + mockFetchSuccess({ items: [{ id: "m1" }], total: 1 }); - const result = await getCourseExams("c1"); - expect(result).toEqual({ ...mockPage, limit: null, offset: 0 }); + const result = await getCourseMembers("c1", { limit: 10 }); + expect(result.items).toEqual([{ id: "m1" }]); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/courses/c1/exams"); + expect(url).toBe("/api/courses/c1/members?limit=10"); expect(init?.method).toBe("GET"); }); - it("postCourseExam calls /courses/:id/exams", async () => { - const mockExam = { id: "ex1", course: "c1" }; - mockFetchSuccess(mockExam); + it("postCourseMember calls /courses/:id/members with the user id", async () => { + mockFetchSuccess({ id: "m1" }); - const data = { title: "Exam", kind: "quiz" }; - const result = await postCourseExam("c1", data); - expect(result).toEqual(mockExam); + await postCourseMember("c1", "u1"); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/courses/c1/exams"); + expect(url).toBe("/api/courses/c1/members"); expect(init?.method).toBe("POST"); - expect(init?.body).toBe(JSON.stringify(data)); + expect(init?.body).toBe(JSON.stringify({ user_id: "u1" })); }); - it("getCourseHomework calls /courses/:id/homework", async () => { - const mockPage = { items: [{ id: "hw1" }], total: 1 }; - mockFetchSuccess(mockPage); + it("deleteCourseMemberByUserId calls /courses/:id/members/:userId", async () => { + mockFetch204(); - const result = await getCourseHomework("c1", { limit: 5 }); - expect(result).toEqual({ ...mockPage, limit: null, offset: 0 }); + await deleteCourseMemberByUserId("c1", "u1"); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/courses/c1/homework?limit=5"); - expect(init?.method).toBe("GET"); + expect(url).toBe("/api/courses/c1/members/u1"); + expect(init?.method).toBe("DELETE"); }); - it("postCourseHomework calls /courses/:id/homework", async () => { - const mockHomework = { id: "hw1", course: "c1" }; - mockFetchSuccess(mockHomework); - - const data = { title: "HW", subject_id: "sub1", due_at: 1900000000000, assigned: ["u1"] }; - const result = await postCourseHomework("c1", data); - expect(result).toEqual(mockHomework); - - const [url, init] = lastFetchCall(); - expect(url).toBe("/api/courses/c1/homework"); - expect(init?.method).toBe("POST"); - expect(init?.body).toBe(JSON.stringify(data)); - }); }); diff --git a/src/api/__tests__/exams/exams.test.ts b/src/api/__tests__/exams/exams.test.ts index 091e7ad..9a88f80 100644 --- a/src/api/__tests__/exams/exams.test.ts +++ b/src/api/__tests__/exams/exams.test.ts @@ -8,6 +8,9 @@ import { getExamChoiceImageBlob } from "../../exams"; import { postExamAttemptAnswerImage } from "../../exams"; import { deleteExamAttemptAnswerImage } from "../../exams"; import { getExamAnswerImageBlob } from "../../exams"; +import { getExamAudience } from "../../exams"; +import { postExamAudience } from "../../exams"; +import { deleteExamAudienceByInstanceId } from "../../exams"; import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch"; describe("exams API - core", () => { @@ -143,4 +146,34 @@ describe("exams API - core", () => { expect(init?.method ?? "GET").toBe("GET"); expect(init?.credentials).toBe("same-origin"); }); + it("getExamAudience calls /exams/:id/audience", async () => { + mockFetchSuccess({ items: [], total: 0 }); + + await getExamAudience("x1", { limit: 10 }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/exams/x1/audience?limit=10"); + }); + + it("postExamAudience announces the exam to another instance", async () => { + mockFetchSuccess({ instance: "i2", class: "c2", course: "co1" }); + + await postExamAudience("x1", "i2"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/exams/x1/audience"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify({ instance: "i2" })); + }); + + it("deleteExamAudienceByInstanceId calls /exams/:id/audience/:instance", async () => { + mockFetch204(); + + await deleteExamAudienceByInstanceId("x1", "i2"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/exams/x1/audience/i2"); + expect(init?.method).toBe("DELETE"); + }); + }); diff --git a/src/api/__tests__/instances/instances.test.ts b/src/api/__tests__/instances/instances.test.ts new file mode 100644 index 0000000..9544259 --- /dev/null +++ b/src/api/__tests__/instances/instances.test.ts @@ -0,0 +1,171 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + deleteInstanceEnrollmentByUserId, + deleteInstanceTeacherByUserId, + getInstanceById, + getInstanceEnrollments, + getInstanceExams, + getInstanceHomework, + getInstanceSessions, + getMyInstances, + patchInstanceById, + postInstanceEnrollment, + postInstanceExam, + postInstanceHomework, + postInstanceSession, + postInstanceTeacher, +} from "../../instances"; +import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; + +describe("instances API", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("getMyInstances GETs /instances/me with pagination", async () => { + mockFetchSuccess({ items: [{ id: "i1" }], total: 1 }); + + const result = await getMyInstances({ limit: 20, offset: 40 }); + expect(result.items).toEqual([{ id: "i1" }]); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/instances/me?limit=20&offset=40"); + expect(init?.method).toBe("GET"); + }); + + it("getInstanceById GETs /instances/:id", async () => { + mockFetchSuccess({ id: "i1" }); + + await getInstanceById("i1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/instances/i1"); + expect(init?.method).toBe("GET"); + }); + + it("patchInstanceById PATCHes /instances/:id with the policy body", async () => { + mockFetchSuccess({ id: "i1" }); + const body = { ders_saati: 4, counts_toward_karne: false }; + + await patchInstanceById("i1", body); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/instances/i1"); + expect(init?.method).toBe("PATCH"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("getInstanceEnrollments GETs /instances/:id/enrollments with pagination", async () => { + mockFetchSuccess({ items: [], total: 0 }); + + await getInstanceEnrollments("i1", { limit: 5 }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/instances/i1/enrollments?limit=5"); + }); + + it("postInstanceEnrollment POSTs /instances/:id/enrollments with the user id", async () => { + mockFetchSuccess({ id: "e1" }); + + await postInstanceEnrollment("i1", "u1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/instances/i1/enrollments"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify({ user_id: "u1" })); + }); + + it("deleteInstanceEnrollmentByUserId DELETEs /instances/:id/enrollments/:user", async () => { + mockFetch204(); + + await deleteInstanceEnrollmentByUserId("i1", "u1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/instances/i1/enrollments/u1"); + expect(init?.method).toBe("DELETE"); + }); + + it("getInstanceExams GETs /instances/:id/exams", async () => { + mockFetchSuccess({ items: [], total: 0 }); + + await getInstanceExams("i1"); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/instances/i1/exams"); + }); + + it("postInstanceExam POSTs /instances/:id/exams with the term", async () => { + mockFetchSuccess({ id: "x1" }); + const body = { title: "Quiz 1", kind: "quiz", term: "t1" }; + + await postInstanceExam("i1", body); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/instances/i1/exams"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("getInstanceHomework GETs /instances/:id/homework", async () => { + mockFetchSuccess({ items: [], total: 0 }); + + await getInstanceHomework("i1"); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/instances/i1/homework"); + }); + + it("postInstanceHomework POSTs /instances/:id/homework with the body", async () => { + mockFetchSuccess({ id: "h1" }); + const body = { title: "Read ch. 3", subject_id: "s1", due_at: 1900000000000 }; + + await postInstanceHomework("i1", body); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/instances/i1/homework"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("getInstanceSessions GETs /instances/:id/sessions", async () => { + mockFetchSuccess({ items: [], total: 0 }); + + await getInstanceSessions("i1"); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/instances/i1/sessions"); + }); + + it("postInstanceSession POSTs /instances/:id/sessions with the body", async () => { + mockFetchSuccess({ id: "se1" }); + const body = { starts_at: 1900000000000, topic: "Limits" }; + + await postInstanceSession("i1", body); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/instances/i1/sessions"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("postInstanceTeacher POSTs /instances/:id/teachers with the user id", async () => { + mockFetchSuccess({ id: "i1" }); + + await postInstanceTeacher("i1", "t1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/instances/i1/teachers"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify({ user_id: "t1" })); + }); + + it("deleteInstanceTeacherByUserId DELETEs /instances/:id/teachers/:user", async () => { + mockFetch204(); + + await deleteInstanceTeacherByUserId("i1", "t1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/instances/i1/teachers/t1"); + expect(init?.method).toBe("DELETE"); + }); +}); diff --git a/src/api/__tests__/rag/rag.test.ts b/src/api/__tests__/rag/rag.test.ts new file mode 100644 index 0000000..d6e1d51 --- /dev/null +++ b/src/api/__tests__/rag/rag.test.ts @@ -0,0 +1,104 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + deleteRagThreadById, + getRagMessageById, + getRagThreadMessages, + getRagThreads, + patchRagThreadById, + postRagMessage, + postRagThread, + ragStreamUrl, +} from "../../rag"; +import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; + +describe("rag API", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("getRagThreads GETs /rag/threads with pagination", async () => { + mockFetchSuccess({ items: [{ id: "r1" }], total: 1 }); + + const result = await getRagThreads({ limit: 10 }); + expect(result.items).toEqual([{ id: "r1" }]); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/rag/threads?limit=10"); + expect(init?.method).toBe("GET"); + }); + + it("postRagThread POSTs /rag/threads with the title", async () => { + mockFetchSuccess({ id: "r1" }); + + await postRagThread("Fizik ödevi"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/rag/threads"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify({ title: "Fizik ödevi" })); + }); + + it("postRagThread sends a null title when none is given", async () => { + mockFetchSuccess({ id: "r1" }); + + await postRagThread(); + + const [, init] = lastFetchCall(); + expect(init?.body).toBe(JSON.stringify({ title: null })); + }); + + it("patchRagThreadById PATCHes /rag/threads/:id", async () => { + mockFetchSuccess({ id: "r1" }); + + await patchRagThreadById("r1", null); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/rag/threads/r1"); + expect(init?.method).toBe("PATCH"); + expect(init?.body).toBe(JSON.stringify({ title: null })); + }); + + it("deleteRagThreadById DELETEs /rag/threads/:id", async () => { + mockFetch204(); + + await deleteRagThreadById("r1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/rag/threads/r1"); + expect(init?.method).toBe("DELETE"); + }); + + it("getRagThreadMessages GETs /rag/threads/:id/messages", async () => { + mockFetchSuccess({ items: [], total: 0 }); + + await getRagThreadMessages("r1", { limit: 50 }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/rag/threads/r1/messages?limit=50"); + }); + + it("getRagMessageById GETs one turn", async () => { + mockFetchSuccess({ id: "m1", status: "pending" }); + + await getRagMessageById("r1", "m1"); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/rag/threads/r1/messages/m1"); + }); + + it("postRagMessage POSTs /rag/threads/:id/messages with the content", async () => { + mockFetchSuccess({ message_id: "m1", status: "pending" }, 202); + + const result = await postRagMessage("r1", "Newton'un ikinci yasası?"); + expect(result.message_id).toBe("m1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/rag/threads/r1/messages"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify({ content: "Newton'un ikinci yasası?" })); + }); + + it("ragStreamUrl builds the SSE path for an EventSource", () => { + expect(ragStreamUrl("r 1", "m1")).toBe("/api/rag/threads/r%201/messages/m1/stream"); + }); +}); diff --git a/src/api/__tests__/reports/reports.test.ts b/src/api/__tests__/reports/reports.test.ts index cf57452..812448e 100644 --- a/src/api/__tests__/reports/reports.test.ts +++ b/src/api/__tests__/reports/reports.test.ts @@ -4,6 +4,8 @@ import { getMyAttendance } from "../../reports"; import { getMyMarks } from "../../reports"; import { getUserAttendance } from "../../reports"; import { getUserMarks } from "../../reports"; +import { getMyKarne } from "../../reports"; +import { getUserKarne } from "../../reports"; import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch"; describe("reports API", () => { @@ -76,4 +78,32 @@ describe("reports API", () => { expect(url).toBe("/api/marks/u1"); expect(init?.method).toBe("GET"); }); + it("getMyKarne calls /marks/karne without a term", async () => { + mockFetchSuccess({ user: "u1", term: "t1", instances: [] }); + + await getMyKarne(); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/marks/karne"); + expect(init?.method).toBe("GET"); + }); + + it("getMyKarne passes the term through as a query", async () => { + mockFetchSuccess({ user: "u1", term: "t 1", instances: [] }); + + await getMyKarne("t 1"); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/marks/karne?term=t%201"); + }); + + it("getUserKarne calls /marks/karne/:user with the term", async () => { + mockFetchSuccess({ user: "u2", term: "t1", instances: [] }); + + await getUserKarne("u2", "t1"); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/marks/karne/u2?term=t1"); + }); + }); diff --git a/src/api/academic-years/deleteAcademicYearById.ts b/src/api/academic-years/deleteAcademicYearById.ts new file mode 100644 index 0000000..80916c4 --- /dev/null +++ b/src/api/academic-years/deleteAcademicYearById.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; + +/** 409 while any şube or dönem still links it. An archived year cannot be deleted. */ +export function deleteAcademicYearById(id: string): Promise { + return client(`/academic-years/${id}`, { method: "DELETE" }); +} diff --git a/src/api/academic-years/getAcademicYearById.ts b/src/api/academic-years/getAcademicYearById.ts new file mode 100644 index 0000000..38211c6 --- /dev/null +++ b/src/api/academic-years/getAcademicYearById.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; +import type { AcademicYear } from "../client"; + +export function getAcademicYearById(id: string, signal?: AbortSignal): Promise { + return client(`/academic-years/${id}`, { signal }); +} diff --git a/src/api/academic-years/getAcademicYears.ts b/src/api/academic-years/getAcademicYears.ts new file mode 100644 index 0000000..56b741a --- /dev/null +++ b/src/api/academic-years/getAcademicYears.ts @@ -0,0 +1,9 @@ +import { client } from "../client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { AcademicYear } from "../client"; + +/** Newest first. Requires teacher+. */ +export async function getAcademicYears(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/academic-years${pageQuery(params)}`, { signal }); + return normalizePage(data); +} diff --git a/src/api/academic-years/index.ts b/src/api/academic-years/index.ts new file mode 100644 index 0000000..81a2965 --- /dev/null +++ b/src/api/academic-years/index.ts @@ -0,0 +1,7 @@ +export * from "./getAcademicYears"; +export * from "./getAcademicYearById"; +export * from "./postAcademicYear"; +export * from "./patchAcademicYearById"; +export * from "./deleteAcademicYearById"; +export * from "./postAcademicYearArchive"; +export * from "./postAcademicYearRollover"; diff --git a/src/api/academic-years/patchAcademicYearById.ts b/src/api/academic-years/patchAcademicYearById.ts new file mode 100644 index 0000000..228151d --- /dev/null +++ b/src/api/academic-years/patchAcademicYearById.ts @@ -0,0 +1,15 @@ +import { client } from "../client"; +import type { AcademicYear, GradePromotion } from "../client"; + +export type PatchAcademicYearBody = { + name?: string | null; + starts_at?: number | null; + ends_at?: number | null; + /** The whole new policy, not a delta: a grade left out is no longer promoted. */ + grade_promotions?: GradePromotion[] | null; +}; + +/** An archived year is read-only. */ +export function patchAcademicYearById(id: string, body: PatchAcademicYearBody): Promise { + return client(`/academic-years/${id}`, { method: "PATCH", body }); +} diff --git a/src/api/academic-years/postAcademicYear.ts b/src/api/academic-years/postAcademicYear.ts new file mode 100644 index 0000000..a54f470 --- /dev/null +++ b/src/api/academic-years/postAcademicYear.ts @@ -0,0 +1,15 @@ +import { client } from "../client"; +import type { AcademicYear, GradePromotion } from "../client"; + +export type PostAcademicYearBody = { + name: string; + /** May lie in the past — a school adopting the app mid-year backfills legitimately. */ + starts_at: number; + ends_at: number; + /** The sınıf-geçme policy; omit while the rollover is undecided. */ + grade_promotions?: GradePromotion[] | null; +}; + +export function postAcademicYear(body: PostAcademicYearBody): Promise { + return client("/academic-years", { method: "POST", body }); +} diff --git a/src/api/academic-years/postAcademicYearArchive.ts b/src/api/academic-years/postAcademicYearArchive.ts new file mode 100644 index 0000000..1a61cee --- /dev/null +++ b/src/api/academic-years/postAcademicYearArchive.ts @@ -0,0 +1,10 @@ +import { client } from "../client"; +import type { AcademicYear } from "../client"; + +/** + * Freezes the year as past structure: no new şube, dönem or exam inside it, + * and no edit or delete. Idempotent, and there is no unarchive route. + */ +export function postAcademicYearArchive(id: string): Promise { + return client(`/academic-years/${id}/archive`, { method: "POST" }); +} diff --git a/src/api/academic-years/postAcademicYearRollover.ts b/src/api/academic-years/postAcademicYearRollover.ts new file mode 100644 index 0000000..be3f9ca --- /dev/null +++ b/src/api/academic-years/postAcademicYearRollover.ts @@ -0,0 +1,15 @@ +import { client } from "../client"; +import type { RolloverResult } from "../client"; + +/** + * Carries `from_year`'s şubeler into this year — same names, promoted grades, + * copies of their instances and live members. The target must be empty, open, + * and a different year; a second rollover is a 409, which is what makes the + * command idempotent. + */ +export function postAcademicYearRollover(id: string, fromYear: string): Promise { + return client(`/academic-years/${id}/rollover`, { + method: "POST", + body: { from_year: fromYear }, + }); +} diff --git a/src/api/ai/getAiCapabilities.ts b/src/api/ai/getAiCapabilities.ts new file mode 100644 index 0000000..d46a75f --- /dev/null +++ b/src/api/ai/getAiCapabilities.ts @@ -0,0 +1,10 @@ +import { client } from "../client"; +import type { AiCapabilities } from "../client"; + +/** + * What the AI bridge can currently do. `enabled: false` is a discovery answer, + * not an error — the deployment simply runs no AI. + */ +export function getAiCapabilities(signal?: AbortSignal): Promise { + return client("/ai/capabilities", { signal }); +} diff --git a/src/api/ai/index.ts b/src/api/ai/index.ts index 78fd8d1..dda4f28 100644 --- a/src/api/ai/index.ts +++ b/src/api/ai/index.ts @@ -1 +1,2 @@ export * from "./getBridgeCertificate"; +export * from "./getAiCapabilities"; diff --git a/src/api/classes/deleteClassCourse.ts b/src/api/classes/deleteClassCourse.ts deleted file mode 100644 index fc64666..0000000 --- a/src/api/classes/deleteClassCourse.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { client } from "../client"; - -// Detaches the course and sweeps only the rows this class pumped. Needs -// course-manage rights, except when the course row is already gone. -export function deleteClassCourse(classId: string, courseId: string): Promise { - return client(`/classes/${classId}/courses/${courseId}`, { method: "DELETE" }); -} diff --git a/src/api/classes/deleteClassInstance.ts b/src/api/classes/deleteClassInstance.ts new file mode 100644 index 0000000..7210696 --- /dev/null +++ b/src/api/classes/deleteClassInstance.ts @@ -0,0 +1,12 @@ +import { client } from "../client"; + +/** + * Detaches an instance from a class. The second segment is the **instance id** + * (`getClassInstances`), not a course id — two sections teaching the same + * course hold two instances. Everything the class taught under it goes with + * it: exams, homework, sessions, roll call, and the whole roster, hand-placed + * rows included (an enrollment cannot outlive its instance). + */ +export function deleteClassInstance(classId: string, instanceId: string): Promise { + return client(`/classes/${classId}/instances/${instanceId}`, { method: "DELETE" }); +} diff --git a/src/api/classes/getClassCourses.ts b/src/api/classes/getClassCourses.ts deleted file mode 100644 index f9c4932..0000000 --- a/src/api/classes/getClassCourses.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { client } from "../client"; -import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; -import type { ClassCourse } from "../client"; - -export async function getClassCourses(classId: string, params?: PageParams, signal?: AbortSignal): Promise> { - const data = await client(`/classes/${classId}/courses${pageQuery(params)}`, { signal }); - return normalizePage(data); -} diff --git a/src/api/classes/getClassInstances.ts b/src/api/classes/getClassInstances.ts new file mode 100644 index 0000000..dbb991d --- /dev/null +++ b/src/api/classes/getClassInstances.ts @@ -0,0 +1,16 @@ +import { client } from "../client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { ClassCourse } from "../client"; + +/** + * The instances a class carries — each a catalog course as this section + * teaches it, with its hours, karne policy and teachers. Requires teacher+. + */ +export async function getClassInstances( + classId: string, + params?: PageParams, + signal?: AbortSignal, +): Promise> { + const data = await client(`/classes/${classId}/instances${pageQuery(params)}`, { signal }); + return normalizePage(data); +} diff --git a/src/api/classes/index.ts b/src/api/classes/index.ts index f1e517e..cdeca43 100644 --- a/src/api/classes/index.ts +++ b/src/api/classes/index.ts @@ -8,9 +8,9 @@ export * from "./deleteClassById"; export * from "./postClassMember"; export * from "./getClassMembers"; export * from "./deleteClassMember"; -export * from "./postClassCourse"; -export * from "./getClassCourses"; -export * from "./deleteClassCourse"; +export * from "./postClassInstance"; +export * from "./getClassInstances"; +export * from "./deleteClassInstance"; export * from "./postClassBlueprint"; export * from "./getClassBlueprints"; export * from "./getClassBlueprintByGrade"; diff --git a/src/api/classes/patchClassById.ts b/src/api/classes/patchClassById.ts index 2c41947..e5b7f64 100644 --- a/src/api/classes/patchClassById.ts +++ b/src/api/classes/patchClassById.ts @@ -1,11 +1,12 @@ import { client } from "../client"; import type { ClassGroup } from "../client"; -// Omit a field to keep it; send null on grade/term_id/teacher_id to clear/unlink it. +// Omit a field to keep it; send null on grade/year/teacher_id to clear/unlink it. export type UpdateClassBody = { name?: string; grade?: string | null; - term_id?: string | null; + /** 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 b4b7e7c..4a2423e 100644 --- a/src/api/classes/postClass.ts +++ b/src/api/classes/postClass.ts @@ -1,7 +1,9 @@ import { client } from "../client"; import type { ClassGroup } from "../client"; -export type CreateClassBody = { name: string; grade?: string; term_id?: string; teacher_id?: string }; +// `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 }; export function postClass(body: CreateClassBody): Promise { return client("/classes", { method: "POST", body }); diff --git a/src/api/classes/postClassCourse.ts b/src/api/classes/postClassCourse.ts deleted file mode 100644 index 79cf799..0000000 --- a/src/api/classes/postClassCourse.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { client } from "../client"; -import type { ClassCourse } from "../client"; - -export type AttachCourseBody = { course_id: string }; - -// Bulk-enrolls the whole roster into the course. Needs course-manage rights -// (403 otherwise); 409 on duplicate, ceiling, or a course too small to seat -// the class. -export function postClassCourse(classId: string, body: AttachCourseBody): Promise { - return client(`/classes/${classId}/courses`, { method: "POST", body }); -} diff --git a/src/api/classes/postClassInstance.ts b/src/api/classes/postClassInstance.ts new file mode 100644 index 0000000..85e946f --- /dev/null +++ b/src/api/classes/postClassInstance.ts @@ -0,0 +1,14 @@ +import { client } from "../client"; +import type { ClassCourse } from "../client"; + +export type AttachCourseBody = { course_id: string }; + +/** + * Attaching a catalog course to a şube is what **mints the instance** — the + * class×course row every exam, session and roster keys on. The class's whole + * roster is enrolled in one go; students already enrolled by hand keep their + * own rows. Needs teacher+ and catalog rights on the course; 409 on a repeat. + */ +export function postClassInstance(classId: string, body: AttachCourseBody): Promise { + return client(`/classes/${classId}/instances`, { method: "POST", body }); +} diff --git a/src/api/client/types.ts b/src/api/client/types.ts index b306f31..426427d 100644 --- a/src/api/client/types.ts +++ b/src/api/client/types.ts @@ -281,20 +281,79 @@ export const BANK_QUESTION_LIMITS = { maxChoices: 10, // MAX_QUESTION_CHOICES } as const; +// A catalog course: the school's course row, taught by nobody on its own. A +// sube attaches it (POST /classes/{id}/instances), which mints the Instance +// every exam, session, homework and enrollment keys on. export type Course = { id: string; creator: PersonRef; - teachers?: PersonRef[]; title: string; description: string; kind: CourseKind; - term: string | null; - capacity: number | null; + // How many instances teach it (how many sections took it). + class_course_count: number; + // Individual club/etut memberships on the catalog row itself. + course_membership_count: number; +}; + +// One catalog course as one sube teaches it. This is what carries the roster, +// the exams, the sessions and the karne weight. +export type Instance = { + id: string; + class: string; + course: string; + // Weekly lesson hours; the instance's weight in the year's karne average. + ders_saati: number; + counts_toward_karne: boolean; + enrollment_count: number; + teachers: PersonRef[]; +}; + +// A club/etut membership on the catalog course itself — the school-scoped +// tier, distinct from an instance's roster. A regular `course` has none. +export type CourseMembership = { + id: string; + course: string; + user: PersonRef; + added_by: PersonRef; + created_at: number; +}; + +/** One sınıf-geçme pair: the grade label students move to at rollover. */ +export type GradePromotion = { + from_grade: string; + to_grade: string; +}; + +// An academic year: the calendar structure dönemler and şubeler hang off. +// Archiving freezes it — no new şube, dönem or exam inside it, and no edit. +export type AcademicYear = { + id: string; + name: string; + starts_at: number; + ends_at: number; + creator: string; + grade_promotions: GradePromotion[]; + class_count: number; + term_count: number; + /** Archived at, UTC unix-millis; null while the year is open. */ + archived_at: number | null; +}; + +/** What one rollover carried into the target year. */ +export type RolloverResult = { + year: string; + classes: number; + students: number; + /** Grade labels left behind because the year promotes them nowhere. */ + graduated: string[]; }; export type Term = { id: string; name: string; + /** The academic year the dönem sits in. */ + year: string; starts_at: number; ends_at: number; /** Archived at, UTC unix-millis; null while the term is open. */ @@ -303,7 +362,8 @@ export type Term = { export type Enrollment = { id: string; - course: string; + /** The instance (class x course) the student is enrolled in. */ + class_course: string; user: PersonRef; enrolled_by: PersonRef; // The class (ClassGroup id) that pumped this enrollment, or null for a @@ -323,7 +383,9 @@ export type ClassGroup = { creator: PersonRef | null; name: string; grade: string | null; - term: string | null; + // 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; // The class's homeroom teacher (sınıf öğretmeni); null when none is assigned. teacher: PersonRef | null; }; @@ -335,10 +397,9 @@ export type ClassMember = { added_by: PersonRef; }; -export type ClassCourse = { - id: string; - class: string; - course: string; +// The instance as the class routes return it: an Instance plus who attached +// the course to the sube. +export type ClassCourse = Instance & { attached_by: PersonRef; }; @@ -384,7 +445,8 @@ export type BlueprintStatus = { export type CourseSession = { id: string; - course: string; + /** The instance this lesson belongs to. */ + class_course: string; teacher: PersonRef; topic: string; starts_at: number; @@ -394,7 +456,7 @@ export type CourseSession = { export type SessionAttendance = { id: string; session: string; - course: string; + class_course: string; user: PersonRef; status: AttendanceStatus; marked_by: PersonRef; @@ -403,7 +465,10 @@ export type SessionAttendance = { export type Exam = { id: string; creator: string; - course: string; + /** The instance the exam is set in. */ + class_course: string; + /** The dönem the exam is sat in; its marks count into that term's karne. */ + term: string; title: string; description: string; kind: ExamKind | string; @@ -554,6 +619,8 @@ export type MarkEntry = { }; export type CourseMarks = { + /** The instance these marks belong to; two sections are two blocks. */ + instance: string; course: Course; results: MarkEntry[]; average: number | null; @@ -571,15 +638,36 @@ export type AttendanceCounts = { }; export type CourseAttendance = { + /** The instance these tallies belong to. */ + instance: string; course: Course; counts: AttendanceCounts; }; +/** The configured per-dönem absence limits; null per limit when unset. */ +export type AbsenceLimits = { + max_excused_days: number | null; + max_unexcused_days: number | null; +}; + +// One dönem's devamsızlık. A *day* is a calendar day with at least one missed +// lesson — two absences in one day count once, the way the regulation counts. +export type TermAbsence = { + term: string; + name: string; + absent_days: number; + excused_days: number; + unexcused_days: number; + limits: AbsenceLimits; + over_limit: boolean; +}; + export type AttendanceReport = { user: string; events: AttendanceCounts; sessions: AttendanceCounts; courses: CourseAttendance[]; + devamsizlik: TermAbsence[]; }; export type WorkEntry = { @@ -678,6 +766,18 @@ export type SchoolSettings = { meal_slots: MealSlot[]; dietary_tags: string[]; meal_cancel_cutoff_minutes: number | null; + // The branş (teaching subject) vocabulary a profile's `branch` may name. + // Empty = the school keeps no list, and no profile may carry one. + branches: string[]; + /** What an absence may be excused as (raporlu/izinli/…). Empty = none named. */ + excuse_kinds: string[]; + /** Per-dönem excused-absence day limit; null = no limit configured. */ + max_excused_absent_days: number | null; + /** Per-dönem unexcused-absence day limit; null = no limit configured. */ + max_unexcused_absent_days: number | null; + // The school's IANA timezone; null = the deployment default + // (Europe/Istanbul). It is the zone devamsızlık days are bucketed in. + timezone: string | null; }; export type Limits = { @@ -835,6 +935,25 @@ export type Limits = { }; request: { max_page_limit: number; max_request_id_len: number; schedule_past_grace_ms: number; request_timeout_secs: number }; rate: { window_secs: number; auth_per_minute: number; api_per_minute: number; chatbot_per_minute: number }; + // The RAG nest. Message length, thread titles, history depth and the thread + // cap are the chatbot's own knobs, republished so a RAG client need not read + // the chatbot group to bound its input. + rag: { + max_scope_pairs: number; + max_citations: number; + max_citation_pages: number; + max_message_len: number; + max_thread_title_len: number; + min_max_message_len: number; + max_max_message_len: number; + default_max_message_len: number; + min_history_turns: number; + max_history_turns: number; + default_history_turns: number; + min_max_threads: number; + max_max_threads: number; + default_max_threads: number; + }; }; // Fallbacks keep forms usable when the unauthenticated metadata request fails. @@ -861,7 +980,7 @@ export type Message = { export type Homework = { id: string; - course: string; + class_course: string; subject: string; title: string; description: string | null; @@ -909,7 +1028,7 @@ export type HomeworkRosterEntry = { }; export type HomeworkReportEntry = { - course: string; + class_course: string; homework: string; title: string; subject: string; @@ -983,3 +1102,86 @@ export type MealLedgerEntry = { recorded_by: PersonRef; created_at: number; }; + +// One instance's line on a karne: the dönem average, its band label, and the +// ders_saati it weighs into the year average with. +export type KarneInstance = { + class_course: string; + /** The catalog course's title — what a family reads. */ + course: string; + ders_saati: number; + average: number | null; + band: string | null; +}; + +// A student's karne for one dönem. An archived dönem serves the snapshot the +// school froze when it closed; an open one computes live. +export type KarneReport = { + user: string; + term: string; + instances: KarneInstance[]; + /** The ders_saati-weighted average; null while nothing is graded. */ + year_average: number | null; + /** `gecti` / `kaldi`, or null with no average or no passing floor. */ + verdict: string | null; +}; + +/** One instance an exam is announced to beyond the one that owns it. */ +export type ExamAudience = { + instance: string; + class: string; + course: string; +}; + +export type RagThread = { + id: string; + title: string | null; + created_at: number; + updated_at: number; +}; + +export type RagMessageStatus = "pending" | "complete" | "failed"; + +// One citation behind a RAG answer. `[N]` in the answer's content resolves to +// the citation whose `n` is N. `file` is null when no file the asker may view +// claims the document — citable, just not openable. +export type RagCitation = { + n: number; + pages: number[]; + span_ids: string[]; + ders?: string | null; + file?: string | null; +}; + +export type RagMessage = { + id: string; + thread_id: string; + role: "user" | "assistant" | string; + status: RagMessageStatus | string; + /** Empty while `status` is `pending`. */ + content: string; + /** True when the service declined to answer — a complete turn, not a failure. */ + abstained: boolean; + /** The abstention's short machine code; "" on an ordinary answer. */ + reason: string; + citations: RagCitation[]; + created_at: number; + completed_at?: number | null; + /** Set only when `status` is `failed`. Backend English — localize it. */ + error_code?: string | null; +}; + +/** One capability's live fleet on the AI bridge. */ +export type AiCapabilityWorkers = { + capability: string; + workers: number; + inflight: number; +}; + +// What the AI bridge can currently do. `enabled: false` is a discovery +// answer, not an error: the deployment simply runs no AI. +export type AiCapabilities = { + enabled: boolean; + protocol: string; + capabilities: AiCapabilityWorkers[]; +}; diff --git a/src/api/course-notes/index.ts b/src/api/course-notes/index.ts index 908def6..b3a0246 100644 --- a/src/api/course-notes/index.ts +++ b/src/api/course-notes/index.ts @@ -10,3 +10,4 @@ export * from "./getCourseNoteFileUrl"; export * from "./getCourseNoteFileBlob"; export * from "./getCourseNoteRag"; export * from "./deleteCourseNoteRagOutput"; +export * from "./postCourseNoteRagReindex"; diff --git a/src/api/course-notes/postCourseNoteRagReindex.ts b/src/api/course-notes/postCourseNoteRagReindex.ts new file mode 100644 index 0000000..f50d144 --- /dev/null +++ b/src/api/course-notes/postCourseNoteRagReindex.ts @@ -0,0 +1,9 @@ +import { client } from "../client"; + +/** + * Re-index a course note now instead of waiting for its next write. 202 — + * the work is queued, not done by the time this resolves. + */ +export function postCourseNoteRagReindex(noteId: string): Promise { + return client(`/course-notes/${noteId}/rag/reindex`, { method: "POST" }); +} diff --git a/src/api/courses/deleteCourseEnrollmentByUserId.ts b/src/api/courses/deleteCourseEnrollmentByUserId.ts deleted file mode 100644 index c64d175..0000000 --- a/src/api/courses/deleteCourseEnrollmentByUserId.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { client } from "../client"; - -export function deleteCourseEnrollmentByUserId( - courseId: string, - userId: string, -): Promise { - return client(`/courses/${courseId}/enrollments/${userId}`, { - method: "DELETE", - }); -} diff --git a/src/api/courses/deleteCourseMemberByUserId.ts b/src/api/courses/deleteCourseMemberByUserId.ts new file mode 100644 index 0000000..d02cedf --- /dev/null +++ b/src/api/courses/deleteCourseMemberByUserId.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; + +/** Exam results and badges are untouched — the membership is a door, not a record. */ +export function deleteCourseMemberByUserId(courseId: string, userId: string): Promise { + return client(`/courses/${courseId}/members/${userId}`, { method: "DELETE" }); +} diff --git a/src/api/courses/deleteCourseTeacherByUserId.ts b/src/api/courses/deleteCourseTeacherByUserId.ts deleted file mode 100644 index b7e1a8e..0000000 --- a/src/api/courses/deleteCourseTeacherByUserId.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { client } from "../client"; - -export function deleteCourseTeacherByUserId( - courseId: string, - userId: string, -): Promise { - return client(`/courses/${courseId}/teachers/${userId}`, { - method: "DELETE", - }); -} diff --git a/src/api/courses/getCourseMembers.ts b/src/api/courses/getCourseMembers.ts new file mode 100644 index 0000000..5ae2886 --- /dev/null +++ b/src/api/courses/getCourseMembers.ts @@ -0,0 +1,16 @@ +import { client } from "../client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { CourseMembership } from "../client"; + +/** + * A club/etüt's own members — the school-scoped tier. An instance's roster is + * `getInstanceEnrollments`. Requires teacher+ and catalog rights. + */ +export async function getCourseMembers( + courseId: string, + params?: PageParams, + signal?: AbortSignal, +): Promise> { + const data = await client(`/courses/${courseId}/members${pageQuery(params)}`, { signal }); + return normalizePage(data); +} diff --git a/src/api/courses/index.ts b/src/api/courses/index.ts index f3aa9d8..c4c5b78 100644 --- a/src/api/courses/index.ts +++ b/src/api/courses/index.ts @@ -3,17 +3,8 @@ export * from "./getCourseById"; export * from "./postCourse"; export * from "./patchCourseById"; export * from "./deleteCourseById"; -export * from "./getCourseEnrollments"; -export * from "./postCourseEnrollment"; -export * from "./deleteCourseEnrollmentByUserId"; -export * from "./getCourseSessions"; -export * from "./postCourseSession"; export * from "./getCourseSubjects"; export * from "./postCourseSubject"; -export * from "./getCourseExams"; -export * from "./postCourseExam"; -export * from "./postCourseTeacher"; -export * from "./deleteCourseTeacherByUserId"; -export * from "./getCourseHomework"; -export * from "./postCourseHomework"; - +export * from "./getCourseMembers"; +export * from "./postCourseMember"; +export * from "./deleteCourseMemberByUserId"; diff --git a/src/api/courses/patchCourseById.ts b/src/api/courses/patchCourseById.ts index 1f4295e..9483459 100644 --- a/src/api/courses/patchCourseById.ts +++ b/src/api/courses/patchCourseById.ts @@ -1,13 +1,11 @@ import { client } from "../client"; import type { Course, CourseKind } from "../client"; -/** Omitted fields keep their value. Only `term_id`/`capacity` clear on explicit null. */ +/** Omitted fields keep their value. Requires catalog rights: creator or manager+. */ export type PatchCourseBody = { title?: string; description?: string; kind?: CourseKind; - term_id?: string | null; - capacity?: number | null; }; export function patchCourseById(id: string, body: PatchCourseBody): Promise { diff --git a/src/api/courses/postCourse.ts b/src/api/courses/postCourse.ts index 26176b1..178e458 100644 --- a/src/api/courses/postCourse.ts +++ b/src/api/courses/postCourse.ts @@ -1,12 +1,14 @@ import { client } from "../client"; import type { Course, CourseKind } from "../client"; +/** + * A catalog row teaches nobody by itself — a şube attaches it + * (`postClassInstance`), which is what mints the instance students sit in. + */ export type PostCourseBody = { title: string; description?: string | null; kind?: CourseKind | null; - term_id?: string | null; - capacity?: number | null; }; export function postCourse(body: PostCourseBody): Promise { diff --git a/src/api/courses/postCourseEnrollment.ts b/src/api/courses/postCourseEnrollment.ts deleted file mode 100644 index 7abdba5..0000000 --- a/src/api/courses/postCourseEnrollment.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { client } from "../client"; -import type { Enrollment } from "../client"; - -export function postCourseEnrollment( - courseId: string, - userId: string, -): Promise { - return client(`/courses/${courseId}/enrollments`, { - method: "POST", - body: { user_id: userId }, - }); -} diff --git a/src/api/courses/postCourseExam.ts b/src/api/courses/postCourseExam.ts deleted file mode 100644 index c8a9fa6..0000000 --- a/src/api/courses/postCourseExam.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { client } from "../client"; -import type { Exam } from "../client"; - -export type PostCourseExamBody = { - title: string; - description?: string | null; - kind: string; - mode?: string | null; - starts_at?: number | null; - ends_at?: number | null; - duration_ms?: number | null; - max_attempts?: number | null; - allow_rejoin?: boolean | null; - allow_review?: boolean | null; - draft?: boolean | null; -}; - -export function postCourseExam( - courseId: string, - body: PostCourseExamBody, -): Promise { - return client(`/courses/${courseId}/exams`, { method: "POST", body }); -} diff --git a/src/api/courses/postCourseHomework.ts b/src/api/courses/postCourseHomework.ts deleted file mode 100644 index 73d235e..0000000 --- a/src/api/courses/postCourseHomework.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { client } from "../client"; -import type { Homework } from "../client"; - -export type PostCourseHomeworkBody = { - title: string; - description?: string | null; - subject_id: string; - due_at: number; - assigned?: string[] | null; -}; - -export function postCourseHomework(courseId: string, body: PostCourseHomeworkBody): Promise { - return client(`/courses/${courseId}/homework`, { method: "POST", body }); -} diff --git a/src/api/courses/postCourseMember.ts b/src/api/courses/postCourseMember.ts new file mode 100644 index 0000000..84efde2 --- /dev/null +++ b/src/api/courses/postCourseMember.ts @@ -0,0 +1,13 @@ +import { client } from "../client"; +import type { CourseMembership } from "../client"; + +/** + * Only students, and only into a `study` (etüt) or `club` (kulüp): a regular + * ders has no school-wide roster — its students come from the şube. + */ +export function postCourseMember(courseId: string, userId: string): Promise { + return client(`/courses/${courseId}/members`, { + method: "POST", + body: { user_id: userId }, + }); +} diff --git a/src/api/courses/postCourseSession.ts b/src/api/courses/postCourseSession.ts deleted file mode 100644 index 3eb82ec..0000000 --- a/src/api/courses/postCourseSession.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { client } from "../client"; -import type { CourseSession } from "../client"; - -export type PostCourseSessionBody = { - topic?: string | null; - teacher_id?: string | null; - starts_at: number; - ends_at?: number | null; -}; - -export function postCourseSession(courseId: string, body: PostCourseSessionBody): Promise { - return client(`/courses/${courseId}/sessions`, { method: "POST", body }); -} diff --git a/src/api/courses/postCourseTeacher.ts b/src/api/courses/postCourseTeacher.ts deleted file mode 100644 index b63ef48..0000000 --- a/src/api/courses/postCourseTeacher.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { client } from "../client"; -import type { Course } from "../client"; - -export function postCourseTeacher( - courseId: string, - userId: string, -): Promise { - return client(`/courses/${courseId}/teachers`, { - method: "POST", - body: { user_id: userId }, - }); -} diff --git a/src/api/exams/deleteExamAudienceByInstanceId.ts b/src/api/exams/deleteExamAudienceByInstanceId.ts new file mode 100644 index 0000000..6c9105f --- /dev/null +++ b/src/api/exams/deleteExamAudienceByInstanceId.ts @@ -0,0 +1,5 @@ +import { client } from "../client"; + +export function deleteExamAudienceByInstanceId(examId: string, instanceId: string): Promise { + return client(`/exams/${examId}/audience/${instanceId}`, { method: "DELETE" }); +} diff --git a/src/api/exams/getExamAudience.ts b/src/api/exams/getExamAudience.ts new file mode 100644 index 0000000..130ad1a --- /dev/null +++ b/src/api/exams/getExamAudience.ts @@ -0,0 +1,13 @@ +import { client } from "../client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { ExamAudience } from "../client"; + +/** The instances this exam is announced to beyond the one that owns it. */ +export async function getExamAudience( + examId: string, + params?: PageParams, + signal?: AbortSignal, +): Promise> { + const data = await client(`/exams/${examId}/audience${pageQuery(params)}`, { signal }); + return normalizePage(data); +} diff --git a/src/api/exams/index.ts b/src/api/exams/index.ts index 7645ecf..03214ee 100644 --- a/src/api/exams/index.ts +++ b/src/api/exams/index.ts @@ -39,3 +39,6 @@ export * from "./getStudentMarksHistory"; export * from "./postExamQuestionFromBank"; export * from "./postExamQuestionRefreshFromBank"; export * from "./postExamQuestionToBank"; +export * from "./getExamAudience"; +export * from "./postExamAudience"; +export * from "./deleteExamAudienceByInstanceId"; diff --git a/src/api/exams/postExamAudience.ts b/src/api/exams/postExamAudience.ts new file mode 100644 index 0000000..dda4737 --- /dev/null +++ b/src/api/exams/postExamAudience.ts @@ -0,0 +1,14 @@ +import { client } from "../client"; +import type { ExamAudience } from "../client"; + +/** + * Announce the exam to another instance. It must teach the exam's own catalog + * course, sit under the same academic year, and be a different instance — the + * owner is refused with a 400. + */ +export function postExamAudience(examId: string, instanceId: string): Promise { + return client(`/exams/${examId}/audience`, { + method: "POST", + body: { instance: instanceId }, + }); +} diff --git a/src/api/instances/deleteInstanceEnrollmentByUserId.ts b/src/api/instances/deleteInstanceEnrollmentByUserId.ts new file mode 100644 index 0000000..9caf913 --- /dev/null +++ b/src/api/instances/deleteInstanceEnrollmentByUserId.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; + +/** Existing exam results are kept — they leave the marks report until re-enrolled. */ +export function deleteInstanceEnrollmentByUserId(instanceId: string, userId: string): Promise { + return client(`/instances/${instanceId}/enrollments/${userId}`, { method: "DELETE" }); +} diff --git a/src/api/instances/deleteInstanceTeacherByUserId.ts b/src/api/instances/deleteInstanceTeacherByUserId.ts new file mode 100644 index 0000000..19b2200 --- /dev/null +++ b/src/api/instances/deleteInstanceTeacherByUserId.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; + +/** Manager+ only. The instance, its exams, sessions and roster are untouched. */ +export function deleteInstanceTeacherByUserId(instanceId: string, userId: string): Promise { + return client(`/instances/${instanceId}/teachers/${userId}`, { method: "DELETE" }); +} diff --git a/src/api/instances/getInstanceById.ts b/src/api/instances/getInstanceById.ts new file mode 100644 index 0000000..1dbc9df --- /dev/null +++ b/src/api/instances/getInstanceById.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; +import type { Instance } from "../client"; + +export function getInstanceById(id: string, signal?: AbortSignal): Promise { + return client(`/instances/${id}`, { signal }); +} diff --git a/src/api/courses/getCourseEnrollments.ts b/src/api/instances/getInstanceEnrollments.ts similarity index 61% rename from src/api/courses/getCourseEnrollments.ts rename to src/api/instances/getInstanceEnrollments.ts index 4cff2bd..2008926 100644 --- a/src/api/courses/getCourseEnrollments.ts +++ b/src/api/instances/getInstanceEnrollments.ts @@ -2,11 +2,11 @@ import { client } from "../client"; import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; import type { Enrollment } from "../client"; -export async function getCourseEnrollments( - courseId: string, +export async function getInstanceEnrollments( + instanceId: string, params?: PageParams, signal?: AbortSignal, ): Promise> { - const data = await client(`/courses/${courseId}/enrollments${pageQuery(params)}`, { signal }); + const data = await client(`/instances/${instanceId}/enrollments${pageQuery(params)}`, { signal }); return normalizePage(data); } diff --git a/src/api/courses/getCourseExams.ts b/src/api/instances/getInstanceExams.ts similarity index 54% rename from src/api/courses/getCourseExams.ts rename to src/api/instances/getInstanceExams.ts index 25d5c2f..1fd0293 100644 --- a/src/api/courses/getCourseExams.ts +++ b/src/api/instances/getInstanceExams.ts @@ -2,11 +2,12 @@ import { client } from "../client"; import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; import type { Exam } from "../client"; -export async function getCourseExams( - courseId: string, +/** Drafts appear only to the instance's managers. */ +export async function getInstanceExams( + instanceId: string, params?: PageParams, signal?: AbortSignal, ): Promise> { - const data = await client(`/courses/${courseId}/exams${pageQuery(params)}`, { signal }); + const data = await client(`/instances/${instanceId}/exams${pageQuery(params)}`, { signal }); return normalizePage(data); } diff --git a/src/api/courses/getCourseHomework.ts b/src/api/instances/getInstanceHomework.ts similarity index 51% rename from src/api/courses/getCourseHomework.ts rename to src/api/instances/getInstanceHomework.ts index 5cfdc28..329e1e4 100644 --- a/src/api/courses/getCourseHomework.ts +++ b/src/api/instances/getInstanceHomework.ts @@ -2,11 +2,12 @@ import { client } from "../client"; import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; import type { Homework } from "../client"; -export async function getCourseHomework( - courseId: string, +/** A student sees only the homework they are assigned, `assigned` narrowed to themselves. */ +export async function getInstanceHomework( + instanceId: string, params?: PageParams, signal?: AbortSignal, ): Promise> { - const data = await client(`/courses/${courseId}/homework${pageQuery(params)}`, { signal }); + const data = await client(`/instances/${instanceId}/homework${pageQuery(params)}`, { signal }); return normalizePage(data); } diff --git a/src/api/courses/getCourseSessions.ts b/src/api/instances/getInstanceSessions.ts similarity index 63% rename from src/api/courses/getCourseSessions.ts rename to src/api/instances/getInstanceSessions.ts index d7dbb79..4178391 100644 --- a/src/api/courses/getCourseSessions.ts +++ b/src/api/instances/getInstanceSessions.ts @@ -2,11 +2,11 @@ import { client } from "../client"; import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; import type { CourseSession } from "../client"; -export async function getCourseSessions( - courseId: string, +export async function getInstanceSessions( + instanceId: string, params?: PageParams, signal?: AbortSignal, ): Promise> { - const data = await client(`/courses/${courseId}/sessions${pageQuery(params)}`, { signal }); + const data = await client(`/instances/${instanceId}/sessions${pageQuery(params)}`, { signal }); return normalizePage(data); } diff --git a/src/api/instances/getMyInstances.ts b/src/api/instances/getMyInstances.ts new file mode 100644 index 0000000..612787b --- /dev/null +++ b/src/api/instances/getMyInstances.ts @@ -0,0 +1,13 @@ +import { client } from "../client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { Instance } from "../client"; + +/** + * The instances the caller may act in or see: a student's şube memberships, a + * homeroom teacher's, plus the instances a teacher was assigned to run. One + * rule for what is "theirs", shared with every instance-scoped gate. + */ +export async function getMyInstances(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/instances/me${pageQuery(params)}`, { signal }); + return normalizePage(data); +} diff --git a/src/api/instances/index.ts b/src/api/instances/index.ts new file mode 100644 index 0000000..e628488 --- /dev/null +++ b/src/api/instances/index.ts @@ -0,0 +1,14 @@ +export * from "./getMyInstances"; +export * from "./getInstanceById"; +export * from "./patchInstanceById"; +export * from "./getInstanceEnrollments"; +export * from "./postInstanceEnrollment"; +export * from "./deleteInstanceEnrollmentByUserId"; +export * from "./getInstanceExams"; +export * from "./postInstanceExam"; +export * from "./getInstanceHomework"; +export * from "./postInstanceHomework"; +export * from "./getInstanceSessions"; +export * from "./postInstanceSession"; +export * from "./postInstanceTeacher"; +export * from "./deleteInstanceTeacherByUserId"; diff --git a/src/api/instances/patchInstanceById.ts b/src/api/instances/patchInstanceById.ts new file mode 100644 index 0000000..43bed9c --- /dev/null +++ b/src/api/instances/patchInstanceById.ts @@ -0,0 +1,12 @@ +import { client } from "../client"; +import type { Instance } from "../client"; + +/** Both fields are non-clearable: omit to keep, never send null. */ +export type PatchInstanceBody = { + ders_saati?: number; + counts_toward_karne?: boolean; +}; + +export function patchInstanceById(id: string, body: PatchInstanceBody): Promise { + return client(`/instances/${id}`, { method: "PATCH", body }); +} diff --git a/src/api/instances/postInstanceEnrollment.ts b/src/api/instances/postInstanceEnrollment.ts new file mode 100644 index 0000000..ffd451a --- /dev/null +++ b/src/api/instances/postInstanceEnrollment.ts @@ -0,0 +1,13 @@ +import { client } from "../client"; +import type { Enrollment } from "../client"; + +/** + * Idempotent upsert; students only. The row is hand-placed (`source` null), so + * no şube sweep takes it back. + */ +export function postInstanceEnrollment(instanceId: string, userId: string): Promise { + return client(`/instances/${instanceId}/enrollments`, { + method: "POST", + body: { user_id: userId }, + }); +} diff --git a/src/api/instances/postInstanceExam.ts b/src/api/instances/postInstanceExam.ts new file mode 100644 index 0000000..217ca7c --- /dev/null +++ b/src/api/instances/postInstanceExam.ts @@ -0,0 +1,26 @@ +import { client } from "../client"; +import type { Exam } from "../client"; + +export type PostInstanceExamBody = { + title: string; + description?: string | null; + kind: string; + /** The dönem the exam is filed in — its marks count into that term's karne. */ + term: string; + /** Omit for an offline-graded exam nobody can sit. */ + mode?: string | null; + starts_at?: number | null; + ends_at?: number | null; + duration_ms?: number | null; + /** Default 1; `0` = unlimited retakes. */ + max_attempts?: number | null; + allow_rejoin?: boolean | null; + allow_review?: boolean | null; + /** Keeps the exam private to the instance's managers until published. */ + draft?: boolean | null; +}; + +/** Only a class-delivered course (`kind` `course`) carries exams. */ +export function postInstanceExam(instanceId: string, body: PostInstanceExamBody): Promise { + return client(`/instances/${instanceId}/exams`, { method: "POST", body }); +} diff --git a/src/api/instances/postInstanceHomework.ts b/src/api/instances/postInstanceHomework.ts new file mode 100644 index 0000000..cde4bb0 --- /dev/null +++ b/src/api/instances/postInstanceHomework.ts @@ -0,0 +1,17 @@ +import { client } from "../client"; +import type { Homework } from "../client"; + +export type PostInstanceHomeworkBody = { + title: string; + description?: string | null; + /** One of the catalog course's subjects — required. */ + subject_id: string; + /** Required and must be in the future. */ + due_at: number; + /** Omit, null or [] assigns the whole enrolled roster; a subset caps at 200. */ + assigned?: string[] | null; +}; + +export function postInstanceHomework(instanceId: string, body: PostInstanceHomeworkBody): Promise { + return client(`/instances/${instanceId}/homework`, { method: "POST", body }); +} diff --git a/src/api/instances/postInstanceSession.ts b/src/api/instances/postInstanceSession.ts new file mode 100644 index 0000000..d75f515 --- /dev/null +++ b/src/api/instances/postInstanceSession.ts @@ -0,0 +1,14 @@ +import { client } from "../client"; +import type { CourseSession } from "../client"; + +export type PostInstanceSessionBody = { + topic?: string | null; + /** Defaults to the caller; must hold `teacher` or higher. */ + teacher_id?: string | null; + starts_at: number; + ends_at?: number | null; +}; + +export function postInstanceSession(instanceId: string, body: PostInstanceSessionBody): Promise { + return client(`/instances/${instanceId}/sessions`, { method: "POST", body }); +} diff --git a/src/api/instances/postInstanceTeacher.ts b/src/api/instances/postInstanceTeacher.ts new file mode 100644 index 0000000..e85bb20 --- /dev/null +++ b/src/api/instances/postInstanceTeacher.ts @@ -0,0 +1,13 @@ +import { client } from "../client"; +import type { Instance } from "../client"; + +/** + * Manager+ only — staffing is the office's call. The assignee gets full + * management of the instance but no catalog rights over the course itself. + */ +export function postInstanceTeacher(instanceId: string, userId: string): Promise { + return client(`/instances/${instanceId}/teachers`, { + method: "POST", + body: { user_id: userId }, + }); +} diff --git a/src/api/rag/deleteRagThreadById.ts b/src/api/rag/deleteRagThreadById.ts new file mode 100644 index 0000000..f84a685 --- /dev/null +++ b/src/api/rag/deleteRagThreadById.ts @@ -0,0 +1,5 @@ +import { client } from "../client"; + +export function deleteRagThreadById(threadId: string): Promise { + return client(`/rag/threads/${encodeURIComponent(threadId)}`, { method: "DELETE" }); +} diff --git a/src/api/rag/getRagMessageById.ts b/src/api/rag/getRagMessageById.ts new file mode 100644 index 0000000..28de1e4 --- /dev/null +++ b/src/api/rag/getRagMessageById.ts @@ -0,0 +1,8 @@ +import { client } from "../client"; +import type { RagMessage } from "../client"; + +/** Poll this while a turn is `pending`, or open its stream instead. */ +export function getRagMessageById(threadId: string, messageId: string, signal?: AbortSignal): Promise { + const url = `/rag/threads/${encodeURIComponent(threadId)}/messages/${encodeURIComponent(messageId)}`; + return client(url, { signal }); +} diff --git a/src/api/rag/getRagThreadMessages.ts b/src/api/rag/getRagThreadMessages.ts new file mode 100644 index 0000000..602420c --- /dev/null +++ b/src/api/rag/getRagThreadMessages.ts @@ -0,0 +1,11 @@ +import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { RagMessage } from "../client"; + +export async function getRagThreadMessages( + threadId: string, + params?: PageParams, + signal?: AbortSignal, +): Promise> { + const url = `/rag/threads/${encodeURIComponent(threadId)}/messages${pageQuery(params)}`; + return normalizePage(await client(url, { signal })); +} diff --git a/src/api/rag/getRagThreads.ts b/src/api/rag/getRagThreads.ts new file mode 100644 index 0000000..08e30a8 --- /dev/null +++ b/src/api/rag/getRagThreads.ts @@ -0,0 +1,7 @@ +import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { RagThread } from "../client"; + +/** Sorted by `updated_at`, so the thread just written to is always first. */ +export async function getRagThreads(params?: PageParams, signal?: AbortSignal): Promise> { + return normalizePage(await client(`/rag/threads${pageQuery(params)}`, { signal })); +} diff --git a/src/api/rag/index.ts b/src/api/rag/index.ts new file mode 100644 index 0000000..1964e7a --- /dev/null +++ b/src/api/rag/index.ts @@ -0,0 +1,8 @@ +export * from "./getRagThreads"; +export * from "./postRagThread"; +export * from "./patchRagThreadById"; +export * from "./deleteRagThreadById"; +export * from "./getRagThreadMessages"; +export * from "./getRagMessageById"; +export * from "./postRagMessage"; +export * from "./ragStreamUrl"; diff --git a/src/api/rag/patchRagThreadById.ts b/src/api/rag/patchRagThreadById.ts new file mode 100644 index 0000000..b9fd6e6 --- /dev/null +++ b/src/api/rag/patchRagThreadById.ts @@ -0,0 +1,10 @@ +import { client } from "../client"; +import type { RagThread } from "../client"; + +/** `null` — or blank — clears the title back to untitled. */ +export function patchRagThreadById(threadId: string, title: string | null): Promise { + return client(`/rag/threads/${encodeURIComponent(threadId)}`, { + method: "PATCH", + body: { title }, + }); +} diff --git a/src/api/rag/postRagMessage.ts b/src/api/rag/postRagMessage.ts new file mode 100644 index 0000000..f18c4cb --- /dev/null +++ b/src/api/rag/postRagMessage.ts @@ -0,0 +1,18 @@ +import { client } from "../client"; + +/** The receipt for an accepted turn — the answer is not here yet. */ +export type AcceptedRagMessage = { + message_id: string; + status: "pending"; +}; + +/** + * 202. The live message-length cap is the school's `max_chatbot_message_len` + * (`GET /settings`), the same knob the chatbot nest uses. + */ +export function postRagMessage(threadId: string, content: string): Promise { + return client(`/rag/threads/${encodeURIComponent(threadId)}/messages`, { + method: "POST", + body: { content }, + }); +} diff --git a/src/api/rag/postRagThread.ts b/src/api/rag/postRagThread.ts new file mode 100644 index 0000000..4100cb0 --- /dev/null +++ b/src/api/rag/postRagThread.ts @@ -0,0 +1,7 @@ +import { client } from "../client"; +import type { RagThread } from "../client"; + +/** Blank counts as absent — an untitled thread is normal, labelled from its first turn. */ +export function postRagThread(title?: string | null): Promise { + return client("/rag/threads", { method: "POST", body: { title: title ?? null } }); +} diff --git a/src/api/rag/ragStreamUrl.ts b/src/api/rag/ragStreamUrl.ts new file mode 100644 index 0000000..fd3c606 --- /dev/null +++ b/src/api/rag/ragStreamUrl.ts @@ -0,0 +1,7 @@ +/** + * The SSE URL for one pending turn. Not a request — hand it to an + * `EventSource` (`withCredentials: true`), the way the çelebi panel does. + */ +export function ragStreamUrl(threadId: string, messageId: string): string { + return `/api/rag/threads/${encodeURIComponent(threadId)}/messages/${encodeURIComponent(messageId)}/stream`; +} diff --git a/src/api/reports/getMyKarne.ts b/src/api/reports/getMyKarne.ts new file mode 100644 index 0000000..a7bb7c9 --- /dev/null +++ b/src/api/reports/getMyKarne.ts @@ -0,0 +1,11 @@ +import { client } from "../client"; +import type { KarneReport } from "../client"; + +/** + * The caller's karne for one dönem. Omit `term` for the newest one. An + * archived dönem serves the snapshot the school froze when it closed. + */ +export function getMyKarne(term?: string, signal?: AbortSignal): Promise { + const query = term ? `?term=${encodeURIComponent(term)}` : ""; + return client(`/marks/karne${query}`, { signal }); +} diff --git a/src/api/reports/getUserKarne.ts b/src/api/reports/getUserKarne.ts new file mode 100644 index 0000000..1e6813d --- /dev/null +++ b/src/api/reports/getUserKarne.ts @@ -0,0 +1,12 @@ +import { client } from "../client"; +import type { KarneReport } from "../client"; + +/** + * Another user's karne. Requires teacher+, or a parent tied to the student. + * An exactly-teacher caller sees only the lines of the instances they run, + * with the average recomputed over those and no verdict. + */ +export function getUserKarne(userId: string, term?: string, signal?: AbortSignal): Promise { + const query = term ? `?term=${encodeURIComponent(term)}` : ""; + return client(`/marks/karne/${userId}${query}`, { signal }); +} diff --git a/src/api/reports/index.ts b/src/api/reports/index.ts index 4c36147..7025430 100644 --- a/src/api/reports/index.ts +++ b/src/api/reports/index.ts @@ -3,3 +3,5 @@ export * from "./getMyAttendance"; export * from "./getMyMarks"; export * from "./getUserAttendance"; export * from "./getUserMarks"; +export * from "./getMyKarne"; +export * from "./getUserKarne"; diff --git a/src/api/settings/patchSettings.ts b/src/api/settings/patchSettings.ts index c53373e..5e6c5b9 100644 --- a/src/api/settings/patchSettings.ts +++ b/src/api/settings/patchSettings.ts @@ -13,6 +13,15 @@ export type PatchSettingsBody = { meal_slots?: MealSlot[]; dietary_tags?: string[]; meal_cancel_cutoff_minutes?: number | null; + /** What an absence may be excused as (raporlu/izinli/…). */ + excuse_kinds?: string[]; + /** The branş vocabulary a profile's `branch` may name. */ + branches?: string[]; + /** Per-dönem day limits; null clears the limit. */ + max_excused_absent_days?: number | null; + max_unexcused_absent_days?: number | null; + /** IANA timezone the devamsızlık days are bucketed in; null = deployment default. */ + timezone?: string | null; }; export function patchSettings(body: PatchSettingsBody): Promise { diff --git a/src/api/terms/postTerm.ts b/src/api/terms/postTerm.ts index b35ee91..10e8a23 100644 --- a/src/api/terms/postTerm.ts +++ b/src/api/terms/postTerm.ts @@ -3,6 +3,8 @@ import type { Term } from "../client"; export type PostTermBody = { name: string; + /** The academic year the dönem sits in; an archived year refuses it (409). */ + year: string; starts_at: number; ends_at: number; }; diff --git a/src/components/attendance/attendance-report-view.tsx b/src/components/attendance/attendance-report-view.tsx index d11d463..8242309 100644 --- a/src/components/attendance/attendance-report-view.tsx +++ b/src/components/attendance/attendance-report-view.tsx @@ -133,6 +133,48 @@ export function AttendanceReportView(props: { report: AttendanceReport; compact? + {/* Devamsızlık is counted in *days*, not marks: two absences in one + calendar day count once, which is what the regulation counts. */} + 0}> +
+

{t("attendance.devamsizlik")}

+
+ + {(term) => ( +
+
+

{term.name}

+ + {t("attendance.overLimit")} + +
+
+
+
{t("attendance.unexcusedDays")}
+
+ {term.unexcused_days} + + / {term.limits.max_unexcused_days} + +
+
+
+
{t("attendance.excusedDays")}
+
+ {term.excused_days} + + / {term.limits.max_excused_days} + +
+
+
+
+ )} +
+
+
+
+

{t("attendance.courseBreakdown")}

diff --git a/src/components/courses/course-card.tsx b/src/components/courses/course-card.tsx index c5ff2a6..932f6a9 100644 --- a/src/components/courses/course-card.tsx +++ b/src/components/courses/course-card.tsx @@ -12,12 +12,12 @@ const courseInitials = (title: string) => export function CourseCard(props: { course: Course; - term: string; + /** The şubeler line under the title: "3 sections", or a dash. */ + sections: string; enrolled?: boolean; showTeacherActions?: boolean; labels: { - capacity: string; - unlimited: string; + taughtIn: string; enrolled: string; kind: string; weeklyHours: string; @@ -28,8 +28,9 @@ export function CourseCard(props: { analysis: string; }; }) { - const teachers = () => [props.course.creator, ...(props.course.teachers ?? [])] - .filter((person, index, all) => all.findIndex((row) => row.id === person.id) === index); + // Teaching staff is per instance now, so a catalog card can only name the + // course's owner — the şube pages name who actually teaches it. + const teachers = () => [props.course.creator]; return ( {props.course.description || "—"}

- {props.term} + {props.sections} {teachers().map(personLabel).join(", ")} @@ -65,8 +66,8 @@ export function CourseCard(props: {
- {props.labels.capacity}: - {props.course.capacity ?? props.labels.unlimited} + {props.labels.taughtIn}: + {props.course.class_course_count}
diff --git a/src/components/courses/course-teachers-panel.tsx b/src/components/courses/course-teachers-panel.tsx index 4a3e3d7..9987869 100644 --- a/src/components/courses/course-teachers-panel.tsx +++ b/src/components/courses/course-teachers-panel.tsx @@ -1,6 +1,6 @@ import { Show, createMemo, createSignal } from "solid-js"; import type { ColumnDef } from "@tanstack/solid-table"; -import { deleteCourseTeacherByUserId, postCourseTeacher } from "@/api/courses"; +import { deleteInstanceTeacherByUserId, postInstanceTeacher } from "@/api/instances"; import { formatApiError } from "@/api/client"; import type { PersonRef } from "@/api/client"; import { Alert } from "@/components/ui/alert"; @@ -14,13 +14,15 @@ import { UserSearchSelect } from "@/components/users/user-search-select"; import { createFlash } from "@/lib/flash"; import { useT } from "@/stores/preferences-context"; +// Staffing is per instance now: a teacher runs this course *in this şube*, and +// the assignment carries no rights over the catalog course itself. export function CourseTeachersPanel(props: { - courseId: string; + instanceId: string; teachers: PersonRef[]; canStaff: boolean; assignOpen: boolean; onAssignOpenChange: (open: boolean) => void; - onCourseUpdated: () => void; + onInstanceUpdated: () => void; }) { const t = useT(); const [selectedTeacherId, setSelectedTeacherId] = createSignal(""); @@ -70,11 +72,11 @@ export function CourseTeachersPanel(props: { setError(""); try { - await postCourseTeacher(props.courseId, teacherId); + await postInstanceTeacher(props.instanceId, teacherId); setFlash(t("courses.teacherAssigned")); setSelectedTeacherId(""); props.onAssignOpenChange(false); - props.onCourseUpdated(); + props.onInstanceUpdated(); } catch (err) { setError(formatApiError(err)); } finally { @@ -90,10 +92,10 @@ export function CourseTeachersPanel(props: { setError(""); try { - await deleteCourseTeacherByUserId(props.courseId, target.id); + await deleteInstanceTeacherByUserId(props.instanceId, target.id); setFlash(t("courses.teacherUnassigned")); setRemoveTarget(null); - props.onCourseUpdated(); + props.onInstanceUpdated(); } catch (err) { setError(formatApiError(err)); } finally { diff --git a/src/components/exams/exam-form.tsx b/src/components/exams/exam-form.tsx index 70b4629..60e8c0a 100644 --- a/src/components/exams/exam-form.tsx +++ b/src/components/exams/exam-form.tsx @@ -4,6 +4,7 @@ import { formatApiError } from "@/api/client"; import { For } from "solid-js"; import { getSettings } from "@/api/settings"; import { getTime } from "@/api/time"; +import { getTerms } from "@/api/terms"; import type { Exam } from "@/api/client"; import { EXAM_KINDS, EXAM_MODES } from "@/api/client"; import { Button } from "@/components/ui/button"; @@ -56,6 +57,8 @@ function scheduleInputToMs(date: string, time: string): number | null { export type ExamFormValues = { title: string; + /** The dönem the exam is filed in. Create-only — the backend cannot move it. */ + term: string; description: string; kind: string; mode: string | null; @@ -102,6 +105,16 @@ export function ExamForm(props: { const isEdit = () => !!props.initial?.id; const [settings] = createResource(() => getSettings()); const [serverTime] = createResource(() => getTime().catch(() => ({ now: Date.now() }))); + // Terms are only asked for while creating: the backend has no way to move a + // filed exam to another dönem, so an edit never shows the field. + const [terms] = createResource(() => (isEdit() ? null : true), async () => (await getTerms({ limit: 100 })).items); + const [term, setTerm] = createSignal(""); + createEffect(() => { + const list = terms(); + if (!list || list.length === 0 || term()) return; + // Newest first from the backend — the open dönem is what a teacher means. + setTerm((list.find((item) => item.archived_at == null) ?? list[0]).id); + }); const examKinds = createMemo(() => { const names = settings()?.exam_kinds.map((item) => item.name) ?? EXAM_KINDS; return names.includes(kind()) ? names : [kind(), ...names]; @@ -125,6 +138,7 @@ export function ExamForm(props: { if (ends <= starts) return t("form.timeOrder"); if (!isEdit() && (starts < (serverTime()?.now ?? Date.now()) || ends < (serverTime()?.now ?? Date.now()))) return t("form.timePast"); } + if (!isEdit() && !term()) return t("terms.term"); if (hasDuration() || mode() === "async") { if (duration == null) return t("exams.durationRequired"); if (duration < 60000 || duration > 86400000) return t("exams.durationRange"); @@ -182,6 +196,7 @@ export function ExamForm(props: { return; } const values = { + term: term(), title: title().trim(), description: description(), kind: kind(), @@ -229,6 +244,16 @@ export function ExamForm(props: { onInput={(e) => setDescription(e.currentTarget.value)} />
+ +
+ + +
+
props.onTermChange(event.currentTarget.value)} + > + {(term) => } + +
+
+
+

{t("karne.average")}

+

{formatAverage(props.report.year_average)}

+
+
+

{t("karne.verdict")}

+

{verdictLabel()}

+
+
+
+ + 0} + fallback={{t("karne.empty")}} + > +
+ + + + + + + + + + + + {(line) => ( + + + + + + + )} + + +
{t("nav.courses")}{t("instances.dersSaati")}{t("marks.courseAvg")}{t("karne.band")}
{line.course}{line.ders_saati}{formatAverage(line.average)} + + {(band) => {band()}} + +
+
+
+
+ ); +} diff --git a/src/components/marks/marks-report-view.tsx b/src/components/marks/marks-report-view.tsx index 65f667e..afaf761 100644 --- a/src/components/marks/marks-report-view.tsx +++ b/src/components/marks/marks-report-view.tsx @@ -11,7 +11,6 @@ import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { cn } from "@/lib/cn"; import { examKindLabel } from "@/lib/exam-labels"; import { examWeight } from "@/lib/exam-weight"; -import { personLabel } from "@/lib/person"; import { useT } from "@/stores/preferences-context"; const round = (n: number) => (Math.round(n * 100) / 100).toString(); @@ -32,11 +31,11 @@ export function MarksReportView(props: { report: MarksReport; compact?: boolean const compact = () => props.compact === true; const resultCount = createMemo(() => props.report.courses.reduce((total, course) => total + course.results.length, 0)); const [tab, setTab] = createSignal<"general" | "byCourse">("general"); - const [activeCourseId, setActiveCourseId] = createSignal(null); + const [activeInstanceId, setActiveInstanceId] = createSignal(null); const activeCourse = createMemo(() => { - const id = activeCourseId(); + const id = activeInstanceId(); const courses = props.report.courses; - return (id ? courses.find((c) => c.course.id === id) : undefined) ?? courses[0]; + return (id ? courses.find((c) => c.instance === id) : undefined) ?? courses[0]; }); const columns = createMemo[]>(() => [ { @@ -136,9 +135,9 @@ export function MarksReportView(props: { report: MarksReport; compact?: boolean - - {block.course.teachers && block.course.teachers.length > 0 ? block.course.teachers.map((tr) => personLabel(tr)).join(", ") : "—"} - + + {t("instances.open")} +
@@ -165,11 +164,11 @@ export function MarksReportView(props: { report: MarksReport; compact?: boolean type="button" class={cn( "rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors", - activeCourse()?.course.id === block.course.id + activeCourse()?.instance === block.instance ? "border-border bg-surface-base text-foreground shadow-xs" : "border-transparent text-muted-foreground hover:bg-muted/60", )} - onClick={() => setActiveCourseId(block.course.id)} + onClick={() => setActiveInstanceId(block.instance)} > {block.course.title} @@ -185,9 +184,9 @@ export function MarksReportView(props: { report: MarksReport; compact?: boolean {block.course.title} -

- {block.course.teachers && block.course.teachers.length > 0 ? block.course.teachers.map((tr) => personLabel(tr)).join(", ") : "—"} -

+ + {t("instances.open")} +

{t("marks.courseAvg")}

diff --git a/src/components/sessions/course-sessions-panel.tsx b/src/components/sessions/course-sessions-panel.tsx index 1806eef..25a5e2e 100644 --- a/src/components/sessions/course-sessions-panel.tsx +++ b/src/components/sessions/course-sessions-panel.tsx @@ -3,11 +3,10 @@ import { createResource } from "@/lib/create-resource"; import type { ColumnDef } from "@tanstack/solid-table"; import { deleteSessionById } from "@/api/sessions"; import { deleteSessionAttendanceByUserId } from "@/api/sessions"; -import { getCourseSessions } from "@/api/courses"; import { getSessionAttendance } from "@/api/sessions"; +import { getInstanceSessions, postInstanceSession } from "@/api/instances"; import { getTime } from "@/api/time"; import { patchSessionById } from "@/api/sessions"; -import { postCourseSession } from "@/api/courses"; import { postSessionAttendance } from "@/api/sessions"; import { formatApiError } from "@/api/client"; import type { AttendanceStatus, CourseSession, Enrollment, SessionAttendance } from "@/api/client"; @@ -62,7 +61,8 @@ function msToTimeInput(ms: number): string { const ROLL_CALL_PAGE_SIZE = 8; export function CourseSessionsPanel(props: { - courseId: string; + /** The instance (class x course) these lessons belong to. */ + instanceId: string; roster: Enrollment[]; canManage: boolean; active: boolean; @@ -73,8 +73,8 @@ export function CourseSessionsPanel(props: { const t = useT(); const { locale } = usePreferences(); const [sessions, { refetch }] = createResource( - () => (props.active ? props.courseId : null), - async (courseId) => (courseId ? (await getCourseSessions(courseId)).items : []), + () => (props.active ? props.instanceId : null), + async (instanceId) => (instanceId ? (await getInstanceSessions(instanceId)).items : []), ); const [selectedSession, setSelectedSession] = createSignal(null); const [detailSession, setDetailSession] = createSignal(null); @@ -162,7 +162,7 @@ export function CourseSessionsPanel(props: { }); setFlash(t("common.saved")); } else { - await postCourseSession(props.courseId, { + await postInstanceSession(props.instanceId, { starts_at, ...(topic().trim() ? { topic: topic().trim() } : {}), ...(ends_at != null ? { ends_at } : {}), @@ -245,7 +245,7 @@ export function CourseSessionsPanel(props: { columns={columns()} data={sessions() ?? []} filterColumn="topic" - storageKey={`course-sessions-${props.courseId}`} + storageKey={`instance-sessions-${props.instanceId}`} enablePagination pageSize={10} empty={t("sessions.empty")} diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index f610843..6da4ed1 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -1928,7 +1928,67 @@ export type MessageKey = | "appointments.rejectReasonPlaceholder" | "appointments.rejectReason" | "appointments.rejectedBy" - | "appointments.reasonRequired"; + | "appointments.reasonRequired" + | "nav.academicYears" + | "instances.title" + | "instances.item" + | "instances.taughtIn" + | "instances.empty" + | "instances.emptyHelp" + | "instances.dersSaati" + | "instances.countsTowardKarne" + | "instances.policy" + | "instances.notFound" + | "instances.open" + | "instances.mine" + | "instances.selectSection" + | "instances.selectSectionHelp" + | "academicYears.title" + | "academicYears.subtitle" + | "academicYears.new" + | "academicYears.year" + | "academicYears.empty" + | "academicYears.unassigned" + | "academicYears.classCount" + | "academicYears.termCount" + | "academicYears.archive" + | "academicYears.archiveConfirm" + | "academicYears.archived" + | "academicYears.deleteConfirm" + | "academicYears.promotions" + | "academicYears.promotionsHelp" + | "academicYears.fromGrade" + | "academicYears.toGrade" + | "academicYears.addPromotion" + | "academicYears.rollover" + | "academicYears.rolloverFrom" + | "academicYears.rolloverHelp" + | "academicYears.rolloverDone" + | "academicYears.graduated" + | "karne.title" + | "karne.average" + | "karne.verdict" + | "karne.passed" + | "karne.failed" + | "karne.empty" + | "karne.band" + | "courses.members" + | "courses.memberItem" + | "courses.addMember" + | "courses.removeMember" + | "courses.removeMemberConfirm" + | "courses.membersClubOnly" + | "settings.branches" + | "settings.excuseKinds" + | "settings.maxExcusedDays" + | "settings.maxUnexcusedDays" + | "settings.timezone" + | "attendance.devamsizlik" + | "attendance.excusedDays" + | "attendance.unexcusedDays" + | "attendance.overLimit" + | "common.yes" + | "common.no"; type Dict = Record; @@ -3873,6 +3933,66 @@ const en: Dict = { "messages.deleteForeverOnlyTrash": "Permanent delete only applies to messages in the trash.", "messages.readOnlyReceived": "Only received messages can be marked read or unread.", "messages.trashEmptiedToast": "Trash emptied.", + "nav.academicYears": "Academic years", + "instances.title": "Sections", + "instances.item": "section", + "instances.taughtIn": "Taught in", + "instances.empty": "No section teaches this course yet.", + "instances.emptyHelp": "A course starts teaching when a class attaches it.", + "instances.dersSaati": "Weekly hours", + "instances.countsTowardKarne": "Counts toward karne", + "instances.policy": "Section policy", + "instances.notFound": "Section not found.", + "instances.open": "Open section", + "instances.mine": "My sections", + "instances.selectSection": "Select a section", + "instances.selectSectionHelp": "Exams, homework and lessons belong to a section, not to the catalog course.", + "academicYears.title": "Academic years", + "academicYears.subtitle": "The calendar structure terms and classes hang off.", + "academicYears.new": "New academic year", + "academicYears.year": "Academic year", + "academicYears.empty": "No academic year yet.", + "academicYears.unassigned": "Unassigned", + "academicYears.classCount": "Classes", + "academicYears.termCount": "Terms", + "academicYears.archive": "Archive year", + "academicYears.archiveConfirm": "An archived year takes no new class, term or exam, and cannot be edited. There is no undo.", + "academicYears.archived": "Archived", + "academicYears.deleteConfirm": "Delete this academic year?", + "academicYears.promotions": "Grade promotions", + "academicYears.promotionsHelp": "Each pair maps a grade to the one its students move to at rollover. A grade left out graduates.", + "academicYears.fromGrade": "From grade", + "academicYears.toGrade": "To grade", + "academicYears.addPromotion": "Add pair", + "academicYears.rollover": "Carry classes over", + "academicYears.rolloverFrom": "Carry from", + "academicYears.rolloverHelp": "Plants the source year's classes here with promoted grades, their sections and their students. The target must still be empty.", + "academicYears.rolloverDone": "{classes} classes and {students} students carried over.", + "academicYears.graduated": "Graduated grades", + "karne.title": "Karne", + "karne.average": "Year average", + "karne.verdict": "Verdict", + "karne.passed": "Passed", + "karne.failed": "Failed", + "karne.empty": "No karne line for this term yet.", + "karne.band": "Band", + "courses.members": "Members", + "courses.memberItem": "member", + "courses.addMember": "Add member", + "courses.removeMember": "Remove member", + "courses.removeMemberConfirm": "Remove this member?", + "courses.membersClubOnly": "Only a club or study group keeps its own member list.", + "settings.branches": "Teaching subjects (branş)", + "settings.excuseKinds": "Excuse kinds", + "settings.maxExcusedDays": "Excused absence day limit", + "settings.maxUnexcusedDays": "Unexcused absence day limit", + "settings.timezone": "Timezone", + "attendance.devamsizlik": "Absence by term", + "attendance.excusedDays": "Excused days", + "attendance.unexcusedDays": "Unexcused days", + "attendance.overLimit": "Over the limit", + "common.yes": "Yes", + "common.no": "No", }; const tr: Dict = { @@ -5816,6 +5936,66 @@ const tr: Dict = { "messages.deleteForeverOnlyTrash": "Kalıcı silme yalnızca çöp kutusundaki mesajlar için geçerli.", "messages.readOnlyReceived": "Yalnızca gelen mesajların okundu durumu değiştirilebilir.", "messages.trashEmptiedToast": "Çöp kutusu boşaltıldı.", + "nav.academicYears": "Eğitim yılları", + "instances.title": "Şubeler", + "instances.item": "şube", + "instances.taughtIn": "İşlendiği şubeler", + "instances.empty": "Bu dersi işleyen şube yok.", + "instances.emptyHelp": "Ders, bir şube onu eklediğinde işlenmeye başlar.", + "instances.dersSaati": "Ders saati", + "instances.countsTowardKarne": "Karneye işler", + "instances.policy": "Şube ayarı", + "instances.notFound": "Şube bulunamadı.", + "instances.open": "Şubeyi aç", + "instances.mine": "Şubelerim", + "instances.selectSection": "Şube seç", + "instances.selectSectionHelp": "Sınav, ödev ve dersler katalog dersine değil şubeye bağlıdır.", + "academicYears.title": "Eğitim yılları", + "academicYears.subtitle": "Dönemlerin ve şubelerin bağlı olduğu takvim yapısı.", + "academicYears.new": "Yeni eğitim yılı", + "academicYears.year": "Eğitim yılı", + "academicYears.empty": "Henüz eğitim yılı yok.", + "academicYears.unassigned": "Atanmamış", + "academicYears.classCount": "Şube", + "academicYears.termCount": "Dönem", + "academicYears.archive": "Yılı arşivle", + "academicYears.archiveConfirm": "Arşivlenen yıl yeni şube, dönem veya sınav almaz ve düzenlenemez. Geri alınamaz.", + "academicYears.archived": "Arşivlendi", + "academicYears.deleteConfirm": "Bu eğitim yılı silinsin mi?", + "academicYears.promotions": "Sınıf geçme", + "academicYears.promotionsHelp": "Her satır bir sınıfın, devir sırasında geçeceği sınıfı belirler. Listede olmayan sınıf mezun olur.", + "academicYears.fromGrade": "Sınıftan", + "academicYears.toGrade": "Sınıfa", + "academicYears.addPromotion": "Satır ekle", + "academicYears.rollover": "Şubeleri devret", + "academicYears.rolloverFrom": "Kaynak yıl", + "academicYears.rolloverHelp": "Kaynak yılın şubelerini, sınıfları yükseltilmiş hâlde, şubeleri ve öğrencileriyle buraya taşır. Hedef yıl boş olmalı.", + "academicYears.rolloverDone": "{classes} şube ve {students} öğrenci devredildi.", + "academicYears.graduated": "Mezun olan sınıflar", + "karne.title": "Karne", + "karne.average": "Yıl ortalaması", + "karne.verdict": "Sonuç", + "karne.passed": "Geçti", + "karne.failed": "Kaldı", + "karne.empty": "Bu döneme ait karne satırı yok.", + "karne.band": "Not aralığı", + "courses.members": "Üyeler", + "courses.memberItem": "üye", + "courses.addMember": "Üye ekle", + "courses.removeMember": "Üyeyi çıkar", + "courses.removeMemberConfirm": "Bu üye çıkarılsın mı?", + "courses.membersClubOnly": "Yalnızca kulüp ve etütlerin kendi üye listesi olur.", + "settings.branches": "Branşlar", + "settings.excuseKinds": "Mazeret türleri", + "settings.maxExcusedDays": "Mazeretli devamsızlık gün sınırı", + "settings.maxUnexcusedDays": "Mazeretsiz devamsızlık gün sınırı", + "settings.timezone": "Saat dilimi", + "attendance.devamsizlik": "Dönemlik devamsızlık", + "attendance.excusedDays": "Mazeretli gün", + "attendance.unexcusedDays": "Mazeretsiz gün", + "attendance.overLimit": "Sınır aşıldı", + "common.yes": "Evet", + "common.no": "Hayır", }; export const messages: Record = { en, tr }; diff --git a/src/lib/instance-options.ts b/src/lib/instance-options.ts new file mode 100644 index 0000000..a3f3ad0 --- /dev/null +++ b/src/lib/instance-options.ts @@ -0,0 +1,74 @@ +import { getClasses, getClassInstances, getMyClasses } from "@/api/classes"; +import { getCourseById } from "@/api/courses"; +import { getMyInstances } from "@/api/instances"; +import type { ClassGroup, Role } from "@/api/client"; +import { hasMinRole } from "@/lib/roles"; + +/** One pickable section: " — <şube>", plus the ids behind the label. */ +export type InstanceOption = { + id: string; + /** The catalog course it teaches — what subjects and question banks key on. */ + course: string; + class: string; + label: string; +}; + +/** + * The sections a user may act in, labelled for a picker. + * + * There is no course-scoped instance route, so the office walks the class list + * (one read per class) while everyone else reads the single `/instances/me` + * that already answers "which sections are mine". + */ +export async function loadInstanceOptions(role: Role | undefined): Promise { + if (!role) return []; + const office = hasMinRole(role, "manager"); + + const rows: { id: string; course: string; class: string }[] = []; + const classNames = new Map(); + + if (office) { + const classes = (await getClasses({ limit: 200 })).items; + const perClass = await Promise.all( + classes.map(async (klass) => { + classNames.set(klass.id, klass.name); + try { + return (await getClassInstances(klass.id, { limit: 200 })).items; + } catch { + // One unreadable şube must not empty the whole picker. + return []; + } + }), + ); + for (const instance of perClass.flat()) { + rows.push({ id: instance.id, course: instance.course, class: instance.class }); + } + } else { + const [mine, classes] = await Promise.all([ + getMyInstances({ limit: 200 }), + (hasMinRole(role, "teacher") ? getClasses({ limit: 200 }) : getMyClasses({ limit: 200 })).catch( + () => ({ items: [] as ClassGroup[] }), + ), + ]); + for (const klass of classes.items) classNames.set(klass.id, klass.name); + for (const instance of mine.items) { + rows.push({ id: instance.id, course: instance.course, class: instance.class }); + } + } + + const titles = new Map(); + await Promise.all( + [...new Set(rows.map((row) => row.course))].map(async (courseId) => { + try { + titles.set(courseId, (await getCourseById(courseId)).title); + } catch { + // Falls back to the id in the label below. + } + }), + ); + + return rows.map((row) => ({ + ...row, + label: `${titles.get(row.course) ?? row.course} — ${classNames.get(row.class) ?? "—"}`, + })); +} diff --git a/src/lib/meals.test.ts b/src/lib/meals.test.ts index 2425e2a..8463a4f 100644 --- a/src/lib/meals.test.ts +++ b/src/lib/meals.test.ts @@ -18,19 +18,31 @@ describe("meal helpers", () => { .toBe(Date.parse("2026-07-28T10:00:00Z")); }); - it("selects nearest course work", () => { + it("selects nearest course work for one instance", () => { expect(nextCourseWork( - "c1", - [{ course: "c1", title: "Exam", starts_at: 30 } as never], - [{ course: "c1", title: "Homework", due_at: 20 } as never], + "i1", + [{ class_course: "i1", title: "Exam", starts_at: 30 } as never], + [{ class_course: "i1", title: "Homework", due_at: 20 } as never], )?.title).toBe("Homework"); }); + // Two şubeler teaching the same course are two instances; work filed against + // the other one must not surface here. + it("ignores work filed against another instance", () => { + expect(nextCourseWork( + "i1", + [{ class_course: "i2", title: "Exam", starts_at: 30 } as never], + [{ class_course: "i2", title: "Homework", due_at: 20 } as never], + )).toBeNull(); + }); + it("builds a field-only settings patch", () => { const before = { exam_kinds: [], attendance_statuses: [], grade_bands: [], max_file_bytes: 1, chatbot_history_turns: 1, max_chatbot_threads: 1, max_chatbot_message_len: 100, meal_slots: [], dietary_tags: [], meal_cancel_cutoff_minutes: null, + branches: [], excuse_kinds: [], max_excused_absent_days: null, + max_unexcused_absent_days: null, timezone: null, } satisfies SchoolSettings; expect(dirtySettingsPatch(before, { ...before, max_chatbot_threads: 2 })).toEqual({ max_chatbot_threads: 2 }); }); diff --git a/src/lib/meals.ts b/src/lib/meals.ts index 551472f..6c3a907 100644 --- a/src/lib/meals.ts +++ b/src/lib/meals.ts @@ -21,10 +21,10 @@ export function mealCutoffAt(date: string, slot: MealSlot | undefined, minutes: return Date.parse(`${date}T00:00:00Z`) + servingMinute * 60_000 - minutes * 60_000; } -export function nextCourseWork(courseId: string, exams: Exam[], homework: Homework[]) { +export function nextCourseWork(instanceId: string, exams: Exam[], homework: Homework[]) { return [ - ...exams.filter((item) => item.course === courseId).map((item) => ({ kind: "exam" as const, title: item.title, at: item.starts_at ?? item.ends_at })), - ...homework.filter((item) => item.course === courseId).map((item) => ({ kind: "homework" as const, title: item.title, at: item.due_at })), + ...exams.filter((item) => item.class_course === instanceId).map((item) => ({ kind: "exam" as const, title: item.title, at: item.starts_at ?? item.ends_at })), + ...homework.filter((item) => item.class_course === instanceId).map((item) => ({ kind: "homework" as const, title: item.title, at: item.due_at })), ] .filter((item): item is { kind: "exam" | "homework"; title: string; at: number } => item.at != null) .sort((a, b) => a.at - b.at)[0] ?? null; @@ -43,6 +43,11 @@ export function dirtySettingsPatch(before: SchoolSettings, after: SchoolSettings "meal_slots", "dietary_tags", "meal_cancel_cutoff_minutes", + "excuse_kinds", + "branches", + "max_excused_absent_days", + "max_unexcused_absent_days", + "timezone", ] as const) { if (JSON.stringify(before[key]) !== JSON.stringify(after[key])) patch[key] = after[key] as never; } diff --git a/src/pages/academic-years-page.tsx b/src/pages/academic-years-page.tsx new file mode 100644 index 0000000..c7b75f3 --- /dev/null +++ b/src/pages/academic-years-page.tsx @@ -0,0 +1,450 @@ +import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; +import { createResource } from "@/lib/create-resource"; +import type { ColumnDef } from "@tanstack/solid-table"; +import { + deleteAcademicYearById, + getAcademicYears, + patchAcademicYearById, + postAcademicYear, + postAcademicYearArchive, + postAcademicYearRollover, +} from "@/api/academic-years"; +import { formatApiError } from "@/api/client"; +import type { AcademicYear, GradePromotion } from "@/api/client"; +import { RouteGuard } from "@/components/layout/route-guard"; +import { Alert } from "@/components/ui/alert"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; +import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; +import { DatePicker } from "@/components/ui/date-picker"; +import { ErrorAlert } from "@/components/ui/error-alert"; +import { IconArchive, IconEdit, IconPlus, IconRotateCcw, IconTrash } from "@/components/ui/icons"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { PageHeader } from "@/components/layout/page-header"; +import { Select } from "@/components/ui/select"; +import { SidePanel } from "@/components/ui/side-panel"; +import { TableRowActions } from "@/components/ui/table-row-actions"; +import { createFlash } from "@/lib/flash"; +import { formatDateTime } from "@/lib/format"; +import { usePreferences, useT } from "@/stores/preferences-context"; + +const YEAR_PAGE_SIZE = 10; + +function dateInputFromMs(ms: number): string { + const date = new Date(ms); + const pad = (n: number) => String(n).padStart(2, "0"); + return `${pad(date.getDate())}/${pad(date.getMonth() + 1)}/${date.getFullYear()}`; +} + +function dateInputToMs(value: string): number | null { + const match = value.trim().match(/^(\d{2})\/(\d{2})\/(\d{4})$/); + if (!match) return null; + const [, dayRaw, monthRaw, yearRaw] = match; + const day = Number(dayRaw); + const month = Number(monthRaw); + const year = Number(yearRaw); + const date = new Date(year, month - 1, day, 0, 0, 0, 0); + if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) return null; + return date.getTime(); +} + +export default function AcademicYearsPage() { + return ( + + + + ); +} + +function AcademicYearsContent() { + const t = useT(); + const { locale } = usePreferences(); + const [list, { refetch }] = createResource(async () => (await getAcademicYears({ limit: 100 })).items); + const years = () => list() ?? []; + const openYears = createMemo(() => years().filter((year) => year.archived_at == null)); + + const [panelOpen, setPanelOpen] = createSignal(false); + const [name, setName] = createSignal(""); + const [starts, setStarts] = createSignal(""); + const [ends, setEnds] = createSignal(""); + const [promotions, setPromotions] = createSignal([]); + const [editing, setEditing] = createSignal(null); + const [deleteTarget, setDeleteTarget] = createSignal(null); + const [archiveTarget, setArchiveTarget] = createSignal(null); + const [rolloverTarget, setRolloverTarget] = createSignal(null); + const [rolloverFrom, setRolloverFrom] = createSignal(""); + const [error, setError] = createSignal(""); + const [flash, setFlash] = createFlash(); + const [pending, setPending] = createSignal(false); + + const resetForm = () => { + setName(""); + setStarts(""); + setEnds(""); + setPromotions([]); + setEditing(null); + setError(""); + }; + + const openCreate = () => { + resetForm(); + setPanelOpen(true); + }; + + const startEdit = (year: AcademicYear) => { + setEditing(year); + setName(year.name); + setStarts(dateInputFromMs(year.starts_at)); + setEnds(dateInputFromMs(year.ends_at)); + setPromotions(year.grade_promotions.map((pair) => ({ ...pair }))); + setError(""); + setPanelOpen(true); + }; + + const save = async (event: SubmitEvent) => { + event.preventDefault(); + setError(""); + const starts_at = dateInputToMs(starts()); + const ends_at = dateInputToMs(ends()); + if (starts_at == null || ends_at == null) { + setError(t("form.datePlaceholder")); + return; + } + if (ends_at < starts_at) { + setError(t("form.timeOrder")); + return; + } + // 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); + + setPending(true); + try { + const current = editing(); + if (current) { + await patchAcademicYearById(current.id, { name: name().trim(), starts_at, ends_at, grade_promotions }); + setFlash(t("common.saved")); + } else { + await postAcademicYear({ name: name().trim(), starts_at, ends_at, grade_promotions }); + setFlash(t("common.created")); + } + resetForm(); + setPanelOpen(false); + await refetch(); + } catch (err) { + setError(formatApiError(err)); + } finally { + setPending(false); + } + }; + + const columns = createMemo[]>(() => [ + { + accessorKey: "name", + header: t("settings.name"), + cell: (cell) => ( + + {cell.row.original.name} + + {t("academicYears.archived")} + + + ), + }, + { + accessorKey: "starts_at", + header: t("events.starts"), + cell: (cell) => {formatDateTime(cell.row.original.starts_at, locale())}, + }, + { + accessorKey: "ends_at", + header: t("events.ends"), + cell: (cell) => {formatDateTime(cell.row.original.ends_at, locale())}, + }, + { + id: "classes", + accessorFn: (row) => row.class_count, + header: t("academicYears.classCount"), + meta: { cellClass: "mono" }, + }, + { + id: "terms", + accessorFn: (row) => row.term_count, + header: t("academicYears.termCount"), + meta: { cellClass: "mono" }, + }, + { + id: "actions", + header: t("common.actions"), + meta: { headerClass: "w-14 text-center", cellClass: "px-1 text-center" }, + cell: (cell) => { + const year = cell.row.original; + const archived = year.archived_at != null; + return ( + , onSelect: () => startEdit(year) }, + { + label: t("academicYears.rollover"), + icon: , + onSelect: () => { + setRolloverFrom(""); + setRolloverTarget(year); + }, + }, + { + label: t("academicYears.archive"), + icon: , + onSelect: () => setArchiveTarget(year), + }, + ]), + { + label: t("common.delete"), + icon: , + destructive: true, + onSelect: () => setDeleteTarget(year), + }, + ]} + /> + ); + }, + }, + ]); + + return ( +
+ + + + {flash()} + + + {error()} + + +
+ }> + + void refetch()} /> + + + + {t("academicYears.new")} + + } + columns={columns()} + data={years()} + tableClass="min-w-160" + filterColumn="name" + enablePagination + pageSize={YEAR_PAGE_SIZE} + empty={t("academicYears.empty")} + /> + +
+ + { + setPanelOpen(open); + if (!open) resetForm(); + }} + title={editing() ? t("common.edit") : t("academicYears.new")} + description={t("academicYears.subtitle")} + > +
+ + {error()} + +
+ + setName(e.currentTarget.value)} /> +
+
+ + +
+
+ + +
+ +
+
+
+

{t("academicYears.promotions")}

+

{t("academicYears.promotionsHelp")}

+
+ +
+ + {(pair, index) => ( +
+ + setPromotions((rows) => rows.map((row, i) => (i === index() ? { ...row, from_grade: e.currentTarget.value } : row))) + } + /> + + setPromotions((rows) => rows.map((row, i) => (i === index() ? { ...row, to_grade: e.currentTarget.value } : row))) + } + /> + +
+ )} +
+
+ +
+ + +
+
+
+ + !open && setRolloverTarget(null)} + title={t("academicYears.rollover")} + description={rolloverTarget()?.name ?? ""} + > +
{ + event.preventDefault(); + const target = rolloverTarget(); + const from = rolloverFrom(); + if (!target || !from) return; + void (async () => { + setPending(true); + setError(""); + try { + const result = await postAcademicYearRollover(target.id, from); + setFlash(t("academicYears.rolloverDone", { classes: result.classes, students: result.students })); + setRolloverTarget(null); + await refetch(); + } catch (err) { + setError(formatApiError(err)); + } finally { + setPending(false); + } + })(); + }} + > + + {error()} + +

{t("academicYears.rolloverHelp")}

+
+ + +
+
+ + +
+
+
+ + !open && setArchiveTarget(null)} + title={t("academicYears.archive")} + variant="destructive" + summary={`${archiveTarget()?.name ?? ""} — ${t("academicYears.archiveConfirm")}`} + onConfirm={async () => { + const year = archiveTarget(); + if (!year) return; + try { + await postAcademicYearArchive(year.id); + setFlash(t("academicYears.archived")); + await refetch(); + } catch (err) { + setError(formatApiError(err)); + } finally { + setArchiveTarget(null); + } + }} + /> + + !open && setDeleteTarget(null)} + title={t("confirm.deleteTitle")} + variant="destructive" + summary={`${deleteTarget()?.name ?? ""} — ${t("academicYears.deleteConfirm")}`} + onConfirm={async () => { + const year = deleteTarget(); + if (!year) return; + try { + await deleteAcademicYearById(year.id); + setFlash(t("common.deleted")); + await refetch(); + } catch (err) { + setError(formatApiError(err)); + } finally { + setDeleteTarget(null); + } + }} + /> + + 0}> + {t("academicYears.empty")} + +
+ ); +} diff --git a/src/pages/bank-question-detail-page.tsx b/src/pages/bank-question-detail-page.tsx index 2fac84b..4dcedf7 100644 --- a/src/pages/bank-question-detail-page.tsx +++ b/src/pages/bank-question-detail-page.tsx @@ -52,7 +52,6 @@ function BankQuestionDetailContent() { const current = auth.user(); return !!current && ( course.creator.id === current.id || - (course.teachers ?? []).some((teacher) => teacher.id === current.id) || hasMinRole(current.role, "manager") ); }), diff --git a/src/pages/calendar-page.tsx b/src/pages/calendar-page.tsx index 67c4ded..e126cec 100644 --- a/src/pages/calendar-page.tsx +++ b/src/pages/calendar-page.tsx @@ -4,7 +4,8 @@ import { getEvents } from "@/api/events"; import { getExams } from "@/api/exams"; import { getHomework } from "@/api/homework"; import { getAppointments } from "@/api/appointments"; -import { getCourseSessions, getCourses } from "@/api/courses"; +import { getCourses } from "@/api/courses"; +import { getInstanceSessions, getMyInstances } from "@/api/instances"; import { getMyCourses } from "@/api/reports"; import type { Appointment, AppointmentStatus, Course } from "@/api/client"; import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status"; @@ -158,16 +159,22 @@ function CalendarContent() { const [sessions] = createResource( () => auth.user()?.role ?? null, async (role) => { - const courses: Course[] = role === "student" - ? (await getMyCourses()).items - : (await getCourses()).items; + // Sessions hang off the instance (şube × ders) now; the catalog course is + // still what says whether a meeting is a ders, an etüt or a kulüp. + const [instances, courses] = await Promise.all([ + getMyInstances({ limit: 200 }), + role === "student" ? getMyCourses() : getCourses(), + ]); + const byId = new Map(courses.items.map((course) => [course.id, course])); const pages = await Promise.all( - courses.slice(0, SESSION_COURSE_CAP).map(async (course) => { + instances.items.slice(0, SESSION_COURSE_CAP).map(async (instance) => { + const course = byId.get(instance.course); + if (!course) return []; try { - const page = await getCourseSessions(course.id, { limit: 100 }); + const page = await getInstanceSessions(instance.id, { limit: 100 }); return page.items.map((session) => ({ session, course })); } catch { - // One unreadable course must not empty the whole calendar. + // One unreadable section must not empty the whole calendar. return []; } }), diff --git a/src/pages/class-detail-page.tsx b/src/pages/class-detail-page.tsx index 7736d97..5f89b96 100644 --- a/src/pages/class-detail-page.tsx +++ b/src/pages/class-detail-page.tsx @@ -9,13 +9,13 @@ import { getClassMembers, postClassMember, deleteClassMember, - getClassCourses, - postClassCourse, - deleteClassCourse, + getClassInstances, + postClassInstance, + deleteClassInstance, postClassBlueprintApply, } from "@/api/classes"; import { getCourses } from "@/api/courses"; -import { getTerms } from "@/api/terms"; +import { getAcademicYears } from "@/api/academic-years"; import { getLimits } from "@/api/limits"; import { ApiError, formatApiError, type BlueprintSkip, type ClassCourse, type ClassGroup, type ClassMember } from "@/api/client"; import { BlueprintSkippedReport } from "@/components/classes/blueprint-skipped-report"; @@ -61,7 +61,7 @@ function ClassDetailContent() { const [editing, setEditing] = createSignal(false); const [name, setName] = createSignal(""); const [grade, setGrade] = createSignal(""); - const [termId, setTermId] = createSignal(""); + const [yearId, setYearId] = createSignal(""); const [teacherId, setTeacherId] = createSignal(""); const [deleteOpen, setDeleteOpen] = createSignal(false); const [showAddMember, setShowAddMember] = createSignal(false); @@ -74,11 +74,11 @@ function ClassDetailContent() { const [reportOpen, setReportOpen] = createSignal(false); const [cls, { refetch: refetchClass }] = createResource(id, (classId) => getClassById(classId)); - const [terms] = createResource(async () => (await getTerms({ limit: 100 })).items); + const [years] = createResource(async () => (await getAcademicYears({ limit: 100 })).items); const [limits] = createResource(() => canManage() ? getLimits() : null); const [courses] = createResource(() => canManage() ? getCourses().then((page) => page.items) : null); const [members, { refetch: refetchMembers }] = createResource(id, async (classId) => (await getClassMembers(classId, { limit: 200 })).items); - const [classCourses, { refetch: refetchCourses }] = createResource(id, async (classId) => (await getClassCourses(classId, { limit: 50 })).items); + const [classCourses, { refetch: refetchCourses }] = createResource(id, async (classId) => (await getClassInstances(classId, { limit: 50 })).items); // The last class the page actually loaded. A refetch that fails leaves the // resource in an error state, and reading it there throws; holding the last @@ -89,7 +89,7 @@ function ClassDetailContent() { if (cls.state === "ready") setLoadedClass(cls()); }); - const termName = (tid: string | null) => terms.latest?.find((term) => term.id === tid)?.name ?? (tid || t("terms.unassigned")); + const yearName = (yid: string | null) => years.latest?.find((year) => year.id === yid)?.name ?? (yid || t("academicYears.unassigned")); const courseTitle = (courseId: string) => courses.latest?.find((course) => course.id === courseId)?.title ?? courseId; const memberUserIds = () => (members.latest ?? []).map((row) => row.user.id); const attachedCourseIds = () => (classCourses.latest ?? []).map((row) => row.course); @@ -184,6 +184,18 @@ function ClassDetailContent() { header: t("classGroups.courseColumn"), meta: { cellClass: "font-medium" }, }, + { + id: "dersSaati", + accessorFn: (row) => row.ders_saati, + header: t("instances.dersSaati"), + meta: { cellClass: "mono" }, + }, + { + id: "roster", + accessorFn: (row) => row.enrollment_count, + header: t("courses.roster"), + meta: { cellClass: "mono" }, + }, { id: "attachedBy", accessorFn: (row) => personLabel(row.attached_by), @@ -198,7 +210,10 @@ function ClassDetailContent() { , destructive: true, onSelect: () => setDetachCourse(cell.row.original) }]} + actions={[ + { label: t("instances.open"), icon: , onSelect: () => void navigate({ to: "/instances/$id", params: { id: cell.row.original.id } }) }, + { label: t("classGroups.detachCourse"), icon: , destructive: true, onSelect: () => setDetachCourse(cell.row.original) }, + ]} /> ), @@ -228,7 +243,7 @@ function ClassDetailContent() {

{c().name}

{c().grade} - {termName(c().term)} + {yearName(c().year)} · {t("classGroups.homeroomTeacher")}: {c().teacher ? personLabel(c().teacher!) : t("classGroups.noTeacher")}
@@ -245,7 +260,7 @@ function ClassDetailContent() { > {t("classBlueprints.apply")} - +
@@ -299,11 +314,11 @@ function ClassDetailContent() { {/* Edit class */} -
{ e.preventDefault(); void wrap(async () => { await patchClassById(id(), { name: name().trim(), grade: grade().trim() || null, term_id: termId() || null, teacher_id: teacherId() || null }); setEditing(false); await refresh(refetchClass); }, "common.saved"); }}> + { e.preventDefault(); void wrap(async () => { await patchClassById(id(), { name: name().trim(), grade: grade().trim() || null, year: yearId() || null, teacher_id: teacherId() || null }); setEditing(false); await refresh(refetchClass); }, "common.saved"); }}>
setName(e.currentTarget.value)} />
setGrade(e.currentTarget.value)} />
-
+
@@ -320,7 +335,7 @@ function ClassDetailContent() { {/* Attach course */} - { e.preventDefault(); const cid = attachCourseId(); if (!cid) return; void wrap(async () => { await postClassCourse(id(), { course_id: cid }); setAttachCourseId(""); setShowAttachCourse(false); await refresh(refetchCourses); }, "common.saved"); }}> + { e.preventDefault(); const cid = attachCourseId(); if (!cid) return; void wrap(async () => { await postClassInstance(id(), { course_id: cid }); setAttachCourseId(""); setShowAttachCourse(false); await refresh(refetchCourses); }, "common.saved"); }}>
setName(e.currentTarget.value)} />
setGrade(e.currentTarget.value)} />
-
+
{error()} @@ -195,7 +195,7 @@ function ClassesContent() { {(cls) => ( void navigate({ to: "/management/classes/$id", params: { id: cls.id } })} /> @@ -215,7 +215,7 @@ function ClassesContent() { ); } -function ClassCard(props: { cls: ClassGroup; termName: string; memberCount: number | null; onClick: () => void }) { +function ClassCard(props: { cls: ClassGroup; yearName: string; memberCount: number | null; onClick: () => void }) { const t = useT(); return (