forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB078b459Burak Boduroğlu2 months ago671 commits

instance-options.ts74 lines, 2.5 KiBHistoryRawDownload
1import { getClasses, getClassInstances, getMyClasses } from "@/api/classes";
2import { getCourseById } from "@/api/courses";
3import { getMyInstances } from "@/api/instances";
4import type { ClassGroup, Role } from "@/api/client";
5import { hasMinRole } from "@/lib/roles";
6
7/** One pickable section: "<ders> — <şube>", plus the ids behind the label. */
8export type InstanceOption = {
9 id: string;
10 /** The catalog course it teaches — what subjects and question banks key on. */
11 course: string;
12 class: string;
13 label: string;
14};
15
16/**
17 * The sections a user may act in, labelled for a picker.
18 *
19 * There is no course-scoped instance route, so the office walks the class list
20 * (one read per class) while everyone else reads the single `/instances/me`
21 * that already answers "which sections are mine".
22 */
23export async function loadInstanceOptions(role: Role | undefined): Promise<InstanceOption[]> {
24 if (!role) return [];
25 const office = hasMinRole(role, "manager");
26
27 const rows: { id: string; course: string; class: string }[] = [];
28 const classNames = new Map<string, string>();
29
30 if (office) {
31 const classes = (await getClasses({ limit: 200 })).items;
32 const perClass = await Promise.all(
33 classes.map(async (klass) => {
34 classNames.set(klass.id, klass.name);
35 try {
36 return (await getClassInstances(klass.id, { limit: 200 })).items;
37 } catch {
38 // One unreadable şube must not empty the whole picker.
39 return [];
40 }
41 }),
42 );
43 for (const instance of perClass.flat()) {
44 rows.push({ id: instance.id, course: instance.course, class: instance.class });
45 }
46 } else {
47 const [mine, classes] = await Promise.all([
48 getMyInstances({ limit: 200 }),
49 (hasMinRole(role, "teacher") ? getClasses({ limit: 200 }) : getMyClasses({ limit: 200 })).catch(
50 () => ({ items: [] as ClassGroup[] }),
51 ),
52 ]);
53 for (const klass of classes.items) classNames.set(klass.id, klass.name);
54 for (const instance of mine.items) {
55 rows.push({ id: instance.id, course: instance.course, class: instance.class });
56 }
57 }
58
59 const titles = new Map<string, string>();
60 await Promise.all(
61 [...new Set(rows.map((row) => row.course))].map(async (courseId) => {
62 try {
63 titles.set(courseId, (await getCourseById(courseId)).title);
64 } catch {
65 // Falls back to the id in the label below.
66 }
67 }),
68 );
69
70 return rows.map((row) => ({
71 ...row,
72 label: `${titles.get(row.course) ?? row.course} — ${classNames.get(row.class) ?? "—"}`,
73 }));
74}