Skip to content

Commit

Permalink
Merge pull request #1469 from UniversityOfHelsinkiCS/fix-grouping-que…
Browse files Browse the repository at this point in the history
…stion

fix: Grouping filter not working for grouping question
  • Loading branch information
Veikkosuhonen authored Feb 4, 2025
2 parents 5d9a21c + b7e2c8d commit 7051381
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 103 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ const { teacher, student } = require('../fixtures/headers')

/// <reference types="Cypress" />

describe('Feedback count', () => {
describe('Feedback results', () => {
beforeEach(() => {
cy.createFeedbackTarget({ extraStudents: 5 })
cy.createFeedbackTarget({ extraStudents: 12 })
cy.setFeedbackActive()
cy.getTestFbtId().as('fbtId')
})
Expand Down Expand Up @@ -50,8 +50,8 @@ describe('Feedback count', () => {
.invoke('text')
.then(newCount => {
cy.get('@fbtPageInitialCount').then(initialCount => {
const newCountInt = parseInt(newCount.split("/")[0], 10)
const initialCountInt = parseInt(initialCount.split("/")[0], 10)
const newCountInt = parseInt(newCount.split('/')[0], 10)
const initialCountInt = parseInt(initialCount.split('/')[0], 10)
expect(newCountInt).to.eq(initialCountInt + 1)
})
})
Expand Down
17 changes: 10 additions & 7 deletions src/client/pages/FeedbackTarget/tabs/Results/GroupSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,21 @@ const GroupButton: React.FC<GroupButtonProps> = ({ option, onClick, value, ...pr

const buttonLabel = <Box p={1}>{option.name}</Box>

const hasTooltipContent = option.studentCount || option.teachers

const buttonChildren =
option.id !== 'ALL' ? (
option.id !== 'ALL' && hasTooltipContent ? (
<PaperTooltip
title={
<Box p="0.3rem">
<Typography variant="body2">
{t('common:studentCount')}:{' '}
<Typography component="span" color="textSecondary">
{option.studentCount}
{option.studentCount && (
<Typography variant="body2">
{t('common:studentCount')}:{' '}
<Typography component="span" color="textSecondary">
{option.studentCount}
</Typography>
</Typography>
</Typography>
)}
{option.teachers && (
<>
<Typography variant="body2" sx={{ mt: '0.3rem', mb: '0.2rem' }}>
Expand Down Expand Up @@ -105,7 +109,6 @@ const GroupSelector: React.FC<GroupSelectorProps> = ({
teachers: group.teachers,
studentCount: group.studentCount,
}))
.filter(group => group.studentCount && group.studentCount > 0 && group.studentCount < studentCount)
.sort(sortGroups)

const groupOptions: GroupOption[] = React.useMemo(() => {
Expand Down
22 changes: 21 additions & 1 deletion src/client/pages/FeedbackTarget/tabs/Results/Results.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import useIsMobile from '../../../../hooks/useIsMobile'
import useChartConfig from './QuestionResults/useChartConfig'
import { useFeedbackTargetContext } from '../../FeedbackTargetContext'
import GroupSelector from './GroupSelector'
import { getGroups } from './utils'
import useFeedbackTargetId from '../../useFeedbackTargetId'

const NotEnoughFeedbacks = ({ t }) => (
Expand Down Expand Up @@ -49,6 +48,26 @@ const OnlyTeacherAccess = ({ t }) => (
</Box>
)

/**
* Get the groups for the feedback target
* If the feedback target has a grouping question, use the options from that question
* Otherwise use the groups from the feedback target
*/
const getGroups = feedbackTarget => {
const groupQuestion = feedbackTarget.surveys.teacherSurvey?.questions?.find(q => q.secondaryType === 'GROUPING')

if (groupQuestion) {
return groupQuestion.data.options.map(opt => ({
id: opt.id,
name: opt.label,
teachers: feedbackTarget.groups?.find(g => g.id === opt.id)?.teachers,
// It would be nice to have studentCount here as well. Atm it's not available when using grouping question
}))
}

return feedbackTarget.groups ?? []
}

const FilterSection = ({ isLoading, groupId, setGroupId, feedbackResults, exportRef }) => {
const { ref, inView } = useInView({ initialInView: true })

Expand All @@ -59,6 +78,7 @@ const FilterSection = ({ isLoading, groupId, setGroupId, feedbackResults, export
const groups = getGroups(feedbackTarget)

const hasMultipleGroups = groups?.length > 1

const feedbacks = feedbackResults?.feedbacks
const groupsAvailable = feedbackResults?.groupsAvailable

Expand Down
12 changes: 0 additions & 12 deletions src/client/pages/FeedbackTarget/tabs/Results/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,6 @@ import { format, parseISO } from 'date-fns'
export const getCourseStartDate = feedbackTarget =>
format(parseISO(feedbackTarget.courseRealisation.startDate), 'yyyy-MM-dd')

export const getGroups = feedbackTarget => {
const groupQuestion = feedbackTarget.surveys.teacherSurvey?.questions?.find(q => q.secondaryType === 'GROUPING')
if (groupQuestion) {
return groupQuestion.data.options.map(opt => ({
id: opt.id,
name: opt.label,
}))
}

return feedbackTarget.groups ?? []
}

export const sortGroups = ({ name: nameA }, { name: nameB }) => {
// Helper function to check if a string contains any numbers
const containsNumber = str => /\d/.test(str)
Expand Down
33 changes: 33 additions & 0 deletions src/server/test/seedFeedbacks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import Feedback, { FeedbackData } from 'models/feedback'
import { FeedbackTarget, UserFeedbackTarget } from '../models'
import { TEST_COURSE_REALISATION_ID } from './testIds'

export const seedFeedbacks = async (feedbackDatas: FeedbackData[]) => {
const fbt = await FeedbackTarget.findOne({
where: {
courseRealisationId: TEST_COURSE_REALISATION_ID,
},
include: [
{
model: UserFeedbackTarget,
as: 'userFeedbackTargets',
},
],
})

await Promise.all(
// @ts-expect-error fbt is any
(fbt!.userFeedbackTargets as any[]).map(async (uft, idx) => {
if (idx >= feedbackDatas.length) return
const ftData = feedbackDatas[idx]
const ft = await Feedback.create({
data: ftData,
userId: uft.userId,
degreeStudyRight: null,
createdAt: new Date(),
updatedAt: new Date(),
})
await uft.update({ feedbackId: ft.id })
})
)
}
87 changes: 8 additions & 79 deletions src/server/test/testingController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const Router = require('express')
const _ = require('lodash')
const morgan = require('morgan')

const { FeedbackTarget, CourseRealisation, User } = require('../models')
const { FeedbackTarget } = require('../models')

const { ApplicationError } = require('../util/customErrors')
const { initTestSummary } = require('./seedSummary')
Expand All @@ -12,79 +12,6 @@ const { TEST_COURSE_REALISATION_ID } = require('./testIds')
const { inProduction } = require('../util/config')
const { getUniversitySurvey } = require('../services/surveys')

const updateCourseRealisation = async (req, res) => {
const { feedbackTargetId } = req.params

const feedbackTarget = await FeedbackTarget.findByPk(Number(feedbackTargetId))

if (!feedbackTarget) ApplicationError.NotFound(`FBT ${feedbackTargetId} not found`)

const courseRealisation = await CourseRealisation.findByPk(feedbackTarget.courseRealisationId)

if (!courseRealisation) ApplicationError.NotFound(`Course realisation ${courseRealisation.id} not found`)

const updates = _.pick(req.body, ['startDate', 'endDate'])

Object.assign(courseRealisation, updates)

await courseRealisation.save()

const { feedbackResponse, feedbackResponseEmailSent } = req.body

Object.assign(feedbackTarget, {
opensAt: updates.startDate,
closesAt: updates.endDate,
feedbackResponse,
feedbackResponseEmailSent,
})

await feedbackTarget.save()

return res.sendStatus(200)
}

const updateManyCourseRealisations = async (req, res) => {
const { user } = req

if (!user) throw new ApplicationError('No user found', 404)

const { feedbackTargetIds } = _.pick(req.body, ['feedbackTargetIds'])

const updates = _.pick(req.body, ['startDate', 'endDate'])

/* eslint-disable */
for (const id of feedbackTargetIds) {
const feedbackTarget = await FeedbackTarget.findByPk(Number(id))
if (!feedbackTarget) ApplicationError.NotFound(`FBT ${id} not found`)

const courseRealisation = await CourseRealisation.findByPk(feedbackTarget.courseRealisationId)
if (!courseRealisation) ApplicationError.NotFound(`CUR ${feedbackTarget.courseRealisationId} not found`)

Object.assign(courseRealisation, updates)

await courseRealisation.save()
}
/* eslint-enable */

return res.send(200)
}

const updateUser = async (req, res) => {
const { userId } = req.params

const user = await User.findByPk(userId)

if (!user) throw new ApplicationError('User not found', 404)

const updates = _.pick(req.body, ['employeeNumber', 'studentNumber', 'username'])

Object.assign(user, updates)

await user.save()

return res.send(200)
}

const initSummary = async (req, res) => {
await initTestSummary({ user: _.pick(req.body, ['hyPersonSisuId', 'uid']) })
return res.send(200)
Expand Down Expand Up @@ -129,6 +56,12 @@ const resetDb = async (req, res) => {
return res.send(204)
}

const seedFeedbacks = async (req, res) => {
const { feedbackDatas } = req.body
await seedFeedbacks(feedbackDatas)
return res.send(201)
}

const getTestFbtId = async (req, res) => {
const fbt = await FeedbackTarget.findOne({
where: {
Expand Down Expand Up @@ -157,14 +90,10 @@ router.use((_, __, next) => {
router.use(Router.json())
router.use(morgan('dev'))

router.put('/user/:userId', updateUser)

router.put('/courseRealisation/:feedbackTargetId', updateCourseRealisation)
router.put('/courseRealisations', updateManyCourseRealisations)

router.post('/init-summary', initSummary)
router.post('/seed-users', seedTestUsers2)
router.post('/seed-feedback-targets', seedFeedbackTargets)
router.post('/seed-feedbacks', seedFeedbacks)
router.post('/seed-organisation-correspondent', seedOrganisationCorrespondentHandler)
router.post('/reset-db', resetDb)

Expand Down

0 comments on commit 7051381

Please sign in to comment.