Skip to content
Merged
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
89 changes: 45 additions & 44 deletions my-app/firebase.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,50 +126,6 @@ export function syncScrollPositionToFirebase(model, containerRef) {
containerRef.current?.removeEventListener("scroll", handleScroll);
}

function startAverageRatingListener(model) {
const coursesRef = ref(db, "reviews");

// Step 1: One-time fetch if model.avgRating is not initialized
if (!model.avgRating || Object.keys(model.avgRating).length === 0) {
get(coursesRef).then((snapshot) => {
if (!snapshot.exists()) return;

const initialRatings = {};

snapshot.forEach((courseSnapshot) => {
const courseCode = courseSnapshot.key;
const avgRating = courseSnapshot.child("avgRating").val();

if (typeof avgRating === "number") {
initialRatings[courseCode] = avgRating;
}
});

model.setAverageRatings(initialRatings);
});
}

// Step 2: listener for each courses avgRating
onChildAdded(coursesRef, (courseSnapshot) => {
const courseCode = courseSnapshot.key;
const avgRatingRef = ref(db, `reviews/${courseCode}/avgRating`);

onValue(avgRatingRef, (ratingSnapshot) => {
if (!ratingSnapshot.exists()) return;

const rating = ratingSnapshot.val();

if (typeof rating === "number") {
model.updateAverageRating(courseCode, rating);
}
});
});

onChildRemoved(coursesRef, (courseSnapshot) => {
const courseCode = courseSnapshot.key;
model.updateAverageRating(courseCode, null);
});
}


function saveCoursesToCache(courses, timestamp) {
Expand Down Expand Up @@ -348,6 +304,51 @@ export async function addReviewForCourse(courseCode, review) {
}
}

function startAverageRatingListener(model) {
const coursesRef = ref(db, "reviews");

// Step 1: One-time fetch if model.avgRating is not initialized
if (!model.avgRating || Object.keys(model.avgRating).length === 0) {
get(coursesRef).then((snapshot) => {
if (!snapshot.exists()) return;

const initialRatings = {};

snapshot.forEach((courseSnapshot) => {
const courseCode = courseSnapshot.key;
const avgRating = courseSnapshot.child("avgRating").val();

if (avgRating && Array.isArray(avgRating)) {
initialRatings[courseCode] = avgRating;
}
});

model.setAverageRatings(initialRatings);
});
}

// Step 2: listener for each courses avgRating
onChildAdded(coursesRef, (courseSnapshot) => {
const courseCode = courseSnapshot.key;
const avgRatingRef = ref(db, `reviews/${courseCode}/avgRating`);

onValue(avgRatingRef, (ratingSnapshot) => {
if (!ratingSnapshot.exists()) return;

const rating = ratingSnapshot.val();

if (typeof rating === "number") {
model.updateAverageRating(courseCode, rating);
}
});
});

onChildRemoved(coursesRef, (courseSnapshot) => {
const courseCode = courseSnapshot.key;
model.updateAverageRating(courseCode, null);
});
}

export async function getReviewsForCourse(courseCode) {
const reviewsRef = ref(db, `reviews/${courseCode}`);
const snapshot = await get(reviewsRef);
Expand Down
41 changes: 32 additions & 9 deletions my-app/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,26 +20,49 @@ exports.updateCourseAvgRating = functions.https.onCall(async (data, context) =>
}

// Compute average from overallRating
let total = 0;
let count = 0;
let totalOverall = 0;
let countOverall = 0;
let totalDifficulty = 0;
let countDifficulty = 0;
let totalProfessor = 0;
let countProfessor = 0;

Object.values(reviews).forEach(review => {
if (typeof review.overallRating === 'number') {
total += review.overallRating;
count++;
totalOverall += review.overallRating;
countOverall++;
}
if (typeof review.difficultyRating === 'number') {
totalDifficulty += review.difficultyRating;
countDifficulty++;
}
if (typeof review.professorRating === 'number') {
totalProfessor += review.professorRating;
countProfessor++;
}
});

if (count === 0) {
let avgRatingOverall = 0;
let avgRatingDifficulty = 0;
let avgRatingProfessor = 0;

if (!(countOverall === 0)) {
avgRatingOverall = parseFloat((totalOverall / countOverall).toFixed(2));
}
if (!(countDifficulty === 0)) {
avgRatingDifficulty = parseFloat((totalDifficulty / countDifficulty).toFixed(2));
}
if (!(countProfessor === 0)) {
avgRatingProfessor = parseFloat((totalProfessor / countProfessor).toFixed(2));
}
if (countOverall === 0 && countDifficulty === 0 && countProfessor === 0) {
throw new functions.https.HttpsError('failed-precondition', 'No valid ratings');
}

const avgRating = parseFloat((total / count).toFixed(2));

// Update the avgRating in reviews
await db.ref(`reviews/${courseCode}`).update({ avgRating });
await db.ref(`reviews/${courseCode}`).update({"avgRating" :[avgRatingOverall, avgRatingDifficulty, avgRatingProfessor] } );

return { success: true, avgRating };
return { success: true, "avgRating": [avgRatingOverall, avgRatingDifficulty, avgRatingProfessor] };
} catch (error) {
throw new functions.https.HttpsError('internal', error.message);
}
Expand Down
2 changes: 1 addition & 1 deletion my-app/src/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const model = {
courses: [],
departments : [],
locations: [],
// indexes: 0 -> overall rating; 1 -> difficulty; 2->teacher rating
avgRatings: [],
/* courses the user selected as their favourite */
favourites: [],
Expand Down Expand Up @@ -296,7 +297,6 @@ export const model = {
if (isOpen) {
window.history.pushState({}, '', '/' + this.selectedCourse.code);
}
console.log("POPOPOOPOPOOOOOOP")
if (!isOpen) {
let current_url = window.location.href;
console.log(current_url);
Expand Down