Skip to content

Commit

Permalink
Fix style issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Nephelite committed Dec 27, 2024
1 parent 54c0103 commit 9a17dc0
Show file tree
Hide file tree
Showing 14 changed files with 286 additions and 188 deletions.
17 changes: 13 additions & 4 deletions backend/controllers/assessmentAssignmentSetController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ export const createAssignmentSetController = async (
res.status(400).json({ error: error.message });
} else {
console.error('Error creating AssessmentAssignmentSet:', error);
res.status(500).json({ error: 'Failed to create AssessmentAssignmentSet' });
res
.status(500)
.json({ error: 'Failed to create AssessmentAssignmentSet' });
}
}
};
Expand Down Expand Up @@ -96,7 +98,9 @@ export const getAssignmentSetController = async (
res.status(404).json({ error: error.message });
} else {
console.error('Error fetching AssessmentAssignmentSet:', error);
res.status(500).json({ error: 'Failed to fetch AssessmentAssignmentSet' });
res
.status(500)
.json({ error: 'Failed to fetch AssessmentAssignmentSet' });
}
}
};
Expand Down Expand Up @@ -153,7 +157,9 @@ export const updateAssignmentSetController = async (
res.status(400).json({ error: error.message });
} else {
console.error('Error updating AssessmentAssignmentSet:', error);
res.status(500).json({ error: 'Failed to update AssessmentAssignmentSet' });
res
.status(500)
.json({ error: 'Failed to update AssessmentAssignmentSet' });
}
}
};
Expand Down Expand Up @@ -228,7 +234,10 @@ export const getUnmarkedAssignmentsByGraderIdController = async (
const userId = await getUserIdByAccountId(accountId);

try {
const assignments = await getUnmarkedAssignmentsByTAId(userId, assessmentId);
const assignments = await getUnmarkedAssignmentsByTAId(
userId,
assessmentId
);
res.status(200).json(assignments);
} catch (error) {
if (error instanceof NotFoundError) {
Expand Down
7 changes: 5 additions & 2 deletions backend/controllers/internalAssessmentController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ export const addQuestionsToAssessmentController = async (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const questions: any[] = [];

questionDatas.forEach(async (questionData) => {
questionDatas.forEach(async questionData => {
questions.push(
await addQuestionToAssessment(assessmentId, questionData, accountId)
);
Expand Down Expand Up @@ -343,7 +343,10 @@ export const deleteQuestionByIdController = async (
* - 401 Unauthorized: If authorization is missing.
* - 500 Internal Server Error: For any unknown errors.
*/
export const releaseInternalAssessment = async (req: Request, res: Response) => {
export const releaseInternalAssessment = async (
req: Request,
res: Response
) => {
try {
const { assessmentId } = req.params;
const accountId = await getAccountId(req);
Expand Down
5 changes: 4 additions & 1 deletion backend/routes/assessmentAssignmentSetRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ router.get('/:assessmentId/assignment-sets', getAssignmentSetController);
router.patch('/:assessmentId/assignment-sets', updateAssignmentSetController);

// TA Assignment Routes
router.get('/:assessmentId/assignment-sets/grader', getAssignmentsByGraderIdController);
router.get(
'/:assessmentId/assignment-sets/grader',
getAssignmentsByGraderIdController
);
router.get(
'/:assessmentId/assignment-sets/graderunmarked',
getUnmarkedAssignmentsByGraderIdController
Expand Down
69 changes: 38 additions & 31 deletions backend/services/assessmentAssignmentSetService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,19 +103,19 @@ export const createAssignmentSet = async (
: null;

if (assessment.granularity === 'team' && assignedTeams) {
const allTAs = assignedTeams.flatMap((at) => at.tas as User[]);
const allTAs = assignedTeams.flatMap(at => at.tas as User[]);
const uniqueTAIds = Array.from(
new Set(allTAs.map((id) => id.toString()))
).map((idStr) => new mongoose.Types.ObjectId(idStr));
new Set(allTAs.map(id => id.toString()))
).map(idStr => new mongoose.Types.ObjectId(idStr));

ensureAtLeastOneTA(assignedTeams, uniqueTAIds);
}

if (assessment.granularity === 'individual' && assignedUsers) {
const allTAIds = assignedUsers.flatMap((au) => au.tas as User[]);
const allTAIds = assignedUsers.flatMap(au => au.tas as User[]);
const uniqueTAIds = Array.from(
new Set(allTAIds.map((id) => id.toString()))
).map((idStr) => new mongoose.Types.ObjectId(idStr));
new Set(allTAIds.map(id => id.toString()))
).map(idStr => new mongoose.Types.ObjectId(idStr));

ensureAtLeastOneTA(assignedUsers, uniqueTAIds);
}
Expand Down Expand Up @@ -238,13 +238,13 @@ export const updateAssignmentSet = async (
}
}

assignmentSet.assignedTeams = assignedTeams.map((at) => ({
assignmentSet.assignedTeams = assignedTeams.map(at => ({
team: at.team,
tas: at.tas,
}));

const anyTeamWithoutTA = assignmentSet.assignedTeams.some(
(at) => at.tas.length === 0
at => at.tas.length === 0
);
if (anyTeamWithoutTA) {
throw new BadRequestError(
Expand All @@ -267,13 +267,13 @@ export const updateAssignmentSet = async (
}
}

assignmentSet.assignedUsers = assignedUsers.map((au) => ({
assignmentSet.assignedUsers = assignedUsers.map(au => ({
user: au.user,
tas: au.tas,
}));

const anyUserWithoutTA = assignmentSet.assignedUsers.some(
(au) => au.tas.length === 0
au => au.tas.length === 0
);
if (anyUserWithoutTA) {
throw new BadRequestError(
Expand Down Expand Up @@ -328,24 +328,24 @@ export const getAssignmentsByTAId = async (
// If assignedTeams exist, the granularity is 'team'
if (assignmentSet.assignedTeams) {
const teamIds: mongoose.Types.ObjectId[] = assignmentSet.assignedTeams
.filter((at) => at.tas.length > 0)
.map((at) => at.team as mongoose.Types.ObjectId);
.filter(at => at.tas.length > 0)
.map(at => at.team as mongoose.Types.ObjectId);

const teams = await Promise.all(
teamIds.map(async (teamId) => {
teamIds.map(async teamId => {
// NOTE: This lacks `await` in the original code, could cause concurrency issues, but left unchanged
return TeamModel.findById(teamId).populate('members');
})
);
return teams.filter(Boolean) as Team[];
} else {
// Otherwise, assignedUsers
const userIds: mongoose.Types.ObjectId[] = assignmentSet.assignedUsers!
.filter((au) => au.tas.length > 0)
.map((au) => au.user as mongoose.Types.ObjectId);
const userIds: mongoose.Types.ObjectId[] = assignmentSet
.assignedUsers!.filter(au => au.tas.length > 0)
.map(au => au.user as mongoose.Types.ObjectId);

const users = await Promise.all(
userIds.map(async (userId) => {
userIds.map(async userId => {
return UserModel.findById(userId);
})
);
Expand Down Expand Up @@ -393,43 +393,50 @@ export const getUnmarkedAssignmentsByTAId = async (
throw new NotFoundError('AssessmentAssignmentSet not found');
}

const submissions = await getSubmissionsByAssessmentAndUser(assessmentId, taId);
const submissions = await getSubmissionsByAssessmentAndUser(
assessmentId,
taId
);

// Extract user IDs from all submissions related to Team Member Selection Answer
const submittedUserIds = submissions.flatMap((sub) => {
const answer = sub.answers.find((ans) => ans.type === 'Team Member Selection Answer');
const submittedUserIds = submissions.flatMap(sub => {
const answer = sub.answers.find(
ans => ans.type === 'Team Member Selection Answer'
);
return (answer?.toObject() as TeamMemberSelectionAnswer).selectedUserIds;
});

if (assignmentSet.assignedTeams) {
const teamIds: mongoose.Types.ObjectId[] = assignmentSet.assignedTeams
.filter(
(at) =>
at =>
at.tas.length > 0 &&
submittedUserIds.every(
(uid) =>
!(at.team as Team).members?.find((member) => member._id.toString() === uid)
uid =>
!(at.team as Team).members?.find(
member => member._id.toString() === uid
)
)
)
.map((at) => at.team as mongoose.Types.ObjectId);
.map(at => at.team as mongoose.Types.ObjectId);

const teams = await Promise.all(
teamIds.map(async (teamId) => {
teamIds.map(async teamId => {
return TeamModel.findById(teamId).populate('members');
})
);
return teams.filter(Boolean) as Team[];
} else {
const userIds: mongoose.Types.ObjectId[] = assignmentSet.assignedUsers!
.filter(
(au) =>
const userIds: mongoose.Types.ObjectId[] = assignmentSet
.assignedUsers!.filter(
au =>
au.tas.length > 0 &&
submittedUserIds.every((uid) => uid !== au.user._id.toString())
submittedUserIds.every(uid => uid !== au.user._id.toString())
)
.map((au) => au.user as mongoose.Types.ObjectId);
.map(au => au.user as mongoose.Types.ObjectId);

const users = await Promise.all(
userIds.map(async (userId) => {
userIds.map(async userId => {
return UserModel.findById(userId);
})
);
Expand Down
41 changes: 23 additions & 18 deletions backend/services/internalAssessmentService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ import {
UndecidedQuestionModel,
} from '@models/QuestionTypes';
import { createAssignmentSet } from './assessmentAssignmentSetService';
import AssessmentResultModel, { AssessmentResult } from '@models/AssessmentResult';
import AssessmentResultModel, {
AssessmentResult,
} from '@models/AssessmentResult';
import { User } from '@models/User';

/**
Expand Down Expand Up @@ -317,7 +319,10 @@ export const addInternalAssessmentsToCourse = async (

// Attempt to create the assignment set
try {
await createAssignmentSet(assessment._id.toString(), teamSet._id.toString());
await createAssignmentSet(
assessment._id.toString(),
teamSet._id.toString()
);
} catch (error) {
console.error(
`Failed to create AssessmentAssignmentSet for assessment ${assessment._id}:`,
Expand Down Expand Up @@ -550,9 +555,8 @@ export const addQuestionToAssessment = async (
if (validQuestionData.isScored) {
// Assumes that the highest-value label is last in the array
addedMaxScore =
validQuestionData.labels![
validQuestionData.labels!.length - 1
].points;
validQuestionData.labels![validQuestionData.labels!.length - 1]
.points;
}
break;
case 'Short Response':
Expand Down Expand Up @@ -643,9 +647,8 @@ export const getQuestionsByAssessmentId = async (
throw new NotFoundError('Account not found');
}

const assessment = await InternalAssessmentModel.findById(assessmentId).populate(
'questions'
);
const assessment =
await InternalAssessmentModel.findById(assessmentId).populate('questions');
if (!assessment) {
throw new NotFoundError('Assessment not found');
}
Expand Down Expand Up @@ -702,10 +705,9 @@ export const updateQuestionById = async (
// Adjust scoring logic based on question type
switch (existingQuestion.type) {
case 'Multiple Choice':
currentScore = (existingQuestion as MultipleChoiceQuestion).options.reduce(
(acc, val) => (acc > val.points ? acc : val.points),
0
);
currentScore = (
existingQuestion as MultipleChoiceQuestion
).options.reduce((acc, val) => (acc > val.points ? acc : val.points), 0);
updatedScore = (updateData as MultipleChoiceQuestion).options.reduce(
(acc, val) => (acc > val.points ? acc : val.points),
0
Expand All @@ -717,7 +719,9 @@ export const updateQuestionById = async (
);
break;
case 'Multiple Response':
currentScore = (existingQuestion as MultipleResponseQuestion).options.reduce(
currentScore = (
existingQuestion as MultipleResponseQuestion
).options.reduce(
(acc, val) => (val.points > 0 ? acc + val.points : acc),
0
);
Expand Down Expand Up @@ -801,11 +805,12 @@ export const updateQuestionById = async (
);
break;
case 'Team Member Selection':
updatedQuestion = await TeamMemberSelectionQuestionModel.findByIdAndUpdate(
questionId,
updateData,
{ new: true }
);
updatedQuestion =
await TeamMemberSelectionQuestionModel.findByIdAndUpdate(
questionId,
updateData,
{ new: true }
);
break;
case 'NUSNET ID':
updatedQuestion = await NUSNETIDQuestionModel.findByIdAndUpdate(
Expand Down
9 changes: 6 additions & 3 deletions backend/services/submissionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,8 @@ export const createSubmission = async (
SaveAnswerModel = MultipleResponseAnswerModel;
break;
case 'Team Member Selection Answer':
question = await TeamMemberSelectionQuestionModel.findById(questionId);
question =
await TeamMemberSelectionQuestionModel.findById(questionId);
SaveAnswerModel = TeamMemberSelectionAnswerModel;
break;
case 'Date Answer':
Expand Down Expand Up @@ -733,7 +734,8 @@ export const updateSubmission = async (
savedAnswer = MultipleResponseAnswerModel.findById(answer.id);
break;
case 'Team Member Selection Answer':
question = await TeamMemberSelectionQuestionModel.findById(questionId);
question =
await TeamMemberSelectionQuestionModel.findById(questionId);
SaveAnswerModel = TeamMemberSelectionAnswerModel;
savedAnswer = TeamMemberSelectionAnswerModel.findById(answer.id);
break;
Expand Down Expand Up @@ -1136,7 +1138,8 @@ const calculateScaleScore = (
if (answerValue === next.value) return next.points;
if (answerValue > current.value && answerValue < next.value) {
// Linear interpolation
const slope = (next.points - current.points) / (next.value - current.value);
const slope =
(next.points - current.points) / (next.value - current.value);
const interpolatedPoints =
current.points + slope * (answerValue - current.value);
return interpolatedPoints;
Expand Down
5 changes: 4 additions & 1 deletion backend/test/controllers/codeAnalysisController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import {
getAllCodeAnalysisDataByCourse,
getAllCodeAnalysisDataByOrg,
} from '../../controllers/codeAnalysisController';
import { MissingAuthorizationError, NotFoundError } from '../../services/errors';
import {
MissingAuthorizationError,
NotFoundError,
} from '../../services/errors';
import * as codeAnalysisService from '../../services/codeAnalysisService';
import * as auth from '../../utils/auth';

Expand Down
4 changes: 1 addition & 3 deletions backend/test/controllers/submissionController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,9 +215,7 @@ describe('submissionController', () => {
jest
.spyOn(submissionService, 'getSubmissionsByAssessmentAndUser')
.mockResolvedValue(mockSubmissions as any);
jest
.spyOn(AccountModel, 'findById')
.mockResolvedValue(account);
jest.spyOn(AccountModel, 'findById').mockResolvedValue(account);

await getUserSubmissions(req, res);

Expand Down
Loading

0 comments on commit 9a17dc0

Please sign in to comment.