Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Internal: Fix vote handling & course ranking updates #6073

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 0 additions & 26 deletions assets/vue/services/trackCourseRankingService.js

This file was deleted.

100 changes: 100 additions & 0 deletions assets/vue/services/userRelCourseVoteService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import baseService from "./baseService"

/**
* Saves a new vote for a course in the catalog.
*
* @param {string} courseIri - IRI of the course
* @param {number} userId - ID of the user who votes
* @param {number} vote - Rating given by the user (1-5)
* @param {number} sessionId - Session ID (optional)
* @param {number} urlId - Access URL ID
* @returns {Promise<Object>}
*/
export async function saveVote({ courseIri, userId, vote, sessionId = null, urlId }) {
return await baseService.post("/api/user_rel_course_votes", {
course: courseIri,
user: `/api/users/${userId}`,
vote,
session: sessionId ? `/api/sessions/${sessionId}` : null,
url: `/api/access_urls/${urlId}`,
})
}

/**
* Updates an existing vote for a course.
*
* @param {string} iri - IRI of the vote to update
* @param {number} vote - New rating from the user (1-5)
* @param sessionId
* @param urlId
* @returns {Promise<Object>}
*/
export async function updateVote({ iri, vote, sessionId = null, urlId }) {
try {
if (!iri) {
throw new Error("Cannot update vote because IRI is missing.")
}

let payload = { vote }
if (sessionId) payload.session = `/api/sessions/${sessionId}`
if (urlId) payload.url = `/api/access_urls/${urlId}`

return await baseService.put(iri, payload)
} catch (error) {
console.error("Error updating user vote:", error)
throw error
}
}

/**
* Retrieves the user's vote for a specific course.
*
* @param {number} userId - ID of the user
* @param {number} courseId - ID of the course
* @param sessionId
* @param urlId
* @returns {Promise<Object|null>} - Returns the vote object if found, otherwise null
*/
export async function getUserVote({ userId, courseId, sessionId = null, urlId }) {
try {
let query = `/api/user_rel_course_votes?user.id=${userId}&course.id=${courseId}`
if (urlId) query += `&url.id=${urlId}`

// Remove session.id if null
if (sessionId) {
query += `&session.id=${sessionId}`
}

const response = await baseService.get(query)

if (response && response["hydra:member"] && response["hydra:member"].length > 0) {
return response["hydra:member"][0]
}

return null
// eslint-disable-next-line no-unused-vars
} catch (error) {
return null
}
}

/**
* Retrieves all votes of a user for different courses.
*
* @param {number} userId - User ID
* @param {number} urlId - Access URL ID
* @returns {Promise<Array>} - List of user votes
*/
export async function getUserVotes({ userId, urlId }) {
try {
let query = `/api/user_rel_course_votes?user.id=${userId}`
if (urlId) query += `&url.id=${urlId}`

const response = await baseService.get(query)

return response && response["hydra:member"] ? response["hydra:member"] : []
} catch (error) {
console.error("Error retrieving user votes:", error)
return []
}
}
97 changes: 60 additions & 37 deletions assets/vue/views/course/CatalogueCourses.vue
Original file line number Diff line number Diff line change
Expand Up @@ -132,16 +132,16 @@
<Column
:header="$t('Ranking')"
:sortable="true"
field="trackCourseRanking.realTotalScore"
field="userVote.vote"
style="min-width: 10rem; text-align: center"
>
<template #body="{ data }">
<Rating
:cancel="false"
:model-value="data.trackCourseRanking ? data.trackCourseRanking.realTotalScore : 0"
:model-value="data.userVote ? data.userVote.vote : 0"
:stars="5"
class="pointer-events: none"
@change="onRatingChange($event, data.trackCourseRanking, data.id)"
@change="onRatingChange($event, data.userVote, data.id)"
/>
</template>
</Column>
Expand Down Expand Up @@ -204,10 +204,9 @@ import { usePlatformConfig } from "../../store/platformConfig"
import { useSecurityStore } from "../../store/securityStore"

import courseService from "../../services/courseService"
import * as trackCourseRanking from "../../services/trackCourseRankingService"

import { useNotification } from "../../composables/notification"
import { useLanguage } from "../../composables/language"
import * as userRelCourseVoteService from "../../services/userRelCourseVoteService"

const { showErrorNotification } = useNotification()
const { findByIsoCode: findLanguageByIsoCode } = useLanguage()
Expand All @@ -227,31 +226,43 @@ async function load() {
try {
const { items } = await courseService.listAll()

courses.value = items.map((course) => ({
...course,
courseLanguage: findLanguageByIsoCode(course.courseLanguage)?.originalName,
}))
const votes = await userRelCourseVoteService.getUserVotes({
userId: currentUserId,
urlId: window.access_url_id,
})

courses.value = items.map((course) => {
const userVote = votes.find((vote) => vote.course === `/api/courses/${course.id}`)

return {
...course,
courseLanguage: findLanguageByIsoCode(course.courseLanguage)?.originalName,
userVote: userVote ? { ...userVote } : { vote: 0 },
}
})
} catch (error) {
showErrorNotification(error)
} finally {
status.value = false
}
}

async function updateRating(id, value) {
async function updateRating(voteIri, value) {
status.value = true

try {
const response = await trackCourseRanking.updateRanking({
iri: `/api/track_course_rankings/${id}`,
totalScore: value,
await userRelCourseVoteService.updateVote({
iri: voteIri,
vote: value,
sessionId: window.session_id,
urlId: window.access_url_id,
})

courses.value.forEach((course) => {
if (course.trackCourseRanking && course.trackCourseRanking.id === id) {
course.trackCourseRanking.realTotalScore = response.realTotalScore
}
})
courses.value = courses.value.map((course) =>
course.userVote && course.userVote["@id"] === voteIri
? { ...course, userVote: { ...course.userVote, vote: value } }
: course,
)
} catch (e) {
showErrorNotification(e)
} finally {
Expand All @@ -263,25 +274,47 @@ const newRating = async function (courseId, value) {
status.value = true

try {
const response = await trackCourseRanking.saveRanking({
totalScore: value,
courseIri: `/api/courses/${courseId}`,
const existingVote = await userRelCourseVoteService.getUserVote({
userId: currentUserId,
courseId,
sessionId: window.session_id || null,
urlId: window.access_url_id,
sessionId: 0,
})

courses.value.forEach((course) => {
if (course.id === courseId) {
course.trackCourseRanking = response
}
})
if (existingVote) {
await updateRating(existingVote["@id"], value)
} else {
await userRelCourseVoteService.saveVote({
vote: value,
courseIri: `/api/courses/${courseId}`,
userId: currentUserId,
sessionId: window.session_id || null,
urlId: window.access_url_id,
})
}

await load()
} catch (e) {
showErrorNotification(e)
} finally {
status.value = false
}
}

const onRatingChange = function (event, userVote, courseId) {
let { value } = event

if (value > 0) {
if (userVote && userVote["@id"]) {
updateRating(userVote["@id"], value)
} else {
newRating(courseId, value)
}
} else {
event.preventDefault()
}
}

const isUserInCourse = (course) => {
return course.users.some((user) => user.user.id === currentUserId)
}
Expand All @@ -296,16 +329,6 @@ const initFilters = function () {
}
}

const onRatingChange = function (event, trackCourseRanking, courseId) {
let { value } = event
if (value > 0) {
if (trackCourseRanking) updateRating(trackCourseRanking.id, value)
else newRating(courseId, value)
} else {
event.preventDefault()
}
}

load()
initFilters()
</script>
Expand Down
Loading
Loading