forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

student-directory.ts118 lines, 5.1 KiBHistoryRawDownload
1import { getClassMembers } from "@/api/classes";
2import { getUserSearch } from "@/api/users";
3import type { ClassGroup, ClassMember, PersonRef } from "@/api/client";
4import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent";
5import { classList } from "@/lib/instance-labels";
6
7export type StudentDirectoryRow = {
8 person: PersonRef;
9 classes: ClassGroup[];
10};
11
12/** Page size for the class-roster reads; the same one the full sweep asks for. */
13const MEMBERS_PAGE = 500;
14const FRESH_MS = 5 * 60 * 1000;
15const memberCache = new Map<string, { until: number; value: Promise<ClassMember[]> }>();
16const countCache = new Map<string, { until: number; value: Promise<number> }>();
17let studentsCache: { until: number; value: Promise<PersonRef[]> } | null = null;
18
19export function invalidateStudentDirectory(): void {
20 memberCache.clear();
21 countCache.clear();
22 studentsCache = null;
23}
24
25/** Every live member of one class: the route is paged, so follow offsets to `total`. */
26async function fetchClassMembers(classId: string): Promise<ClassMember[]> {
27 const members: ClassMember[] = [];
28 let offset = 0;
29 for (;;) {
30 const page = await getClassMembers(classId, { limit: MEMBERS_PAGE, offset });
31 members.push(...page.items);
32 offset += page.items.length;
33 if (page.items.length === 0 || offset >= page.total) return members;
34 }
35}
36
37export function readClassMembers(classId: string): Promise<ClassMember[]> {
38 const hit = memberCache.get(classId);
39 if (hit && hit.until > Date.now()) return hit.value;
40 const entry = { until: Date.now() + FRESH_MS, value: fetchClassMembers(classId) };
41 memberCache.set(classId, entry);
42 void entry.value.then((members) => {
43 if (memberCache.get(classId) === entry) countCache.set(classId, { until: entry.until, value: Promise.resolve(members.length) });
44 }, () => {
45 if (memberCache.get(classId) === entry) memberCache.delete(classId);
46 });
47 return entry.value;
48}
49
50export function classMemberCount(classId: string): Promise<number> {
51 const roster = memberCache.get(classId);
52 if (roster && roster.until > Date.now()) return roster.value.then((members) => members.length);
53 const hit = countCache.get(classId);
54 if (hit && hit.until > Date.now()) return hit.value;
55 const entry = { until: Date.now() + FRESH_MS, value: getClassMembers(classId, { limit: 1 }).then((page) => page.total) };
56 countCache.set(classId, entry);
57 void entry.value.catch(() => {
58 if (countCache.get(classId) === entry) countCache.delete(classId);
59 });
60 return entry.value;
61}
62
63function students(): Promise<PersonRef[]> {
64 if (studentsCache && studentsCache.until > Date.now()) return studentsCache.value;
65 const entry = { until: Date.now() + FRESH_MS, value: getUserSearch("", undefined, "student").then((page) => page.items) };
66 studentsCache = entry;
67 void entry.value.catch(() => { if (studentsCache === entry) studentsCache = null; });
68 return entry.value;
69}
70
71/**
72 * Shared student list for teacher-facing reports: one name column and the classes it belongs to.
73 * With `cls` the read is scoped to that class: only its roster is fetched, and
74 * each row's `classes` is just that class. Without it every student and every
75 * class's members are read, as before.
76 */
77export async function getStudentDirectory(cls?: ClassGroup): Promise<StudentDirectoryRow[]> {
78 if (cls) return sortByClass((await readClassMembers(cls.id)).map((member) => ({ person: member.user, classes: [cls] })));
79 const [people, classes] = await Promise.all([students(), classList()]);
80 const byStudent = new Map<string, ClassGroup[]>();
81 const memberships = await mapConcurrent(classes, FAN_OUT_LIMIT, async (cls) => ({
82 cls, members: await readClassMembers(cls.id).catch(() => [] as ClassMember[]),
83 }));
84 for (const { cls, members } of memberships) {
85 for (const member of members) {
86 byStudent.set(member.user.id, [...(byStudent.get(member.user.id) ?? []), cls]);
87 }
88 }
89 return sortByClass(people.map((person) => ({ person, classes: byStudent.get(person.id) ?? [] })));
90}
91
92const collator = new Intl.Collator("tr", { numeric: true, sensitivity: "base" });
93
94/** Class order a school reads rosters in: grade (9 before 10), then the şube name. */
95export function compareClasses(a: ClassGroup, b: ClassGroup): number {
96 if (a.grade_level !== b.grade_level) return a.grade_level - b.grade_level;
97 return collator.compare(a.name, b.name);
98}
99
100/**
101 * Rows ordered class by class (9-A, 9-B, 10-A…) and by name inside a class.
102 * A student in several classes files under the first of them; students with
103 * no class come last. The row's own `classes` are put in the same order.
104 */
105export function sortByClass<Row extends { person: PersonRef; classes: ClassGroup[] }>(rows: Row[]): Row[] {
106 const ordered = rows.map((row) => ({ ...row, classes: [...row.classes].sort(compareClasses) }));
107 return ordered.sort((a, b) => {
108 const classA = a.classes[0];
109 const classB = b.classes[0];
110 if (classA && !classB) return -1;
111 if (!classA && classB) return 1;
112 if (classA && classB) {
113 const byClass = compareClasses(classA, classB);
114 if (byClass !== 0) return byClass;
115 }
116 return collator.compare(a.person.display_name || a.person.username, b.person.display_name || b.person.username);
117 });
118}