Commit 23a768da authored by Yechang's avatar Yechang
Browse files

perf: grade book

parent 0f233d59
Loading
Loading
Loading
Loading
Loading
+1 −94
Original line number Diff line number Diff line
@@ -12,28 +12,6 @@ export const load = (async ({ parent, locals }) => {
	const data: PageParentData = await parent();
	const { currentClass } = data;


	// get all students in this class
	const students = await db.classesOnUsers.findMany({
		where: {
			classId: currentClass.id,
			role: 'STUDENT'
		},
		include: {
			user: {
				select: {
					sustechId: true
				},
			}
		},
		orderBy: {
			user: {
				sustechId: 'asc'
			}
		}
	})
	const studentIds = students.map(student => student.user.sustechId).filter(id => !_.isNil(id))

	// get all entries with groups and records
	const entries = await db.gradeEntry.findMany({
		where: {
@@ -41,16 +19,6 @@ export const load = (async ({ parent, locals }) => {
		},
		include: {
			groups: {
				include: {
					records: {
						include: {
							student: {
								select: { sustechId: true }
							}
						},
						orderBy: { id: 'asc' }
					}
				},
				orderBy: {
					index: 'asc'
				}
@@ -58,75 +26,14 @@ export const load = (async ({ parent, locals }) => {
		},
	});

	const calculated = entries.map((entry) => {
		const groups = entry.groups.map((group) => {
			const { strategy, records } = group;
			const strategyFn = {
				MAX: _.max<number>,
				MIN: _.min<number>,
				LAST: _.last<number>
			}[strategy]


			const userRecords = _.groupBy(records.filter(record => !_.isNil(record.student.sustechId)), record => record.student.sustechId)
			const userScores = _.entries(userRecords).map(([sustechId, records]) => {
				const score = strategyFn(records.map((record) => record.grade)) || 0;
				return {
					[sustechId]: {
						[group.name]: score
					}
				}
			})

			return {
				...group,
				userScores
			};
		});

		const empty = _.fromPairs(groups.map(group => { return [group.name, 0] }))
		const empties = studentIds.map(studentId => ({
			[studentId]: empty
		}))

		const users: {
			[sustechId: string]: {
				[groupName: string]: number
			}
		} = _.merge(empties, ...groups.map(group => group.userScores))


		const weightedScores = _.entries(users).map(([sustechId, scores]) => {
			const weightedScore = _.sum(
				groups.map((group) => {
					const s: number = scores[group.name] || 0;
					return (s * group.proportion) / 100;
				}),
			);
			return {
				[sustechId]: {
					weightedScore
				}
			}
		})

		const usersWithWeightedScore = _.merge(users, weightedScores)


		return {
			...entry,
			users: usersWithWeightedScore
		};
	});

	return {
		entries: calculated
		entries
	} satisfies {
		entries: Array<{
			name: string,
			title: string,
			groups: Array<{}>
			users: Array<{}>
		}>
	};
}) satisfies PageServerLoad;